Example #1
2
 public function __invoke(Request $req, Response $res, callable $next)
 {
     $res = $next($req, $res);
     $identity = $this->authService->getIdentity();
     if (!$identity) {
         return $res;
     }
     try {
         $user = R::findOne('user', 'mail = ?', [$identity->mail]);
         if (!$user) {
             $user = R::dispense('user');
             $user->uid = $identity->uid;
             $user->mail = $identity->mail;
             $user->display_name = $identity->displayName;
             $user->office_name = $identity->officeName;
             $user->authentication_source = $identity->authenticationSource;
             $user->password = '';
             $user->created = time();
             $user->role = 'school';
             $this->logger->info(sprintf('User %s imported from sso.sch.gr to database', $identity->mail));
         }
         $user->last_login = time();
         $user_id = R::store($user);
         $identityClass = get_class($identity);
         $newIdentity = new $identityClass($user_id, $user->uid, $user->mail, $user->display_name, $user->office_name, $user->authentication_source);
         $this->authService->getStorage()->write($newIdentity);
     } catch (\Exception $e) {
         $this->authService->clearIdentity();
         $this->flash->addMessage('danger', 'A problem occured storing user in database. <a href="%s" title="SSO logout">SSO Logout</a>');
         $this->logger->error('Problem inserting user form CAS in database', $identity->toArray());
         $this->logger->debug('Exception', [$e->getMessage(), $e->getTraceAsString()]);
         return $res->withRedirect($this->userErrorRedirectUrl);
     }
     return $res;
 }
Example #2
0
 /**
  * @param $data
  * @return mixed
  */
 public function login($data)
 {
     /** @var ObjectRepository $adapter */
     $adapter = $this->authService->getAdapter();
     $adapter->setIdentityValue($data->login);
     $adapter->setCredentialValue($data->password);
     $result = $adapter->authenticate();
     switch ($result->getCode()) {
         case Result::SUCCESS:
             $identity = $result->getIdentity();
             $this->authService->getStorage()->write($identity);
             if (isset($data->rememberMe)) {
                 $this->sessionManager->rememberMe(1209600);
             }
             $toJson['user'] = $identity->toArray();
             $toJson['session_id'] = $this->sessionManager->getId();
             $toJson['success'] = true;
             return json_decode(json_encode($toJson));
         case Result::FAILURE_IDENTITY_NOT_FOUND:
             return ['success' => false, 'message' => 'User not found.'];
         case Result::FAILURE_CREDENTIAL_INVALID:
             return ['success' => false, 'message' => 'Invalid password'];
         default:
             return ['success' => false, 'message' => 'Error while login'];
     }
 }
Example #3
0
 /**
  * Updates user's email address and updates auth storage with
  * updated user data
  *
  * @param array  $user  User data
  * @param string $email New email address
  *
  * @return array User data
  */
 public function updateEmail(array $user, $email)
 {
     $user = $this->dao->updateEmail($user['id'], $email);
     $this->auth->clearIdentity();
     $this->auth->getStorage()->write($user);
     return $user;
 }
Example #4
0
 public function proceed($userId, $tokenHash)
 {
     /** @var UserInterface $user */
     $user = $this->userRepository->findOneBy(array('id' => new \MongoId($userId), 'tokens.hash' => $tokenHash));
     if (!$user) {
         throw new UserNotFoundException('User or token does not exists');
     }
     $this->checkAllTokens($user, $tokenHash);
     $this->authenticationService->getStorage()->write($user->getId());
 }
Example #5
0
 public function proceed($userId)
 {
     if (!($user = $this->userRepository->find($userId))) {
         throw new Exception\UserNotFoundException('User cannot be found');
     }
     /* \Auth\Entity\Info */
     $user->getInfo()->setEmailVerified(true);
     $user->setEmail($user->getInfo()->getEmail());
     // Set verified email as primary email.
     $this->userRepository->store($user);
     $this->authenticationService->getStorage()->write($user->getId());
 }
 /**
  *
  * @param MvcAuthEvent $mvcAuthEvent
  * @throws \Dws\Exception\Service\ModelNotFoundException
  */
 public function __invoke(MvcAuthEvent $mvcAuthEvent)
 {
     // Add validated identity to ZfcUser storage
     $identity = $mvcAuthEvent->getIdentity();
     if ($identity instanceof AuthenticatedIdentity) {
         $user = $this->userService->getUserMapper()->findById($identity->getAuthenticationIdentity()['user_id']);
         if ($user) {
             $this->authenticationService->getStorage()->write($user);
         }
         $identity->setName(implode(', ', $user->getRoles()->toArray()));
     }
 }
 /**
  * verify authentication
  */
 public function verificaAuth()
 {
     $this->identity = $this->auth->getStorage()->read();
     if (!$this->auth->hasIdentity()) {
         //there is no id?
         $this->redirect()->toRoute('Locador/logoff');
     } else {
         $this->locador = $this->identity[0];
         $this->layout()->locador = $this->locador;
         $visitas = $this->getEm()->getRepository("MyClasses\\Entities\\Locador")->find($this->locador->getId())->getVisitas()->filter(function ($visita) {
             return $visita->getStatus() == "agendada";
         })->count();
         $this->layout()->visitas = $visitas;
     }
 }
 /**
  * @return \Zend\View\Model\ViewModel
  */
 public function impersonateAction()
 {
     $user = $this->checkIfUserExists();
     $this->auth->getStorage()->write($user);
     $this->flashMessenger()->addSuccessMessage($this->translate('You have impersonated the account succesfully'));
     return $this->redirect()->toRoute('users', ['controller' => 'account', 'action' => 'my-account']);
 }
Example #9
0
 public function loginAction()
 {
     $messages = null;
     $form = new AuthForm();
     $form->get('submit')->setvalue('Login');
     $request = $this->getRequest();
     if ($request->isPost()) {
         $authFormFilters = new Auth();
         $form->setInputFilter($authFormFilters->getInputFilter());
         $form->setData($request->getPost());
         if ($form->isValid()) {
             $data = $form->getData();
             $sm = $this->getServiceLocator();
             $dbAdapter = $sm->get('Zend\\Db\\Adapter\\Adapter');
             $config = $this->getServiceLocator()->get('Config');
             $staticSalt = $config['static_salt'];
             $authAdapter = new AuthAdapter($dbAdapter, 'users', 'usr_name', 'usr_password', "MD5(CONCAT('{$staticSalt}', ?, usr_password_salt)) AND usr_active = 1");
             $authAdapter->setIdentity($data['usr_name'])->setCredential($data['usr_password']);
             $auth = new AuthenticationService();
             // or prepare in the globa.config.php and get it from there. Better to be in a module, so we can replace in another module.
             // $auth = $this->getServiceLocator()->get('Zend\Authentication\AuthenticationService');
             // $sm->setService('Zend\Authentication\AuthenticationService', $auth); // You can set the service here but will be loaded only if this action called.
             $result = $auth->authenticate($authAdapter);
             //                echo '<pre>';
             //                print_r($result);
             //                echo '</pre>';
             switch ($result->getCode()) {
                 case Result::FAILURE_IDENTITY_NOT_FOUND:
                     // do stuff for nonexistent identity
                     break;
                 case Result::FAILURE_CREDENTIAL_INVALID:
                     // do stuff for invalid credential
                     break;
                 case Result::SUCCESS:
                     $storage = $auth->getStorage();
                     $storage->write($authAdapter->getResultRowObject(null, 'usr_password'));
                     $time = 1209600;
                     // 14 days 1209600/3600 = 336 hours => 336/24 = 14 days
                     //						if ($data['rememberme']) $storage->getSession()->getManager()->rememberMe($time); // no way to get the session
                     //                                if ($data['rememberme']) {
                     //                                        $sessionManager = new \Zend\Session\SessionManager();
                     //                                        $sessionManager->rememberMe($time);
                     //                                }
                     break;
                 default:
                     // do stuff for other failure
                     break;
             }
             foreach ($result->getMessages() as $message) {
                 $messages .= "{$message}\n";
             }
         } else {
             echo '<h1> The form is NOT valid </h1>';
         }
     }
     //        echo '<pre>';
     //        print_r($_SESSION);
     //        echo '</pre>';
     return new ViewModel(array('form' => $form, 'messages' => $messages));
 }
 public function addAction()
 {
     $viewModel = new ViewModel();
     $form = $this->getServiceLocator()->get("Process\\Form\\ReceiveInventoryForm");
     $viewModel->setVariable('form', $form);
     $request = $this->getRequest();
     if ($request->isPost()) {
         $receiveInventory = new ReceiveInventory();
         $form->setInputFilter($receiveInventory->getInputFilter());
         $data = $request->getPost()->toArray();
         $form->setData($data);
         if ($form->isValid()) {
             $fileService = $this->getServiceLocator()->get('Admin\\Service\\FileService');
             $fileService->setDestination($this->config['component']['receive_inventory']['file_path']);
             $fileService->setSize($this->config['file_characteristics']['file']['size']);
             $fileService->setExtension($this->config['file_characteristics']['file']['extension']);
             $invoiceFile = $fileService->copy($this->params()->fromFiles('invoice_file'));
             $data['invoice_file'] = $invoiceFile ? $invoiceFile : "";
             $authenticationService = new AuthenticationService();
             $user = $authenticationService->getStorage()->read()->id;
             $receiveInventory->setUser($user);
             $receiveInventory->exchangeArray($data);
             $receiveInventoryId = $this->getReceiveInventoryTable()->save($receiveInventory);
             $container = new Container('receive_inventory');
             $container->id = $receiveInventoryId;
             $container->user = $user;
             return $this->redirect()->toRoute('process/receive_inventory/add/details');
         }
     }
     $viewModel->setVariable('config', $this->config);
     return $viewModel;
 }
Example #11
0
 public function authenticate($username, $password)
 {
     $callback = function ($password, $hash) {
         $bcrypt = new Bcrypt();
         return $bcrypt->verify($hash, $password);
     };
     $authenticationService = new AuthenticationService();
     $callbackCheckAdapter = new CallbackCheckAdapter($this->dbAdapter, "users", 'username', 'password', $callback);
     $callbackCheckAdapter->setIdentity($username)->setCredential($password);
     $authenticationService->setAdapter($callbackCheckAdapter);
     $authResult = $authenticationService->authenticate();
     if ($authResult->isValid()) {
         $userObject = $callbackCheckAdapter->getResultRowObject();
         $authenticationService->getStorage()->write($userObject);
         if ($userObject->status == 0) {
             $authenticationService->clearIdentity();
             $this->setCode(-5);
             return false;
         } else {
             return true;
         }
     } else {
         $this->setCode($authResult->getCode());
         return false;
     }
 }
Example #12
0
 public function checkAcl(MvcEvent $e)
 {
     //guardamos el nombre de la ruta o recurso a permitir o denegar
     $route = $e->getRouteMatch()->getMatchedRouteName();
     //Instanciamos el servicio de autenticacion
     $auth = new AuthenticationService();
     $identi = $auth->getStorage()->read();
     // Establecemos nuestro rol
     // $userRole = 'admin';
     // Si el usuario esta identificado le asignaremos el rol admin y si no el rol visitante.
     if ($identi != false && $identi != null) {
         $userRole = $identi->role;
     } else {
         $userRole = 'visitante';
     }
     /*
     Esto se puede mejorar fácilmente, si tenemos un campo rol en la BD cuando el usuario
     se identifique en la sesión se guardarán todos los datos del mismo, de modo que
     $userRole=$identi->role;
     */
     //Comprobamos si no está permitido para ese rol esa ruta
     if (!$e->getViewModel()->acl->isAllowed($userRole, $route)) {
         //Devolvemos un error 404
         $response = $e->getResponse();
         $response->getHeaders()->addHeaderLine('Location', $e->getRequest()->getBaseUrl() . '/404');
         $response->setStatusCode(404);
     }
 }
Example #13
0
 public function loginAction()
 {
     if ($this->authenticationService->hasIdentity()) {
         return $this->redirect()->toRoute('home');
     }
     $this->layout('layout/layout-blank');
     $resultModel = new JsonResultModel();
     if ($this->getRequest()->isPost()) {
         $jsonData = $this->getRequest()->getPost('login');
         $data = Json::decode($jsonData, Json::TYPE_ARRAY);
         // If you used another name for the authentication service, change it here
         $adapter = $this->authenticationService->getAdapter();
         $adapter->setIdentityValue($data['username']);
         $adapter->setCredentialValue($data['password']);
         $authResult = $this->authenticationService->authenticate();
         //@todo remember me
         if ($authResult->isValid()) {
             if ($data['rememberMe']) {
                 $this->authenticationService->getStorage()->getManager()->rememberMe(36000);
             }
             return $resultModel;
         } else {
             $resultModel->addErrors('password', '登录名或密码错误');
             return $resultModel;
         }
     }
 }
 public function addAction()
 {
     $viewModel = new ViewModel();
     $form = $this->getServiceLocator()->get("Process\\Form\\OutputInventoryForm");
     $viewModel->setVariable('form', $form);
     $request = $this->getRequest();
     if ($request->isPost()) {
         $outputInventory = new OutputInventory();
         $form->setInputFilter($outputInventory->getInputFilter());
         $data = $request->getPost()->toArray();
         $form->setData($data);
         if ($form->isValid()) {
             $authenticationService = new AuthenticationService();
             $user = $authenticationService->getStorage()->read()->id;
             $outputInventory->setUser($user);
             $outputInventory->exchangeArray($data);
             $outputInventoryId = $this->getOutputInventoryTable()->save($outputInventory);
             $container = new Container('output_inventory');
             $container->id = $outputInventoryId;
             $container->user = $user;
             return $this->redirect()->toRoute('process/output_inventory/add/details');
         }
     }
     $viewModel->setVariable('config', $this->config);
     return $viewModel;
 }
Example #15
0
 /**
  * @return string 用户名字符串
  * 如果没有登录,返回null
  */
 public static function get_auth()
 {
     $auth = new AuthenticationService();
     $tmp = $auth->getStorage()->read();
     return $tmp;
     //返回一个类,有username和schoolID和userID和type这四个在userservice里面get——auth函数里write数据库中的两列。
 }
Example #16
0
    /**
     * @param MvcAuthEvent $mvcAuthEvent
     * @throws \Dws\Exception\Service\ModelNotFoundException
     */
    public function __invoke(MvcAuthEvent $mvcAuthEvent)
    {
        // Add validated identity to ZfcUser storage
        $identity = $mvcAuthEvent->getIdentity();
        if ($identity instanceof AuthenticatedIdentity) {
            /** var AuthenticatedIdentity $identity */
            $user = $this->userService->find($identity->getAuthenticationIdentity()['user_id']);
            if ($user) {
                // It should not be possible to be authenticated without valid user, but in that case
                // we simply don't set the identity to the authentication service. No permissions
                // will then be granted.
                $this->authenticationService->getStorage()->write($user);
            }

        }
    }
 public function forbiddenAction()
 {
     $this->getResponse()->setStatusCode(301);
     $authService = new AuthenticationService();
     $auth = $authService->getStorage()->read();
     return new ViewModel(array('auth' => $auth));
 }
Example #18
0
 public function indexAction()
 {
     $authenticationService = new AuthenticationService();
     $user = $authenticationService->getStorage()->read();
     $notes = $this->getNoteTable()->fetchAll($user->id);
     $logs = $this->getLogTable()->fetchAll($user->id);
     return new ViewModel(array('config' => $this->config, 'notes' => $notes, 'logs' => $logs));
 }
Example #19
0
 public function loginAction()
 {
     $authenticationService = new AuthenticationService();
     if ($authenticationService->hasIdentity()) {
         return $this->redirect()->toRoute('dashboard');
     }
     $form = new LoginForm();
     $viewModel = new ViewModel();
     $this->layout("layout/login");
     $viewModel->setVariable("form", $form);
     $viewModel->setVariable("config", $this->config);
     $request = $this->getRequest();
     if ($request->isPost()) {
         $login = new Login();
         $login->getInputFilter()->get('captcha')->setRequired(false);
         $form->setInputFilter($login->getInputFilter());
         $form->setData($request->getPost());
         if ($form->isValid()) {
             $username = $form->get('username')->getValue();
             $password = $form->get('password')->getValue();
             $authSessionAdapter = $this->getAuthSessionAdapter();
             if ($authSessionAdapter->authenticate($username, $password)) {
                 $userObject = $authenticationService->getStorage()->read();
                 $rol = $userObject->rol;
                 $acl = new Acl();
                 $acl->addResource(new Resource("dashboard"));
                 $acl->addResource(new Resource("note"));
                 if ($rol == 1) {
                     $resources = $this->config['resources'];
                     foreach ($resources as $module => $resource) {
                         foreach ($resource as $resourceValue) {
                             $acl->addResource(new Resource($resourceValue));
                         }
                     }
                 } else {
                     $acl->addRole(new Role($rol));
                     $modules = $this->getModuleRolTable()->fetchAll($rol);
                     foreach ($modules as $module) {
                         $acl->addResource(new Resource($module));
                     }
                 }
                 $userObject->acl = serialize($acl);
                 return $this->redirect()->toRoute('dashboard');
             } else {
                 $form->get('username')->setValue("");
                 $form->get('password')->setValue("");
                 if ($authSessionAdapter->getCode() == -5) {
                     $form->get("username")->setMessages(array('username' => $this->config['authentication_codes'][$authSessionAdapter->getCode()]));
                 } else {
                     $form->get("username")->setMessages(array('username' => $this->config['authentication_codes'][-6]));
                 }
             }
         } else {
             $form->get("username")->setMessages(array('username' => $this->config['authentication_codes'][-6]));
         }
     }
     return $viewModel;
 }
Example #20
0
 /**
  * Trigger the authentication event
  *
  * @param MvcEvent $mvcEvent
  * @return null|Response
  */
 public function authentication(MvcEvent $mvcEvent)
 {
     if (!$mvcEvent->getRequest() instanceof HttpRequest || $mvcEvent->getRequest()->isOptions()) {
         return;
     }
     $mvcAuthEvent = $this->mvcAuthEvent;
     $mvcAuthEvent->setName($mvcAuthEvent::EVENT_AUTHENTICATION);
     $responses = $this->events->triggerEventUntil(function ($r) {
         return $r instanceof Identity\IdentityInterface || $r instanceof Result || $r instanceof Response;
     }, $mvcAuthEvent);
     $result = $responses->last();
     $storage = $this->authentication->getStorage();
     // If we have a response, return immediately
     if ($result instanceof Response) {
         return $result;
     }
     // Determine if the listener returned an identity
     if ($result instanceof Identity\IdentityInterface) {
         $storage->write($result);
     }
     // If we have a Result, we create an AuthenticatedIdentity from it
     if ($result instanceof Result && $result->isValid()) {
         $mvcAuthEvent->setAuthenticationResult($result);
         $mvcAuthEvent->setIdentity(new Identity\AuthenticatedIdentity($result->getIdentity()));
         return;
     }
     $identity = $this->authentication->getIdentity();
     if ($identity === null && !$mvcAuthEvent->hasAuthenticationResult()) {
         // if there is no Authentication identity or result, safe to assume we have a guest
         $mvcAuthEvent->setIdentity(new Identity\GuestIdentity());
         return;
     }
     if ($mvcAuthEvent->hasAuthenticationResult() && $mvcAuthEvent->getAuthenticationResult()->isValid()) {
         $mvcAuthEvent->setIdentity(new Identity\AuthenticatedIdentity($mvcAuthEvent->getAuthenticationResult()->getIdentity()));
     }
     if ($identity instanceof Identity\IdentityInterface) {
         $mvcAuthEvent->setIdentity($identity);
         return;
     }
     if ($identity !== null) {
         // identity found in authentication; we can assume we're authenticated
         $mvcAuthEvent->setIdentity(new Identity\AuthenticatedIdentity($identity));
         return;
     }
 }
Example #21
0
 /**
  *
  * @param unknown $data        	
  */
 public static function setUser($data)
 {
     if (SESSION_KEY == "") {
         die("You must define some random SESSION_KEY in Index.php");
     }
     $auth = new AuthenticationService();
     $auth->setStorage(new \Zend\Authentication\Storage\Session(SESSION_KEY ? SESSION_KEY : ""));
     $auth->getStorage()->write($data);
 }
Example #22
0
 /**
  * Save identity into sesssion
  * @param array $data
  */
 public function login(array $data)
 {
     $identity = $data['identity'];
     //on successfull login save the identity in the storage
     if ($this->auth->hasIdentity()) {
         $this->auth->clearIdentity();
     }
     $this->auth->getStorage()->write($identity);
 }
Example #23
0
 public function indexAction()
 {
     $viewModel = new ViewModel();
     $request = $this->getRequest();
     if (!$request->isPost()) {
         $this->layout('layout/login');
         return $viewModel;
     }
     $user = $this->identity();
     $messages = null;
     $auth = new AuthenticationService();
     if ($auth->hasIdentity()) {
         return $this->redirect()->toRoute('home');
     }
     $request = $this->getRequest();
     if ($request->isPost()) {
         $sm = $this->getServiceLocator();
         $dbAdapter = $sm->get('Zend\\Db\\Adapter\\Adapter');
         $authAdapter = new AuthAdapter($dbAdapter, 'users', 'username', 'password', 'MD5(?) AND block = 1');
         $authAdapter->setIdentity($request->getPost('username'))->setCredential($request->getPost('password'));
         if (trim($request->getPost('username')) == "" || trim($request->getPost('password')) == "") {
             return $this->redirect()->toRoute('auth');
         }
         // or prepare in the globa.config.php and get it from there. Better to be in a module, so we can replace in another module.
         // $auth = $this->getServiceLocator()->get('Zend\Authentication\AuthenticationService');
         // $sm->setService('Zend\Authentication\AuthenticationService', $auth); // You can set the service here but will be loaded only if this action called.
         $result = $auth->authenticate($authAdapter);
         switch ($result->getCode()) {
             case Result::FAILURE_IDENTITY_NOT_FOUND:
                 // do stuff for nonexistent identity
                 break;
             case Result::FAILURE_CREDENTIAL_INVALID:
                 // do stuff for invalid credential
                 break;
             case Result::SUCCESS:
                 $storage = $auth->getStorage();
                 $storage->write($authAdapter->getResultRowObject(null, 'password'));
                 $time = 28800;
                 // 14 days 1209600/3600 = 336 hours => 336/24 = 14 days
                 //						if ($data['rememberme']) $storage->getSession()->getManager()->rememberMe($time); // no way to get the session
                 if ($request->getPost('username')) {
                     $sessionManager = new \Zend\Session\SessionManager();
                     $sessionManager->rememberMe($time);
                 }
                 return $this->redirect()->toRoute('home');
                 break;
             default:
                 // do stuff for other failure
                 break;
         }
         foreach ($result->getMessages() as $message) {
             $messages .= "{$message}\n";
         }
     }
     $this->layout('layout/login');
     return $viewModel;
 }
 public function __invoke()
 {
     $mvcEvent = $this->getServiceLocator()->getServiceLocator()->get('application')->getMvcEvent();
     $match = $mvcEvent->getRouteMatch();
     if (!$match) {
         die('Route khong dung. Vui long kiem tra lai!');
     }
     $params = $match->getParams();
     // return array
     $return_array = array();
     //Get form login
     $login_form = $this->getServiceLocator()->getServiceLocator()->get('Permission\\Form\\LoginForm');
     // tạo url để back lại đúng trang
     $params = $match->getParams();
     $route_array = array();
     foreach ($params as $key => $param) {
         if ($key != 'controller') {
             $route_array[$key] = $param;
         }
     }
     $route_name = $match->getMatchedRouteName();
     $return_array['route_name'] = $route_name;
     $return_array['route_array'] = $route_array;
     if ($mvcEvent->getRequest()->isPost()) {
         $url = '/';
         $post = $mvcEvent->getRequest()->getPost();
         $url = $post['url'];
         $return_array['url'] = $url;
     }
     // Get list giảng viên
     $jos_users_table = $this->getServiceLocator()->getServiceLocator()->get('Permission\\Model\\JosUsersTable');
     $danh_sach_giang_viens = $jos_users_table->getDanhSachGiangVien();
     // id giang vien mặc định để đánh dấu đang chọn giảng viên nào trong bảng danh sách giảng viên trong layout
     if ($params['controller'] == 'Application\\Controller\\Index') {
         if (isset($params['id']) and $params['id']) {
             $id_giang_vien_mac_dinh = $params['id'];
             $return_array['id_giang_vien_mac_dinh'] = $id_giang_vien_mac_dinh;
         }
     }
     // nếu đã đăng nhập
     $auth = new AuthenticationService();
     $read = $auth->getStorage()->read();
     if ($auth->hasIdentity() and isset($read['username'])) {
         // nếu đã đăng nhập thì get id giảng viên, để đánh dấu ngôi sao ở danh sách giảng viên
         // để biết giảng viên nào đã đang đăng
         $user_is_logining = $jos_users_table->getGiangVienByArrayConditionAndArrayColumns(array('username' => $read['username']), array('id'));
         if ($user_is_logining) {
             $return_array['user_id'] = $user_is_logining[0]['id'];
         }
     }
     $return_array['danh_sach_giang_viens'] = $danh_sach_giang_viens;
     $return_array['login_form'] = $login_form;
     return $return_array;
 }
 public function loginAction()
 {
     $user = $this->identity();
     $form = new LoginForm();
     $messages = null;
     $request = $this->getRequest();
     if ($request->isPost()) {
         $form->setInputFilter(new LoginFilter($this->getServiceLocator()));
         $form->setData($request->getPost());
         if ($form->isValid()) {
             $data = $form->getData();
             $sm = $this->getServiceLocator();
             $dbAdapter = $sm->get('Zend\\Db\\Adapter\\Adapter');
             $authAdapter = new AuthAdapter($dbAdapter, 'user', 'email', 'password', "MD5(?)");
             $authAdapter->setIdentity($data['email'])->setCredential($data['password']);
             $auth = new AuthenticationService();
             $result = $auth->authenticate($authAdapter);
             switch ($result->getCode()) {
                 case Result::FAILURE_IDENTITY_NOT_FOUND:
                     // do stuff for nonexistent identity
                     break;
                 case Result::FAILURE_CREDENTIAL_INVALID:
                     // do stuff for invalid credential
                     break;
                 case Result::SUCCESS:
                     $storage = $auth->getStorage();
                     $storage->write($authAdapter->getResultRowObject(null, 'password'));
                     $user = $auth->getIdentity();
                     switch ($user->role_id) {
                         case 1:
                             return $this->redirect()->toRoute('admin');
                             break;
                         case 2:
                             return $this->redirect()->toRoute('teacher');
                             break;
                         case 3:
                             return $this->redirect()->toRoute('student');
                             break;
                         default:
                             return $this->redirect()->toRoute('home');
                             break;
                     }
                     break;
                 default:
                     // do stuff for other failure
                     break;
             }
             foreach ($result->getMessages() as $message) {
                 $messages .= "{$message}\n";
             }
         }
     }
     return new ViewModel(array('form' => $form, 'messages' => $messages));
 }
Example #26
0
 public function authenticate()
 {
     $result = new Result(1, 1, array(1 => 'Witaj ' . $this->username));
     $ses = new SessionStorage();
     $ses->write($result);
     $auth = new AuthenticationService();
     // Use 'someNamespace' instead of 'Zend_Auth'
     $auth->setStorage(new SessionStorage('someNamespace'));
     var_dump($auth->getStorage()->read());
     return $result;
 }
Example #27
0
 public function loginAction()
 {
     $messages = null;
     $form = new AuthForm();
     $form->get('submit')->setValue('Login');
     $request = $this->getRequest();
     if ($request->isPost()) {
         $authFormFilters = new Auth();
         $form->setInputFilter($authFormFilters->getInputFilter());
         $form->setData($request->getPost());
         if ($form->isValid()) {
             $data = $form->getData();
             $sm = $this->getServiceLocator();
             $dbAdapter = $sm->get('Zend\\Db\\Adapter\\Adapter');
             $config = $this->getServiceLocator()->get('Config');
             $staticSalt = $config['static_salt'];
             $authAdapter = new AuthAdapter($dbAdapter, 'users', 'usr_name', 'usr_password', "MD5 (CONCAT('{$staticSalt}', ?, usr_password_salt)) AND usr_active = 1");
             $authAdapter->setIdentity($data['usr_name'])->setCredential($data['usr_password']);
             $auth = new AuthenticationService();
             $result = $auth->authenticate($authAdapter);
             switch ($result->getCode()) {
                 case Result::FAILURE_IDENTITY_NOT_FOUND:
                     // do stuff for nonexistent identity
                     break;
                 case Result::FAILURE_CREDENTIAL_INVALID:
                     // do stuff for invalid credential
                     break;
                 case Result::SUCCESS:
                     $storage = $auth->getStorage();
                     $storage->write($authAdapter->getResultRowObject(null, 'usr_password'));
                     /*$time = 1209600; // 14 days 1209600/3600 = 336 hours => 336/24 = 14 days
                     //						if ($data['rememberme']) $storage->getSession()->getManager()->rememberMe($time); // no way to get the session
                                                 if ($data['rememberme']) {
                                                         $sessionManager = new \Zend\Session\SessionManager();
                                                         $sessionManager->rememberMe($time);
                                                 }*/
                     break;
                 default:
                     // do stuff for other failure
                     break;
             }
             foreach ($result->getMessages() as $message) {
                 $messages .= "{$message}\n";
             }
             //echo '<pre>';
             //print_r($_SESSION);
             //echo '</pre>';
         } else {
             //echo 'Form is not valid!';
         }
     }
     return new viewModel(array('form' => $form, 'messages' => $messages));
 }
 public function processAction()
 {
     // here come the data from LoginForm(admin/index)
     if (!$this->request->isPost()) {
         return $this->redirect()->toRoute(NULL, array('controller' => 'Auth', 'action' => 'auth'));
     }
     $post = $this->getRequest()->getPost();
     //
     $dbAdapter = $this->getServiceLocator()->get('Zend\\Db\\Adapter\\Adapter');
     //
     $config = $this->getServiceLocator()->get('Config');
     //
     $salt = $config['salt'];
     //
     $authAdapter = new CredentialTreatmentAdapter($dbAdapter, 'users', 'user_email', 'user_password', "MD5(?) AND user_role = 'admin'");
     //
     $authAdapter->setIdentity($post->user_email)->setCredential($post->user_password);
     //
     $auth = new AuthenticationService();
     $result = $auth->authenticate($authAdapter);
     //
     switch ($result->getCode()) {
         case Result::FAILURE_IDENTITY_NOT_FOUND:
             //
             $this->flashMessenger()->setNamespace('not_admin')->addMessage('wrong email/pasword');
             //
             return $this->redirect()->toRoute(NULL, array('controller' => 'Auth', 'action' => 'auth'));
             //
             break;
         case Result::FAILURE_CREDENTIAL_INVALID:
             //
             $this->flashMessenger()->setNamespace('not_admin')->addMessage('admin-only allowed');
             //
             return $this->redirect()->toRoute(NULL, array('controller' => 'Auth', 'action' => 'auth'));
             //
             break;
         case Result::SUCCESS:
             $storage = $auth->getStorage();
             $storage->write($authAdapter->getResultRowObject(null, 'user_password'));
             $session = new Container('admin');
             $time = 900;
             if ($post->rememberMe) {
                 $session->remember = $time;
             }
             $session->user_email = $post->user_email;
             return $this->redirect()->toRoute('index', array('controller' => 'Index', 'action' => 'index'));
             break;
         default:
             //
             break;
     }
 }
Example #29
0
 public function getAuthenticateValidate()
 {
     $authenticationService = new AuthenticationService();
     if (!$authenticationService->hasIdentity()) {
         return $this->redirect()->toRoute('security/login');
     } else {
         $userObject = $authenticationService->getStorage()->read();
         $acl = unserialize($userObject->acl);
         if (!$acl->hasResource("user")) {
             return $this->redirect()->toRoute('security/login');
         }
     }
 }
Example #30
0
 public function notes()
 {
     $authenticationService = new AuthenticationService();
     $user = $authenticationService->getStorage()->read();
     $viewModel = new ViewModel();
     $viewModel->setTemplate('admin/helper/modal/notes');
     $config = $this->serviceLocator->get('config');
     $noteTable = $this->serviceLocator->get('Admin\\Model\\NoteTable');
     $notes = $noteTable->fetchAll($user->id);
     $form = new NoteForm();
     $viewModel->setVariables(array('form' => $form, 'config' => $config, 'notes' => $notes));
     return $this->getView()->render($viewModel);
 }