/**
  * @param string $setting
  * @param UserInterface $user
  * @return mixed
  */
 public function getUserSetting($setting, UserInterface $user = null)
 {
     if (!$user) {
         $user = $this->authenticationService->getIdentity();
     }
     return $this->userSettingsService->getValue($setting, $user);
 }
 public function __invoke(Request $req, Response $res)
 {
     $school = $req->getAttribute('school');
     if ($req->isPost()) {
         $this->appFormInputFilter->setData(array_merge($req->getParams(), ['school_id' => $school->id, 'submitted_by' => $this->authService->getIdentity()->mail]));
         $isValid = $this->appFormInputFilter->isValid();
         if ($isValid) {
             $data = $this->appFormInputFilter->getValues();
             $appForm = $this->appFormService->submit($data);
             $_SESSION['applicationForm']['appForm'] = $appForm;
             $res = $res->withRedirect($this->successUrl);
             return $res;
         }
         $this->view['form'] = ['is_valid' => $isValid, 'values' => $this->appFormInputFilter->getValues(), 'raw_values' => $this->appFormInputFilter->getRawValues(), 'messages' => $this->appFormInputFilter->getMessages()];
     }
     $loadForm = (bool) $req->getParam('load', false);
     $this->view['choose'] = !$loadForm && !$req->isPost();
     if (!$req->isPost() && $loadForm) {
         if (null !== ($appForm = $this->appFormService->findSchoolApplicationForm($school->id))) {
             $this->view['form'] = ['values' => $appForm];
         }
     }
     $labs = $this->labService->getLabsBySchoolId($school->id);
     $res = $this->view->render($res, 'application_form/form.twig', ['lab_choices' => array_map(function ($lab) {
         return ['value' => $lab['id'], 'label' => $lab['name']];
     }, $labs), 'type_choices' => array_map(function ($category) {
         return ['value' => $category['id'], 'label' => $category['name']];
     }, $this->assetsService->getAllItemCategories())]);
     return $res;
 }
 /**
  * 
  * @return Response
  */
 public function indexAction()
 {
     if (!is_null($this->identity())) {
         $this->authenticationService->clearIdentity();
     }
     return $this->redirect()->toRoute($this->loginRoute);
 }
 /**
  * Handles redirects in case of dispatch errors caused by unauthorized access
  *
  * @param MvcEvent $event
  * @return void
  */
 public function onError(MvcEvent $event)
 {
     if (!$event->getRequest() instanceof HttpRequest || !($routeMatch = $event->getRouteMatch())) {
         return;
     }
     if (null === $this->redirectUri) {
         if (null === $this->redirectRoute) {
             if ($this->authenticationService->hasIdentity()) {
                 $this->setRedirectRoute($this->options->getAuthenticatedIdentityRedirectRoute());
             } else {
                 $this->setRedirectRoute($this->options->getUnauthenticatedIdentityRedirectRoute());
             }
         }
         if (!($this->redirectRoute && $this->redirectRoute !== $routeMatch->getMatchedRouteName())) {
             return parent::onError($event);
         }
         $params = ['name' => $this->redirectRoute];
         if ($this->options->getUseRedirectParameter()) {
             $redirectKey = $this->options->getRedirectKey();
             $params['query'][$redirectKey] = $event->getRequest()->getUriString();
         }
         $this->setRedirectUri($event->getRouter()->assemble([], $params));
     }
     $response = $event->getResponse() ?: new HttpResponse();
     $response->getHeaders()->addHeaderLine('Location', $this->redirectUri);
     $response->setStatusCode(302);
     $event->setResponse($response);
 }
Beispiel #5
0
 /**
  * Main method to check authorization
  *
  * @param MvcEvent $e
  *
  * @return ResponseInterface
  */
 public function checkAccess(MvcEvent $e)
 {
     /** @var Response $response */
     $response = $e->getResponse();
     /** @var UserEntity $identity */
     $identity = $this->authService->getIdentity();
     $role = $identity ? $identity->getRole() : UserEntity::ROLE_GUEST;
     list($moduleName, $controllerName, $actionName) = $this->namesResolver->resolve($e);
     if ($this->acl->isAllowed($role, $moduleName, $controllerName . ':' . $actionName)) {
         $e->getViewModel()->setVariable('acl', $this->acl);
         return $response;
     }
     $this->getEventManager()->trigger(self::EVENT_IS_NOT_ALLOWED, $e->getTarget());
     $router = $e->getRouter();
     if ($role !== UserEntity::ROLE_GUEST) {
         $url = $router->assemble(['controller' => 'no-access'], ['name' => 'auth/default']);
     } else {
         $url = $router->assemble(['controller' => 'login'], ['name' => 'access/default']);
     }
     $response->setStatusCode(302);
     $response->getHeaders()->clearHeaders();
     $response->getHeaders()->addHeaderLine('Location', $url);
     $e->stopPropagation();
     return $response;
 }
Beispiel #6
0
 /**
  * @private
  * @param  MvcEvent $event
  * @return void
  */
 public function onError(MvcEvent $event)
 {
     // Do nothing if no error or if response is not HTTP response
     if (!$event->getParam('exception') instanceof UnauthorizedExceptionInterface || $event->getResult() instanceof HttpResponse || !$event->getResponse() instanceof HttpResponse) {
         return;
     }
     $router = $event->getRouter();
     if ($this->authenticationService->hasIdentity()) {
         if (!$this->options->getRedirectWhenConnected()) {
             return;
         }
         $redirectRoute = $this->options->getRedirectToRouteConnected();
     } else {
         $redirectRoute = $this->options->getRedirectToRouteDisconnected();
     }
     $uri = $router->assemble([], ['name' => $redirectRoute]);
     if ($this->options->getAppendPreviousUri()) {
         $redirectKey = $this->options->getPreviousUriQueryKey();
         $previousUri = $event->getRequest()->getUriString();
         $uri = $router->assemble([], ['name' => $redirectRoute, 'query' => [$redirectKey => $previousUri]]);
     }
     $response = $event->getResponse() ?: new HttpResponse();
     $response->getHeaders()->addHeaderLine('Location', $uri);
     $response->setStatusCode(302);
     $event->setResponse($response);
     $event->setResult($response);
 }
 /**
  * @todo Remove the AnonymousIdentity instantiation. This belongs in an Authentication Adapter
  * @return Identity
  */
 public function getIdentity()
 {
     $identity = $this->authenticationService->getIdentity();
     if (is_null($identity)) {
         $identity = new AnonymousIdentity();
     }
     return $identity;
 }
 /**
  * @return Context
  */
 public function createContext()
 {
     $context = new Context();
     $token = $this->tokenStorage->getIdentity();
     if (null !== $token) {
         $context->set('username', $this->tokenStorage->getIdentity());
     }
     return $context;
 }
Beispiel #9
0
 public function __invoke(Request $req, Response $res)
 {
     $result = $this->authService->authenticate();
     if (!$result->isValid()) {
         $this->flash->addMessage('danger', reset($result->getMessages()));
         return $res->withRedirect($this->loginUrl);
     }
     return $res->withRedirect($this->successUrl);
 }
Beispiel #10
0
 public function __invoke(ServerRequestInterface $req, Response $res)
 {
     if ($this->authService->hasIdentity()) {
         $identity = $this->authService->getIdentity();
         $events = $this->events;
         $this->authService->clearIdentity();
         $events('trigger', 'logout', $identity, $this->redirectUrl);
     }
     return $res->withRedirect($this->redirectUrl);
 }
Beispiel #11
0
 public function assert(Acl $acl, RoleInterface $role = null, ResourceInterface $resource = null, $privilege = null)
 {
     $identity = $this->authService->getIdentity();
     $user = R::load('user', $identity->id);
     if (!($school = $user->school)) {
         return false;
     }
     $appForm = $this->appFormService->findSchoolApplicationForm($school->id);
     return null === $appForm;
 }
 /**
  * Retrieve the current identity, if any.
  *
  * If none is present, returns null.
  *
  * @return mixed|null
  * @throws Exception\RuntimeException
  */
 public function __invoke()
 {
     if (!$this->authenticationService instanceof AuthenticationServiceInterface) {
         throw new Exception\RuntimeException('No AuthenticationServiceInterface instance provided; cannot lookup identity');
     }
     if (!$this->authenticationService->hasIdentity()) {
         return;
     }
     return $this->authenticationService->getIdentity();
 }
Beispiel #13
0
 public function login(InputFilterInterface $filter)
 {
     if (!$filter->isValid()) {
         throw new \LogicException('Form is not valid');
     }
     $this->authAdapter->setIdentity($filter->getValue('login'));
     $this->authAdapter->setCredential($filter->getValue('password'));
     $result = $this->authenticationService->authenticate($this->authAdapter);
     return $result->isValid();
 }
Beispiel #14
0
    /**
     * Attempt to authenticate the current request.
     *
     * @param Request $request
     * @param Response $response
     * @param MvcAuthEvent $mvcAuthEvent
     * @return false|IdentityInterface False on failure, IdentityInterface
     *     otherwise
     */
    public function authenticate(Request $request, Response $response, MvcAuthEvent $mvcAuthEvent)
    {
        $this->httpAuth->setRequest($request);
        $this->httpAuth->setResponse($response);

        $result = $this->authenticationService->authenticate($this->httpAuth);
        $mvcAuthEvent->setAuthenticationResult($result);

        if (! $result->isValid()) {
            return false;
        }

        $resultIdentity = $result->getIdentity();

        // Pass fully discovered identity to AuthenticatedIdentity instance
        $identity = new Identity\AuthenticatedIdentity($resultIdentity);

        // But determine the name separately
        $name = $resultIdentity;
        if (is_array($resultIdentity)) {
            $name = isset($resultIdentity['username'])
                ? $resultIdentity['username']
                : (string) array_shift($resultIdentity);
        }
        $identity->setName($name);

        return $identity;
    }
 /**
  * Delegate checking of user credentials to ZfcUser's onboard adapter chain
  *
  * @param  string  $username
  * @param  string  $password
  * @return boolean
  */
 public function checkUserCredentials($username, $password)
 {
     $request = new \Zend\Http\Request();
     $request->getPost()->set('identity', $username);
     $request->getPost()->set('credential', $password);
     $adapterResult = $this->authAdapter->prepareForAuthentication($request);
     if ($adapterResult instanceof \Zend\Stdlib\ResponseInterface) {
         return false;
     }
     $authResult = $this->auth->authenticate($this->authAdapter);
     if (!$authResult->isValid()) {
         $this->authAdapter->resetAdapters();
         return false;
     }
     return true;
 }
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null)
 {
     $registration = $this->service->registrationPath();
     $logout = $this->service->logoutPath();
     $login = $this->service->loginPath();
     $base = $this->service->basePath();
     $uri = $request->getUri();
     $path = $uri->getPath();
     if ($path === $logout) {
         $this->service->clearIdentity();
         // including the user session
         return $this->redirectTo($uri->withPath($login));
     }
     // Disallow to render the view (by default) if not authenticated
     if (!$this->service->hasIdentity()) {
         switch ($path) {
             case $login:
                 return $next($request, $response);
             case $registration:
                 return $next($request, $response);
             default:
                 return $this->redirectTo($uri->withPath($login));
         }
     }
     switch ($path) {
         case $login:
             return $this->redirectTo($uri->withPath($base));
         case $registration:
             return $this->redirectTo($uri->withPath($base));
     }
     return $next($request, $response);
 }
Beispiel #17
0
 public function __invoke(Request $req, Response $res)
 {
     $identity = $this->authService->getIdentity();
     if (null === $identity) {
         return $res;
     }
     $user = R::load('user', $identity->id);
     if (!$user->school_id) {
         return $res;
     }
     $school_id = $user->school_id;
     $sync = $this->syncFromInventory;
     $result = $sync($school_id);
     if (false === $result) {
         return $res->withStatus(500);
     }
     return $res->withJson($result);
 }
 /**
  * @dataProvider dataForPrepareExceptionViewModel
  */
 public function testPrepareExceptionViewModel($error, $result, $exception, $hasIdentity, $isActive, $expectedSetResultCalled)
 {
     $this->event->expects($this->any())->method('getError')->willReturn($error);
     $this->event->expects($this->any())->method('getResult')->willReturn($result);
     $this->event->expects($this->any())->method('getParam')->with($this->equalTo('exception'))->willReturn($exception);
     $this->auth->expects($this->any())->method('hasIdentity')->willReturn($hasIdentity);
     $this->user->expects($this->any())->method('isActive')->willReturn($isActive);
     $this->event->expects($this->exactly($expectedSetResultCalled))->method('setResult');
     $this->listener->prepareExceptionViewModel($this->event);
 }
Beispiel #19
0
 public function __invoke(Request $req, Response $res, callable $next)
 {
     $res = $next($req, $res);
     $identity = $this->authService->getIdentity();
     if (null === $identity) {
         return $res;
     }
     $user = R::load('user', $identity->id);
     if (!$user->school_id) {
         return $res;
     }
     $school_id = $user->school_id;
     if (0 < count($this->labService->getLabsBySchoolId($school_id))) {
         return $res;
     }
     $sync = $this->syncFromInventory;
     $sync($school_id);
     return $res;
 }
 public function testValidLogin()
 {
     $request = new Request();
     $response = new Response();
     $serieTokenInCookie = new SerieToken(1, 'abc', 'def');
     $newSerie = new SerieToken(1, 'abc', 'ghi');
     // Assume valid user
     $this->userMapper->expects($this->once())->method('findById')->will($this->returnValue($this->getMock('ZfcUser\\Entity\\UserInterface')));
     // Request contains cookie
     $this->cookieService->expects($this->once())->method('read')->with($request, $response)->will($this->returnValue($serieTokenInCookie));
     // Response contains updated cookie
     $this->cookieService->expects($this->once())->method('writeSerie')->with($response, $newSerie);
     $newSerie->setExpiresAt(new \DateTime('+3 days'));
     $this->rememberMeService->expects($this->once())->method('getNextInSerie')->with($serieTokenInCookie)->will($this->returnValue($newSerie));
     $this->authService->expects($this->once())->method('authenticate');
     $eventManager = $this->getMock('Zend\\EventManager\\EventManagerInterface');
     $this->service->setEventManager($eventManager);
     $eventManager->expects($this->once())->method('trigger')->with('login', $this->service, ['token' => $newSerie]);
     $this->service->loginFrom($request, $response);
 }
 /**
  * Determines whether or not user has access to requested resource.
  *
  * @param ServerRequestInterface $request
  * @param ResponseInterface      $response
  * @param callable               $next
  *
  * @return ResponseInterface
  */
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
 {
     $route = $request->getAttribute('route', null);
     if ($route === null) {
         // User likely accessing a nonexistent route. Calling next middleware.
         return $next($request, $response);
     }
     $role = $this->getRole($this->auth->getIdentity());
     $resource = $route->getPattern();
     /*
     * THIS BUG HAPPENED WHEN ROUTE DID NOT SET ->allow([roles])
     * Hope fix problems when an optional / maybe followed by arguments
     * Route::group('/venues', function (){
     				Route::get('/', ...
     				Route::get('[/{id:[0-9]+}]', ...
     				
     		   dont work for groups that do not have a sub route like '/'
     */
     //         $resource = preg_replace("|\[\/[^\[].*\]|", "/", $route->getPattern());
     //         $resource = $route->getIdentifier();
     $privilege = $request->getMethod();
     //         $isAllowed = false;
     //         if(!$this->acl && $route instanceof AuthorizableRoute){
     //         	$route->getAcl()->isAllowed($role, $resource, $privilege);
     //         } else {
     // 	        $this->acl->isAllowed($role, $resource, $privilege);
     //         }
     // 		var_dump($this->acl);
     $isAllowed = $this->acl->isAllowed($role, $resource, $privilege);
     $isAuthenticated = $this->auth->hasIdentity();
     if ($isAllowed) {
         return $next($request, $response);
     }
     if ($isAuthenticated) {
         // Authenticated but unauthorized for this resource
         return $this->handler->notAuthorized($response);
     }
     // Not authenticated and must be authenticated to access this resource
     return $this->handler->notAuthenticated($response);
 }
Beispiel #22
0
 public function __construct(AuthenticationServiceInterface $authService, AclInterface $acl, $config = null)
 {
     $this->authService = $authService;
     if (is_array($config)) {
         if (isset($config['acl']) && !empty($config['acl']['defaultRole'])) {
             $defaultRole = $config['acl']['defaultRole'];
             if (!$defaultRole instanceof RoleInterface) {
                 $defaultRole = new GenericRole($defaultRole);
             }
             $this->setDefaultRole($defaultRole);
         }
     }
     $this->setAcl($acl);
     $this->setDefaultAcl($acl);
     $identity = $this->authService->getIdentity();
     if ($identity) {
         $role = $identity->getRole();
         if (!$role instanceof RoleInterface) {
             $role = new GenericRole($role);
         }
         $this->setRole($role);
     }
 }
Beispiel #23
0
 public function logout()
 {
     $this->authenticationService->clearIdentity();
 }
 /**
  * @return \Zend\Http\Response
  */
 public function addEmailAction()
 {
     $this->addEmailService->addEmail($this->params()->fromPost(), $this->authService->getIdentity());
     return $this->redirect()->toRoute('PServerCore/user', ['action' => 'index']);
 }
 /**
  * {@inheritDoc}
  */
 public function getIdentity()
 {
     return $this->authenticationService->getIdentity();
 }
Beispiel #26
0
 public function __invoke(Request $req, Response $res)
 {
     $school = $req->getAttribute('school');
     if ($req->isPost()) {
         $reqParams = $req->getParams();
         array_splice($reqParams['items'], 0, 0);
         $this->appFormInputFilter->setData(array_merge($reqParams, ['school_id' => $school->id, 'submitted_by' => $this->authService->getIdentity()->mail]));
         $isValid = $this->appFormInputFilter->isValid();
         if ($isValid) {
             $data = $this->appFormInputFilter->getValues();
             $appForm = $this->appFormService->submit($data);
             $_SESSION['applicationForm']['appForm'] = $appForm;
             $res = $res->withRedirect($this->successUrl);
             return $res;
         }
         $this->view['form'] = ['is_valid' => $isValid, 'values' => $this->appFormInputFilter->getValues(), 'raw_values' => $this->appFormInputFilter->getRawValues(), 'messages' => $this->appFormInputFilter->getMessages()];
     }
     $loadForm = (bool) $req->getParam('load', false);
     $this->view['choose'] = !$loadForm && !$req->isPost();
     if (!$req->isPost() && $loadForm) {
         // take care of new options in applications and migrate existing ones
         if (null !== ($appForm = $this->appFormService->findSchoolApplicationForm($school->id))) {
             /**
              * Do mapping of old items to new only if items do exist (old form) 
              * and the map is available at the app settings.
              * TODO: Only one version migrations are supported. If the old items are
              * two or more versions older, they will not be handled.
              */
             // get the existing (db) application form version
             $items_version = $this->version;
             if (isset($appForm['items']) && \count($appForm['items']) > 0) {
                 $items_version = array_values($appForm['items'])[0]['version'];
             }
             if ($this->version != $items_version && isset($appForm['items']) && isset($this->container['settings']['application_form']['itemcategory']['map']) && $this->container['settings']['application_form']['itemcategory']['map']['fromversion'] == $items_version && $this->container['settings']['application_form']['itemcategory']['map']['toversion'] == $this->version && isset($this->container['settings']['application_form']['itemcategory']['map']['items'])) {
                 // if map exists for this version, use it
                 $items_map = $this->container['settings']['application_form']['itemcategory']['map']['items'];
                 $appForm['items'] = array_map(function ($item) use($items_map) {
                     $migrate_values = [];
                     if (isset($items_map[$item['itemcategory_id']]) && intval($items_map[$item['itemcategory_id']]) > 0) {
                         $migrate_values = ['itemcategory_prev' => $item['itemcategory_id'], 'itemcategory_id_prev' => $item['itemcategory_id'], 'itemcategory_id' => intval($items_map[$item['itemcategory_id']])];
                     } else {
                         $migrate_values = ['itemcategory_prev' => '', 'itemcategory_id_prev' => -1];
                     }
                     $migrate_values['prev_form_load'] = true;
                     return array_merge($item, $migrate_values);
                 }, $appForm['items']);
             } elseif ($this->version != $items_version && isset($appForm['items']) && isset($this->container['settings']['application_form']['itemcategory']['map']) && ($this->container['settings']['application_form']['itemcategory']['map']['fromversion'] != $items_version || $this->container['settings']['application_form']['itemcategory']['map']['toversion'] != $this->version)) {
                 // if map does not exist for this version, notify user
                 $items_map = $this->container['settings']['application_form']['itemcategory']['map']['items'];
                 $appForm['items'] = array_map(function ($item) use($items_map) {
                     $migrate_values = ['itemcategory_prev' => '', 'itemcategory_id_prev' => -2, 'prev_form_load' => true];
                     return array_merge($item, $migrate_values);
                 }, $appForm['items']);
             }
             $this->view['form'] = ['values' => $appForm];
         }
     }
     $labs = $this->labService->getLabsBySchoolId($school->id);
     $res = $this->view->render($res, 'application_form/form.twig', ['lab_choices' => array_map(function ($lab) {
         return ['value' => $lab['id'], 'label' => $lab['name']];
     }, $labs), 'type_choices' => array_map(function ($category) {
         return ['value' => $category['id'], 'label' => $category['name']];
     }, $this->assetsService->getAllItemCategories($this->version))]);
     return $res;
 }
Beispiel #27
0
 private function logoutAndRediret(Response $res, $message)
 {
     $this->authService->clearIdentity();
     $this->flash->addMessage('danger', $message);
     return $res->withRedirect($this->unitNotFoundRedirectUrl);
 }
Beispiel #28
0
 public function init()
 {
     $this->add(['name' => 'token', 'required' => true]);
     $this->add(['name' => 'identity', 'required' => true]);
     $this->add(['name' => 'credential', 'required' => true, 'validators' => [['name' => 'Zend\\Authentication\\Validator\\Authentication', 'options' => ['adapter' => $this->authenticationService->getAdapter(), 'service' => $this->authenticationService, 'identity' => 'identity', 'credential' => 'credential']]]]);
 }