Пример #1
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'];
     }
 }
Пример #2
0
 /**
  * @param AuthenticationEvent $e
  */
 public function authListener(AuthenticationEvent $e)
 {
     $result = $e->getResult();
     if ($result->isValid()) {
         if ($this->rememberMe) {
             $this->sessionManager->rememberMe();
         } else {
             $this->sessionManager->forgetMe();
         }
         $this->sessionManager->writeClose();
     }
 }
Пример #3
0
 protected function userAuthentication($data)
 {
     $auth = $this->authService;
     $adapter = $auth->getAdapter();
     $adapter->setIdentityValue($data['username']);
     $adapter->setCredentialValue($data['password']);
     $authResult = $auth->authenticate();
     if ($authResult->isValid()) {
         $identity = $authResult->getIdentity();
         $auth->getStorage()->write($identity);
         $sessionManager = new SessionManager();
         if ($data['rememberme']) {
             $sessionManager->rememberMe();
         }
         // store user roles in a session container
         $userContainer = new Container('User');
         $userContainer->offsetSet('id', $identity->getUserId());
         $userRoles = $identity->getRole()->toArray();
         $roleNames = array();
         foreach ($userRoles as $userRole) {
             $roleNames[] = $userRole->getRoleName();
         }
         $userContainer->offsetSet('activeRole', $roleNames[0]);
         $userContainer->offsetSet('allRoles', $roleNames);
         $sessionManager->writeClose();
         return true;
     }
     return false;
 }
Пример #4
0
 public function loginAction()
 {
     $form = $this->getAuthForm();
     $request = $this->getRequest();
     if ($request->isPost()) {
         $form->setData($request->getPost());
         if ($form->isValid()) {
             $authenticationService = $this->getAuthenticationService();
             $authAdapter = $authenticationService->getAdapter();
             $authAdapter->setLogin($request->getPost('email'));
             $authAdapter->setSenha($request->getPost('senha'));
             $resultado = $authenticationService->authenticate()->isValid();
             if ($resultado) {
                 $authenticationService->getStorage()->write($authenticationService->getIdentity()['cliente']);
                 if ($request->getPost('lembrar') == 'sim') {
                     $tempo = 2592000000.0;
                     // 30 dias em milissegundos
                     $SessionManager = new SessionManager();
                     $SessionManager->rememberMe($tempo);
                 }
                 return $this->redirect()->toRoute('cliente', array('controller' => 'cliente', 'action' => 'index'));
             } else {
                 echo "Login ou senha incorreto";
             }
         }
     }
     $viewModel = new ViewModel(['form' => $form]);
     return $viewModel->setTerminal(true);
 }
Пример #5
0
 public function indexAction()
 {
     $form = new LoginForm();
     $authService = $this->getServiceLocator()->get('Zend\\Authentication\\AuthenticationService');
     $request = $this->getRequest();
     if ($request->isPost()) {
         $form->setData($request->getPost());
         if ($form->isValid()) {
             $data = $form->getData();
             $adapter = $authService->getAdapter();
             $adapter->setIdentityValue($data['email']);
             $adapter->setCredentialValue($data['password']);
             $authResult = $authService->authenticate();
             if ($authResult->isValid()) {
                 $identity = $authResult->getIdentity();
                 $authService->getStorage()->write($identity);
                 $time = 1209600;
                 // 14 days 1209600/3600 = 336 hours => 336/24 = 14 days
                 //-					if ($data['rememberme']) $authService->getStorage()->session->getManager()->rememberMe($time); // no way to get the session
                 if ($data['remember-me']) {
                     $sessionManager = new SessionManager();
                     $sessionManager->rememberMe($time);
                 }
                 return $this->redirect()->toRoute('user_dashboard');
             } else {
                 $this->flashMessenger()->addErrorMessage("Invalid login credentials provided. Try again, or sign up!");
             }
         }
     }
     $view = new ViewModel(array('form' => $form));
     return $view;
 }
Пример #6
0
 public function indexAction()
 {
     $form = new SigninForm();
     $request = $this->getRequest();
     if ($request->isPost()) {
         $form->setData($request->getPost());
         if ($form->isValid()) {
             $data = $request->getPost()->toArray();
             // Criando Storage para gravar sessão da authtenticação
             //$sessionStorage = new SessionStorage();
             $auth = new AuthenticationService();
             //$auth->setStorage($sessionStorage); // Definindo o SessionStorage para a auth
             $authAdapter = $this->getServiceLocator()->get('Zf2User\\Auth\\Adapter');
             $authAdapter->setUsername($data['username']);
             $authAdapter->setPassword($data['password']);
             $result = $auth->authenticate($authAdapter);
             if ($result->isValid()) {
                 $user = $auth->getIdentity();
                 $userArray = $user['user'];
                 $storage = $auth->getStorage();
                 $storage->write($userArray, null);
                 $sessionManager = new SessionManager();
                 if (isset($data['rememberme'])) {
                     $time = 1209600;
                     // 14 days 1209600/3600 = 336 hours => 336/24 = 14 days
                     $sessionManager->rememberMe($time);
                 } else {
                     $time = 86400;
                     // 1day
                     $sessionManager->rememberMe($time);
                 }
                 $redirect = $this->UserAuthentication()->getIdentity()->getRole()->getRedirect();
                 return $this->redirect()->toRoute($redirect);
             } else {
                 $messageResult = $result->getMessages();
                 $this->flashMessenger()->addMessage($messageResult[0]);
                 return $this->redirect()->toRoute('user-auth');
             }
         }
     }
     if ($this->UserAuthentication()->getIdentity()) {
         $redirect = $this->UserAuthentication()->getIdentity()->getRole()->getRedirect();
         return $this->redirect()->toRoute($redirect);
     } else {
         return new ViewModel(array('form' => $form, 'flashMessages' => $this->flashMessenger()->getMessages()));
     }
 }
 /**
  * Metodo para validar acceso al portal
  * @return \Zend\View\Model\ViewModel
  */
 public function ingresoAction()
 {
     if ($this->getRequest()->isPost()) {
         $auth = new AuthenticationService();
         $validate = $this->getRequest()->getPost();
         $authAdapter = new AuthAdapter($this->adapter(), 'usuario', 'usuario_correo', 'usuario_password');
         $authAdapter->setIdentity($validate['correo']);
         $authAdapter->setCredential(md5($validate['password']));
         $resultado = $auth->authenticate($authAdapter);
         switch ($resultado->getCode()) {
             case Result::FAILURE_IDENTITY_NOT_FOUND:
                 $this->message = "Usuario y/o contraseña incorrectos";
                 $this->flashMessenger()->addMessage($this->message);
                 return $this->redirect()->toUrl($this->getRequest()->getBaseUrl() . '/login');
             case Result::FAILURE_CREDENTIAL_INVALID:
                 $this->message = "Usuario y/o contraseña incorrectos";
                 $this->flashMessenger()->addMessage($this->message);
                 return $this->redirect()->toUrl($this->getRequest()->getBaseUrl() . '/login');
             case Result::SUCCESS:
                 $this->flashMessenger()->clearMessages();
                 $store = $auth->getStorage();
                 $store->write($authAdapter->getResultRowObject(null, 'usuario_password'));
                 $sessionConfig = new StandardConfig();
                 $sessionConfig->setRememberMeSeconds(20)->setCookieLifetime(30)->setCookieSecure(true)->setGcMaxlifetime(60)->setGcDivisor(60);
                 $sesionMa = new SessionManager($sessionConfig);
                 $sesionMa->rememberMe(30);
                 $container = new Container('cbol');
                 $container->setExpirationSeconds(1800);
                 $sesionMa->start();
                 $container->idSession = $auth->getIdentity()->perfil_id;
                 $permisos = $this->getPermisos($auth->getIdentity()->usuario_id);
                 $container->permisosUser = $permisos;
                 $indexProfile = \Login\IndexAllProfile::listIndexAllProfiles($auth->getIdentity()->perfil_id);
                 if ($indexProfile == 'vias') {
                     $container->reportesVias = $this->getReportesViales();
                 }
                 if ($indexProfile == 'admin') {
                     $container->sugerencias = $this->getSugerenciasAction();
                 }
                 $container->setDefaultManager($sesionMa);
                 return $this->redirect()->toUrl($this->getRequest()->getBaseUrl() . "/{$indexProfile}");
             default:
                 echo 'Mensaje por defecto';
                 break;
         }
     }
 }
 /**
  * Log in action
  *
  * The method uses Doctrine Entity Manager to authenticate the input data
  *
  * @return Zend\View\Model\ViewModel|array login form|array messages|array navigation menu
  */
 public function loginAction()
 {
     if ($user = $this->identity()) {
         return $this->redirect()->toRoute($this->getOptions()->getLoginRedirectRoute());
     }
     $user = new User();
     $form = $this->getUserFormHelper()->createUserForm($user, 'login');
     $messages = null;
     if ($this->getRequest()->isPost()) {
         $form->setValidationGroup('usernameOrEmail', 'password', 'rememberme', 'csrf', 'captcha');
         $form->setData($this->getRequest()->getPost());
         if ($form->isValid()) {
             $data = $form->getData();
             $authService = $this->getServiceLocator()->get('Zend\\Authentication\\AuthenticationService');
             $adapter = $authService->getAdapter();
             $usernameOrEmail = $this->params()->fromPost('usernameOrEmail');
             try {
                 $user = $this->getEntityManager()->createQuery("SELECT u FROM CsnUser\\Entity\\User u WHERE u.email = '{$usernameOrEmail}' OR u.username = '******'")->getResult(\Doctrine\ORM\Query::HYDRATE_OBJECT);
                 $user = $user[0];
                 if (!isset($user)) {
                     $message = 'The username or email is not valid!';
                     return new ViewModel(array('error' => $this->getTranslatorHelper()->translate('Your authentication credentials are not valid'), 'form' => $form, 'messages' => $messages, 'navMenu' => $this->getOptions()->getNavMenu()));
                 }
                 if ($user->getState()->getId() < 2) {
                     $messages = $this->getTranslatorHelper()->translate('Your username is disabled. Please contact an administrator.');
                     return new ViewModel(array('error' => $this->getTranslatorHelper()->translate('Your authentication credentials are not valid'), 'form' => $form, 'messages' => $messages, 'navMenu' => $this->getOptions()->getNavMenu()));
                 }
                 $adapter->setIdentityValue($user->getUsername());
                 $adapter->setCredentialValue($this->params()->fromPost('password'));
                 $authResult = $authService->authenticate();
                 if ($authResult->isValid()) {
                     $identity = $authResult->getIdentity();
                     $authService->getStorage()->write($identity);
                     if ($this->params()->fromPost('rememberme')) {
                         $time = 1209600;
                         // 14 days (1209600/3600 = 336 hours => 336/24 = 14 days)
                         $sessionManager = new SessionManager();
                         $sessionManager->rememberMe($time);
                     }
                     return $this->redirect()->toRoute($this->getOptions()->getLoginRedirectRoute());
                 }
                 foreach ($authResult->getMessages() as $message) {
                     $messages .= "{$message}\n";
                 }
             } catch (\Exception $e) {
                 return $this->getServiceLocator()->get('csnuser_error_view')->createErrorView($this->getTranslatorHelper()->translate('Something went wrong during login! Please, try again later.'), $e, $this->getOptions()->getDisplayExceptions(), $this->getOptions()->getNavMenu());
             }
         }
     }
     return new ViewModel(array('error' => $this->getTranslatorHelper()->translate('Your authentication credentials are not valid'), 'form' => $form, 'messages' => $messages, 'navMenu' => $this->getOptions()->getNavMenu()));
 }
Пример #9
0
 /**
  *
  * @param unknown $poIdentity
  * @param unknown $psUrlFrom
  */
 public function authentication($poAuthService, $poIdentity, $psUrlFrom = null, $poForm = null, $psType = 'onion')
 {
     $lsStatus = null;
     if ($poIdentity->getActive() == 1) {
         $laUserContext = null;
         if ($poIdentity->get('stIpContext') !== null) {
             $lsUserAgent = '*';
             if ($poIdentity->get('stUserAgent') !== null) {
                 $lsUserAgent = $poIdentity->get('stUserAgent');
             }
             $laUserContext = array($poIdentity->get('stIpContext') => array('denied' => $poIdentity->get('isContextDenied'), $lsUserAgent => $poIdentity->get('stRegistrationToken')));
         }
         if (Context::hasContextAccess($laUserContext)) {
             $loSession = new Session();
             $loSession->clearRegister('OnionAuth');
             $loSession->clearRegister('storage', 'Zend_Auth');
             $poIdentity->getObject();
             $poIdentity->set('stPassword', 'nono');
             $poIdentity->set('stPasswordSalt', '');
             $poIdentity->set('stAnswer', '');
             $loSession->setRegister('OnionAuth', $poIdentity);
             $loIdentity = $loSession->getRegister('OnionAuth');
             $poAuthService->getStorage()->write($poIdentity);
             if ($poForm->get('rememberme')->getValue() == 1) {
                 $laOptions = Config::getAppOptions('settings');
                 $loSessionManager = new SessionManager();
                 $loSessionManager->rememberMe($laOptions['sessionLifeTime']);
             }
             Debug::debug($poIdentity->getUsername() . " [SUCCESS by {$psType}]");
             Access::log($poIdentity, "SUCCESS by " . $psType);
             if ($psUrlFrom !== null) {
                 if ('/' !== $psUrlFrom) {
                     $psUrlFrom = base64_decode($psUrlFrom);
                 }
                 Debug::debug("Redirect to: ({$psUrlFrom})");
                 $this->redirect()->toUrl($psUrlFrom);
             }
         } else {
             $poForm->get('stUsername')->setMessages(array("Permissão negada para o contexto de acesso!"));
             $lsStatus = "CONTEXT DENIED";
         }
     } else {
         $poForm->get('stUsername')->setMessages(array("Usuário desativado!"));
         $lsStatus = "USER DISABLED";
     }
     return $lsStatus;
 }
Пример #10
0
use JeremyKendall\Slim\Auth\Exception\HttpForbiddenException;
use JeremyKendall\Slim\Auth\Exception\HttpUnauthorizedException;
use Zend\Authentication\Storage\Session as SessionStorage;
use Zend\Session\Config\SessionConfig;
use Zend\Session\SessionManager;
require '../lib/Acl.php';
require '../settings.php';
$app = new \Slim\slim(array('mode' => 'developement', 'debug' => true));
// Configure Slim Auth components
$validator = new PasswordValidator();
$adapter = new PdoAdapter(getDb(), 'users', 'username', 'password', $validator);
$acl = new lib\Acl();
$sessionConfig = new SessionConfig();
$sessionConfig->setOptions(array('remember_me_seconds' => 60 * 60 * 24 * 7, 'name' => $applicationFolderName));
$sessionManager = new SessionManager($sessionConfig);
$sessionManager->rememberMe();
$storage = new SessionStorage(null, null, $sessionManager);
$authBootstrap = new Bootstrap($app, $adapter, $acl);
$authBootstrap->setStorage($storage);
$authBootstrap->bootstrap();
require '../lib/notorm/NotORM.php';
$pdo = new PDO('mysql:dbhost=' . $hostname . ';dbname=' . $database . ';charset=utf8', $dbuser, $dbpassword);
$db = new NotORM($pdo);
/* Get users */
$app->get('/users', function () use($app, $db) {
    try {
        $users = array();
        foreach ($db->users() as $user) {
            $users[] = array('id' => $user['id'], 'fname' => $user['fname'], 'lname' => $user['lname'], 'title' => $user['title'], 'username' => $user['username'], 'role' => $user['role'], 'email' => $user['email'], 'status' => $user['status']);
        }
        $app->response()->header('Content-Type', 'application/json');
 /**
  * Retorna o adaptador de sessao
  * @param string $name
  * @return SessionContainer
  */
 public function getSessionAdapter($name = 'Default')
 {
     if (!isset($_SESSION[$name])) {
         $sessionConfig = new SessionConfig();
         $sessionConfig->setOptions($this->globalConfig['session']);
         $sessionStorage = new \Zend\Session\Storage\SessionArrayStorage();
         $sessionManager = new SessionManager();
         $sessionManager->rememberMe($this->globalConfig['session']['remember_me_seconds']);
         $sessionManager->forgetMe();
         $sessionManager->setConfig($sessionConfig);
         $sessionManager->setStorage($sessionStorage);
         $sessionNamespace = new SessionContainer($name, $sessionManager);
         $sessionNamespace->setExpirationSeconds(3600);
         if (!isset($sessionNamespace->init)) {
             $request = new \Zend\Http\PhpEnvironment\Request();
             $sessionNamespace->init = 1;
             $sessionNamespace->remoteAddr = $request->getServer('REMOTE_ADDR');
             $sessionNamespace->httpUserAgent = $request->getServer('HTTP_USER_AGENT');
             /*
              $chain = $sessionManager->getValidatorChain();
              $validatorUserAgent = new \Zend\Session\Validator\HttpUserAgent($sessionNamespace->httpUserAgent);
              $chain->attach('session.validate', array($validatorUserAgent, 'isValid'));
              $validatorAddr = new \Zend\Session\Validator\RemoteAddr($sessionNamespace->remoteAddr);
              $chain->attach('session.validate', array($validatorAddr, 'isValid'));
             
              $sessionManager->setValidatorChain($chain);
             * 
             */
         }
         $sessionNamespace->setDefaultManager($sessionManager);
     } else {
         $sessionNamespace = new SessionContainer($name);
         $sessionNamespace->setExpirationSeconds(3600);
     }
     $this->sessionAdapter = $sessionNamespace;
     return $sessionNamespace;
 }
Пример #12
0
 /**
  * Callback from Facebook.
  *
  * When user goes through the Facebook oAuth 2.0 process
  * of login in, after he has logged into Facebook, he/she is redirected to this
  * this action. Here he/she is authenticated to the system and if that works the user
  * is logged in. If this does not work, the user is asked it this is his first time logging
  * in via Facebook and if he/she is sure that he/she has an account.
  *
  * @return \Zend\Http\Response|ViewModel
  * @throws \Exception
  */
 public function callbackLoginFacebookAction()
 {
     //GET SERVER
     //	 this check has to be done for instances where this
     //	is not run as an web-application
     $server = isset($_SERVER['HTTP_HOST']) ? "http://" . $_SERVER['HTTP_HOST'] : 'http://0.0.0.0';
     //FACEBOOK CONFIG
     //	get config and use it to cnfigure facebook session
     //	and login functionality
     $config = $this->getServiceLocator()->get('Config');
     FacebookSession::setDefaultApplication($config['facebook']['appId'], $config['facebook']['secret']);
     //TODO should this be in a global space
     //ERROR
     $error = $this->params()->fromQuery('error');
     if ($error == 'access_denied') {
         return new ViewModel(['error' => 'access_denied']);
     }
     //KEY
     //	check if there is a query parameter called $key along
     //	for the ride. If so; then the user is trying to connect old account
     //	to Facebook.
     $key = $this->params()->fromQuery('key');
     //TODO validate this key
     //CONNECTING OLD ACCOUNT
     //	if $key is present, then the callback from Facebook will contain it and
     //	we have to reflect it in the callback validation
     $helper = new FacebookRedirectLoginHelper($key ? $server . AuthController::LOGIN_CALLBACK_FACEBOOK . '?key=' . $key : $server . AuthController::LOGIN_CALLBACK_FACEBOOK);
     //LOGIN
     //	try to log in user
     try {
         //FACEBOOK OBJECT
         //	get user object/properties from facebook graph
         $session = $helper->getSessionFromRedirect();
         if (!$session) {
             throw new \Exception("Facebook session was NULL, key[{$key}], url[{$helper->getReRequestUrl()}]");
         }
         $me = (new FacebookRequest($session, 'GET', '/me'))->execute()->getGraphObject(GraphUser::className())->asArray();
         //CONNECT OLD ACCOUNT CUT-IN
         //	if $key is set, then the user is trying to connect old account to his
         //	Facebook. What we do here is to find the user based on the hash that we got
         //	back from facebook, then we inject the Facebook Auth-ID into his table just
         //	in time so that '$auth = new AuthenticationService();' line of code will pick
         //	it up and authenticate the user. This is just a little detour to quickly connect
         //	the user to a facebook account just before we authenticate him.
         if ($key) {
             $sm = $this->getServiceLocator();
             $userService = $sm->get('Stjornvisi\\Service\\User');
             /** @var $userService \Stjornvisi\Service\User */
             if (($user = $userService->getByHash($key)) != null) {
                 $userService->setOauth($user->id, $me['id'], 'facebook', $me['gender']);
                 //USER NOT FOUND
                 //	can't find the user based on hash
             } else {
                 return new ViewModel(['error' => 'user_undefined']);
             }
         }
         //AUTHENTICATE
         //	try to authenticate user against user database
         $auth = new AuthenticationService();
         $sm = $this->getServiceLocator();
         $authAdapter = $sm->get('Stjornvisi\\Auth\\Facebook');
         $authAdapter->setKey($me['id']);
         $result = $auth->authenticate($authAdapter);
         //VALID
         //	user has logged in before via Facebook
         if ($result->isValid()) {
             $sessionManager = new SessionManager();
             $sessionManager->rememberMe(21600000);
             //250 days
             return $this->redirect()->toRoute('home');
             //INVALID
             //	user hasn't logged in with facebook before. We have
             //	to initialize the connection process.
         } else {
             return new ViewModel(['error' => 'user_disconnected']);
         }
         //CAN'T LOGIN USER
         //	Facebook login library issues exception.
         //	Facebook returns an error
     } catch (FacebookRequestException $ex) {
         // When Facebook returns an error
         return new ViewModel(['error' => $ex->getMessage()]);
         //ERROR
         //	There was a more generic error
         //	When validation fails or other local issues
     }
     /*catch(\Exception $ex) {
       return new ViewModel(array(
       'error' => $ex->getMessage()
       ));
       }*/
 }