/*
Rediect to Server isLogin Controller
@return redirect
160314
private function toServerIsLogin()
	{
		$isLoginUrl = $this->_config['isLogin'].$this->signature().'&appId='.$this->_config['appId'].'&callback='.$this->_callback;
		header('Location:'.$isLoginUrl);
	}
1218615
public function indexAction()
    {
        if ($this->auth->hasIdentity()) {
            return $this->redirect()->toRoute('lang');
        }

        $viewModel        = new ViewModel();
        /* @var $loginForm Login */
        $loginForm        = $this->forms[self::LOGIN];
        /* @var $registerForm Register */
        $registerForm = $this->forms[self::REGISTER];

        /* @var $request \Zend\Http\Request */
        $request   = $this->getRequest();

        if ($request->isPost()) {
            $data                          = $this->params()->fromPost();
            $adapter                       = $this->userLoginAdapter;
            // inject suffixes via shared Events
            $loginSuffix                   = '';
            // @TODO: replace this by the Plugin LoginFilter
            $e                             = $this->getEvent();
            $loginSuffixResponseCollection = $this->getEventManager()->trigger('login.getSuffix', $e);
            if (!$loginSuffixResponseCollection->isEmpty()) {
                $loginSuffix = $loginSuffixResponseCollection->last();
            }

            $loginForm->setData($data);
            if (array_key_exists('credentials', $data) &&
                array_key_exists('login', $data['credentials']) &&
                array_key_exists('credential', $data['credentials'])) {
                $adapter->setIdentity($data['credentials']['login'] . $loginSuffix)
                    ->setCredential($data['credentials']['credential']);
            }
            
            $auth   = $this->auth;
            $result = $auth->authenticate($adapter);
            
            
            if ($result->isValid()) {
                $user = $auth->getUser();
                $language = $this->locale->detectLanguage($request, $user);
                $this->logger->info('User ' . $user->getLogin() . ' logged in');
                
                $ref = $this->params()->fromQuery('ref', false);

                if ($ref) {
                    $ref = urldecode($ref);
                    $url = preg_replace('~/[a-z]{2}(/|$)~', '/' . $language . '$1', $ref);
                    $url = $request->getBasePath() . $url;
                } else {
                    $urlHelper = $this->viewHelperManager->get('url');
                    $url = $urlHelper('lang', array('lang' => $language));
                }
                $this->notification()->success(/*@translate*/ 'You are now logged in.');
                return $this->redirect()->toUrl($url);
            } else {
                $loginName = $data['credentials']['login'];
                if (!empty($loginSuffix)) {
                    $loginName = $loginName . ' (' . $loginName . $loginSuffix . ')';
                }
                $this->logger->info('Failed to authenticate User ' . $loginName);
                $this->notification()->danger(/*@translate*/ 'Authentication failed.');
            }
        }
        
        $ref = $this->params()->fromQuery('ref', false);
        
        if ($ref) {
            $req = $this->params()->fromQuery('req', false);
            if ($req) {
                $this->getResponse()->setStatusCode(Response::STATUS_CODE_401);
                $viewModel->setVariable('required', true);
            }
            $viewModel->setVariable('ref', $ref);
        }

        $allowRegister = $this->options->getEnableRegistration();
        $allowResetPassword = $this->options->getEnableResetPassword();
        if (isset($allowRegister)) {
            $viewModel->setVariables(
                [
                    'allowRegister' => $allowRegister,
                    'allowResetPassword' => $allowResetPassword
                ]
            );
        }

        $viewModel->setVariable('loginForm', $loginForm);
        $viewModel->setVariable('registerForm', $registerForm);

        /* @deprecated use loginForm instead of form in your view scripts */
        $viewModel->setVariable('form', $loginForm);


        return $viewModel;
    }
758598
public function postLogin()
    {
        $remember = Binput::get('rememberMe');

        $input = Binput::only(['email', 'password']);

        $rules = UserRepository::rules(array_keys($input));
        $rules['password'] = 'required|min:6';

        $val = UserRepository::validate($input, $rules, true);
        if ($val->fails()) {
            return Redirect::route('account.login')->withInput()->withErrors($val->errors());
        }

        $this->throttler->hit();

        try {
            $throttle = Credentials::getThrottleProvider()->findByUserLogin($input['email']);
            $throttle->check();

            Credentials::authenticate($input, $remember);
        } catch (WrongPasswordException $e) {
            return Redirect::route('account.login')->withInput()->withErrors($val->errors())
                ->with('error', 'Your password was incorrect.');
        } catch (UserNotFoundException $e) {
            return Redirect::route('account.login')->withInput()->withErrors($val->errors())
                ->with('error', 'That user does not exist.');
        } catch (UserNotActivatedException $e) {
            if (Config::get('credentials::activation')) {
                return Redirect::route('account.login')->withInput()->withErrors($val->errors())
                ->with('error', 'You have not yet activated this account.');
            } else {
                $throttle->user->attemptActivation($throttle->user->getActivationCode());
                $throttle->user->addGroup(Credentials::getGroupProvider()->findByName('Users'));

                return $this->postLogin();
            }
        } catch (UserSuspendedException $e) {
            $time = $throttle->getSuspensionTime();

            return Redirect::route('account.login')->withInput()->withErrors($val->errors())
                ->with('error', "Your account has been suspended for $time minutes.");
        } catch (UserBannedException $e) {
            return Redirect::route('account.login')->withInput()->withErrors($val->errors())
                ->with('error', 'You have been banned. Please contact support.');
        }

        return Redirect::intended(Config::get('credentials.home', '/'));
    }
1037156
public function getLogout()
    {

        new UserEvent(UserEvent::LOGOUT_EVENT, $this->auth->user());

        $this->auth->logout();

        return redirect()->route('login');
    }
42185
public function logout()
    {
        $controller = $this->getController();
        $result = $this->getAuthenticationService()->clearIdentity(
            $controller->request,
            $controller->response
        );

        $controller->request = $result['request'];
        $controller->response = $result['response'];

        $this->dispatchEvent('Authentication.logout', [], $controller);

        $logoutRedirect = $this->getConfig('logoutRedirect');
        if ($logoutRedirect === false) {
            return null;
        }

        return Router::normalize($logoutRedirect);
    }
1330954
public function redirectToRoute()
    {
        if ($this->getRequest()
                 ->isXmlHttpRequest()) {
            return [
                'redirect' => call_user_func_array(
                    [
                        $this->url(),
                        'fromRoute',
                    ],
                    func_get_args()
                ),
            ];
        }

        return call_user_func_array(
            [
                $this->redirect(),
                'toRoute',
            ],
            func_get_args()
        );
    }
1242672
public function registerAction()
    {
        // if the user is logged in, we don't need to register
        if ($this->zfcUserAuthentication()->hasIdentity()) {
            // redirect to the login redirect route
            return $this->redirect()->toRoute($this->getOptions()->getLoginRedirectRoute());
        }
        // if registration is disabled
        if (!$this->getOptions()->getEnableRegistration()) {
            return array('enableRegistration' => false);
        }

        $request = $this->getRequest();
        $service = $this->getUserService();
        $form = $this->getRegisterForm();

        if ($this->getOptions()->getUseRedirectParameterIfPresent() && $request->getQuery()->get('redirect')) {
            $redirect = $request->getQuery()->get('redirect');
        } else {
            $redirect = false;
        }

        $redirectUrl = $this->url()->fromRoute(static::ROUTE_REGISTER)
            . ($redirect ? '?redirect=' . rawurlencode($redirect) : '');
        $prg = $this->prg($redirectUrl, true);

        if ($prg instanceof Response) {
            return $prg;
        } elseif ($prg === false) {
            return array(
                'registerForm' => $form,
                'enableRegistration' => $this->getOptions()->getEnableRegistration(),
                'redirect' => $redirect,
            );
        }

        $post = $prg;
        $user = $service->register($post);

        $redirect = isset($prg['redirect']) ? $prg['redirect'] : null;

        if (!$user) {
            return array(
                'registerForm' => $form,
                'enableRegistration' => $this->getOptions()->getEnableRegistration(),
                'redirect' => $redirect,
            );
        }

        if ($service->getOptions()->getLoginAfterRegistration()) {
            $identityFields = $service->getOptions()->getAuthIdentityFields();
            if (in_array('email', $identityFields)) {
                $post['identity'] = $user->getEmail();
            } elseif (in_array('username', $identityFields)) {
                $post['identity'] = $user->getUsername();
            }
            $post['credential'] = $post['password'];
            $request->setPost(new Parameters($post));
            return $this->forward()->dispatch(static::CONTROLLER_NAME, array('action' => 'authenticate'));
        }

        // TODO: Add the redirect parameter here...
        return $this->redirect()->toUrl($this->url()->fromRoute(static::ROUTE_LOGIN) . ($redirect ? '?redirect='. rawurlencode($redirect) : ''));
    }
473758
public function logoutAction()
    {
        $auth = $this->getServiceLocator()->get('Zend\Authentication\AuthenticationService');
        if ($auth->hasIdentity()) {
            $auth->clearIdentity();
            $sessionManager = new SessionManager();
            $sessionManager->forgetMe();
        }

        return $this->redirect()->toRoute($this->getOptions()->getLogoutRedirectRoute());
    }
276636
public function redirect()
    {
        $state = null;

        if ($this->usesState()) {
            $this->request->getSession()->set('state', $state = Str::random(40));
        }

        return new RedirectResponse($this->getAuthUrl($state));
    }
705563
public function actionLogin($view = 'login', $partial = false)
    {
        if (!\Yii::$app->user->isGuest) {
            return $this->goHome();
        }
        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->redirect($this->getLoginRedirect());
        }
        if (\Yii::$app->request->isAjax || $partial) {
            return $this->renderAjax($view, compact('model'));
        }
        return $this->render($view, compact('model'));
    }
738102
public function loginAction()
    {
        $return = $this->getReturnUri();
        $auth   = $this->getServiceLocator()
                       ->get( 'Zend\Authentication\AuthenticationService' );

        if ( $auth->hasIdentity() )
        {
            return $this->redirect()
                        ->toUrl( $this->getValidReturnUri( $return ) );
        }

        /* @var $form \Zend\Form\Form */
        $request = $this->getRequest();
        $data    = $request->getPost();
        $form    = $this->getServiceLocator()
                        ->get( 'Form' )
                        ->create( 'Grid\User\Login', array(
                            'returnUri' => $return,
                        ) );

        $form->setData( $data );

        if ( $request->isPost() )
        {
            if ( $form->isValid() )
            {
                /* @var $sessm \Zend\Session\SessionManager */
                /* @var $logger \Zork\Log\LoggerManager */
                $data   = $form->getData();
                $sessm  = $this->getSessionManager();
                $logger = $this->getServiceLocator()
                               ->get( 'Zork\Log\LoggerManager' );
                $result = $this->getServiceLocator()
                               ->get( 'Grid\User\Authentication\Service' )
                               ->login( $data, $sessm, $auth );

                $messages = $result->getMessages();

                if ( $result->isValid() )
                {
                    $sessm->regenerateId( false );

                    $this->messenger()
                         ->add( 'user.form.login.success',
                                'user', Message::LEVEL_INFO );

                    if ( $logger->hasLogger( 'application' ) )
                    {
                        $logger->getLogger( 'application' )
                               ->notice( 'user-login', array(
                                   'successful' => true,
                               ) );
                    }
                }
                else
                {
                    foreach ( $messages as $index => $message )
                    {
                        if ( is_int( $index ) && is_string( $message ) )
                        {
                            $this->messenger()
                                 ->add( $message, false, Message::LEVEL_WARN );
                        }
                    }

                    $this->messenger()
                         ->add( $this->getErrorMessageKey( $result->getCode() ),
                                'user', Message::LEVEL_ERROR );

                    if ( $logger->hasLogger( 'application' ) )
                    {
                        $logger->getLogger( 'application' )
                               ->warn( 'user-login', array(
                                   'successful' => false,
                               ) );
                    }
                }

                if ( empty( $messages['returnUri'] ) )
                {
                    if ( empty( $data['returnUri'] ) )
                    {
                        $returnUri = $return;
                    }
                    else
                    {
                        $returnUri = $data['returnUri'];
                    }
                }
                else
                {
                    $returnUri = $messages['returnUri'];
                }

                return $this->redirect()
                            ->toUrl( $this->getValidReturnUri( $returnUri ) );
            }
        }

        $this->plugin( 'layout' )
             ->setMiddleLayout( 'layout/middle/center' );

        return array(
            'form'      => $form,
            'display'   => $this->getServiceLocator()
                                ->get( 'Config' )
                                     [ 'modules' ]
                                     [ 'Grid\User' ]
                                     [ 'display' ]
        );
    }
1271147
public function doLogin($data, MemberLoginForm $form, HTTPRequest $request)
    {
        /**
         * @var ValidationResult $message
         * @var Member|MemberExtension $member
         */
        $member = $this->checkLogin($data, $request, $message);

        if (!$member) {
            return $this->redirectBack();
        }

        // If we're in grace period, continue to the parent
        if ($member->isInGracePeriod()) {
            return parent::doLogin($data, $form, $request);
        }

        if ($message->isValid()) {
            /** @var Session $session */
            $session = $request->getSession();
            $session->set(BootstrapMFAAuthenticator::SESSION_KEY . '.MemberID', $member->ID);
            $session->set(BootstrapMFAAuthenticator::SESSION_KEY . '.Data', $data);
            if (!empty($data['BackURL'])) {
                $session->set(BootstrapMFAAuthenticator::SESSION_KEY . '.BackURL', $data['BackURL']);
            }

            return $this->redirect($this->link('verify'));
        }

        return $this->redirectBack();
    }
560498
public function logoutAction()
    {
        $this->cmsAuthentication()->logout();

        if ($redirect = $this->getRedirectParameter()) {
            return $this->redirect()->toUrl($redirect);
        }

        $redirect = $this->params()->fromRoute('redirect', $this->options->getLogoutRedirectRoute());

        return $this->redirect()->toRoute($redirect);
    }
245483
protected function _get()
    {
        $subject = $this->_subject();
        $this->_trigger('beforeLogout', $subject);

        $subject->set([
            'success' => true,
            'redirectUrl' => $this->_controller()->Auth->logout()
        ]);

        $this->_trigger('afterLogout', $subject);
        $this->setFlash('success', $subject);

        return $this->_redirect(
            $subject,
            $subject->redirectUrl
        );
    }
1346918
public function login()
    {
        $this->setTokenFromCookies();

        if (!empty($this->csrfToken)) {
            $this->loggedIn = true;
        }

        return $this;
    }
574543
public function logoutAction()
    {
        $this->zfcUserAuthentication()->getAuthAdapter()->resetAdapters();
        $this->zfcUserAuthentication()->getAuthAdapter()->logoutAdapters();
        $this->zfcUserAuthentication()->getAuthService()->clearIdentity();

        $redirect = $this->redirectCallback;

        return $redirect();
    }
239918
public function loginWithAction()
    {
        $return = $this->getReturnUri();
        $auth   = $this->getServiceLocator()
                       ->get( 'Zend\Authentication\AuthenticationService' );

        if ( $auth->hasIdentity() )
        {
            return $this->redirect()
                        ->toUrl( $this->getValidReturnUri( $return ) );
        }

        $request = $this->getRequest();
        $data    = $request->getQuery()
                           ->toArray();

        if ( $request->isPost() )
        {
            $data = array_merge( $data, $request->getPost()
                                                ->toArray() );
        }

        /* @var $sessm \Zend\Session\SessionManager */
        /* @var $logger \Zork\Log\LoggerManager */
        $sessm  = $this->getSessionManager();
        $logger = $this->getServiceLocator()
                       ->get( 'Zork\Log\LoggerManager' );
        $result = $this->getServiceLocator()
                       ->get( 'Grid\User\Authentication\Service' )
                       ->login( $data, $sessm, $auth );

        $messages   = $result->getMessages();
        $with       = empty( $messages['loginWith'] )
                    ? 'other'
                    : $messages['loginWith'];

        if ( $result->isValid() )
        {
            $sessm->regenerateId( false );

            $this->messenger()
                 ->add( 'user.form.login.success',
                        'user', Message::LEVEL_INFO );

            if ( $logger->hasLogger( 'application' ) )
            {
                $logger->getLogger( 'application' )
                       ->notice( 'user-login', array(
                           'successful' => true,
                           'loginWith'  => $with,
                       ) );
            }
        }
        else
        {
            foreach ( $messages as $index => $message )
            {
                if ( is_int( $index ) && is_string( $message ) )
                {
                    $this->messenger()
                         ->add( $message, false, Message::LEVEL_WARN );
                }
            }

            $this->messenger()
                 ->add( $this->getErrorMessageKey( $result->getCode() ),
                        'user', Message::LEVEL_ERROR );

            if ( $logger->hasLogger( 'application' ) )
            {
                $logger->getLogger( 'application' )
                       ->warn( 'user-login', array(
                           'successful' => false,
                           'loginWith'  => $with,
                       ) );
            }
        }

        if ( ! empty( $messages['registered'] ) )
        {
            $user = $result->getIdentity();

            $this->getServiceLocator()
                 ->get( 'Grid\Mail\Model\Template\Sender' )
                 ->prepare( array(
                     'template' => 'user.login-with',
                     'locale'   => $user->locale,
                 ) )
                 ->send( array(
                     'email'        => $user->email,
                     'display_name' => $user->displayName,
                     'confirm_url'  => null,
                 ), array(
                     $user->email   => $user->displayName,
                 ) );
        }

        if ( empty( $messages['returnUri'] ) )
        {
            if ( empty( $data['returnUri'] ) )
            {
                $returnUri = $return;
            }
            else
            {
                $returnUri = $data['returnUri'];
            }
        }
        else
        {
            $returnUri = $messages['returnUri'];
        }

        return $this->redirect()
                    ->toUrl( $this->getValidReturnUri( $returnUri ) );
    }