public function before(Request $request, Application $app, $roleRoute = null)
{
// Start the 'stopwatch' for the profiler.
$app['stopwatch']->start('bolt.backend.before');
$route = $request->get('_route');
// Initial event
$event = new AccessControlEvent($request);
$app['dispatcher']->dispatch(AccessControlEvents::ACCESS_CHECK_REQUEST, $event);
// Handle the case where the route doesn't equal the role.
if ($roleRoute === null) {
$roleRoute = $this->getRoutePermission($route);
} else {
$roleRoute = $this->getRoutePermission($roleRoute);
}
// Check for first user set up
$response = $this->checkFirstUser($app, $route);
if ($response !== true) {
return $response;
}
// If we're resetting passwords, we have nothing more to check
if ($route === 'resetpassword' || $route === 'login' || $route === 'postLogin' || $route === 'logout') {
return null;
}
// Confirm the user is enabled or bounce them
$sessionUser = $this->getUser();
if ($sessionUser && !$sessionUser->getEnabled()) {
$app['logger.flash']->error(Trans::__('general.phrase.login-account-disabled'));
$event->setReason(AccessControlEvents::FAILURE_DISABLED);
$event->setUserName($sessionUser->getUsername());
$app['dispatcher']->dispatch(AccessControlEvents::ACCESS_CHECK_FAILURE, $event);
return $this->redirectToRoute('logout');
} elseif ($sessionUser) {
$event->setUserName($sessionUser->getUsername());
}
// Check if there's at least one 'root' user, and otherwise promote the current user.
$this->users()->checkForRoot();
// Most of the 'check if user is allowed' happens here: match the current route to the 'allowed' settings.
$authCookie = $request->cookies->get($this->app['token.authentication.name']);
if ($authCookie === null || !$this->accessControl()->isValidSession($authCookie)) {
// Don't redirect on ajaxy requests (eg. when Saving a record), but send an error
// message with a `500` status code instead.
if ($request->isXmlHttpRequest()) {
$response = ['error' => ['message' => Trans::__('general.phrase.redirect-detected')]];
return new JsonResponse($response, 500);
}
$app['logger.flash']->info(Trans::__('general.phrase.please-logon'));
return $this->redirectToRoute('login');
}
if (!$this->isAllowed($roleRoute)) {
$app['logger.flash']->error(Trans::__('general.phrase.access-denied-privilege-view-page'));
$event->setReason(AccessControlEvents::FAILURE_DENIED);
$app['dispatcher']->dispatch(AccessControlEvents::ACCESS_CHECK_FAILURE, $event);
return $this->redirectToRoute('dashboard');
}
// Success!
$app['dispatcher']->dispatch(AccessControlEvents::ACCESS_CHECK_SUCCESS, $event);
// Stop the 'stopwatch' for the profiler.
$app['stopwatch']->stop('bolt.backend.before');
return null;
}