I am busy writing an API in Symfony2. One of the API functions is to return all the users (not uncommon). Obviously before I return a list of users I must ensure that a user is logged in and has at least ROLE_ADMIN before returning the users. Currently I am doing it like this:
public function getAllUsersAction()
{
$user = $this->getUser();
if ($user == null) die("Unauthorized");
$userRoles = $user->getRoles();
$bAuthorized = false;
foreach ($userRoles as $userRole)
if ($userRole->getRole() == "ROLE_ADMIN" || $userRole->getRole() == "ROLE_SUPER_ADMIN")
$bAuthorized = true;
if ($bAuthorized) return createJsonResponse($this->getDoctrine()->getRepository('PmbLicensingBundle:User')->findAll());
else die("Unauthorized");
}
My question is simply whether there is an easier way in Symfony to determine whether a user is logged in and has ROLE_ADMIN than the process that I am taking, as it seems to be quite lumbersome.