diff --git a/src/Controller/Api/ApiUserController.php b/src/Controller/Api/ApiUserController.php new file mode 100644 index 0000000..f9b1aab --- /dev/null +++ b/src/Controller/Api/ApiUserController.php @@ -0,0 +1,41 @@ +denyAccessUnlessGranted('view', $user); + return new JsonResponse($this->serialize($user), 200); + } + + protected function serialize(User $user) + { + $encoders = [new XmlEncoder(), new JsonEncoder()]; + $normalizers = [new ObjectNormalizer()]; + + $serializer = new Serializer($normalizers, $encoders); + + $json = $serializer->serialize($user, 'json'); + + return $json; + } +} diff --git a/src/Security/UserVoter.php b/src/Security/UserVoter.php new file mode 100644 index 0000000..4296ddd --- /dev/null +++ b/src/Security/UserVoter.php @@ -0,0 +1,84 @@ +decisionManager = $decisionManager; + } + + protected function supports($attribute, $subject) + { + // if the attribute isn't one we support, return false + if (!in_array($attribute, array(self::VIEW, self::EDIT))) { + return false; + } + + // only vote on User objects inside this voter + if (!$subject instanceof User) { + return false; + } + + return true; + } + + protected function voteOnAttribute($attribute, $subject, TokenInterface $token) + { + $user = $token->getUser(); + + if (!$user instanceof User) { + // the user must be logged in; if not, deny access + return false; + } + + // ROLE_SUPER_ADMIN can do anything! The power! + if ($this->decisionManager->decide($token, array('ROLE_ADMIN'))) { + return true; + } + + // you know $subject is a User object, thanks to supports + /** @var User $userSubject */ + $userSubject = $subject; + + switch ($attribute) { + case self::VIEW: + return $this->canView($userSubject, $user); + case self::EDIT: + return $this->canEdit($userSubject, $user); + } + + throw new \LogicException('This code should not be reached!'); + } + + private function canView(User $userSubject, User $user) + { + // if they can edit, they can view + if ($this->canEdit($userSubject, $user)) { + return true; + } + + // the User object could have, for example, a method isPrivate() + // that checks a boolean $private property + return $user === $userSubject; + } + + private function canEdit(User $userSubject, User $user) + { + // this assumes that the data object has a getOwner() method + // to get the entity of the user who owns this data object + return $user === $userSubject; + } +} \ No newline at end of file