Log in action

The method uses cmsAuthentication controller plugin to authenticate the input data

@return Response|ViewModel
14391
public function loginAction()
    {
        $authPlugin = $this->cmsAuthentication();

        $redirectKey = $this->options->getRedirectKey();
        $redirect = $this->options->getUseRedirectParameter()
            ? $this->params()->fromQuery($redirectKey, false)
            : false;

        $url = $this->url()->fromRoute(
            null,
            [],
            $redirect ? ['query' => [$redirectKey => $redirect]] : []
        );

        $prg = $this->prg($url, true);
        // Return early if prg plugin returned a response
        if ($prg instanceof Response) {
            return $prg;
        }

        $post = $prg;

        $form = $this->loginForm;
        $fm   = $this->flashMessenger();

        if ($this->forwardingController && $fm->hasCurrentErrorMessages()) {
            foreach($fm->getCurrentErrorMessages() as $messages) {
                $form->setMessages($messages);
            }
            $fm->clearCurrentMessages($fm::NAMESPACE_ERROR);
        } elseif ($fm->hasErrorMessages()) {
            foreach($fm->getErrorMessages() as $messages) {
                $form->setMessages($messages);
            }
        }

        $form->setAttribute('action', $this->url()->fromRoute());
        if ($redirect) {
            $form->get($redirectKey)->setValue($redirect);
        }

        if ($post && $form->setData($post)->isValid()) {

            // clear adapters
            $this->cmsAuthentication()->getAuthenticationAdapter()->resetAdapters();
            $this->cmsAuthentication()->getAuthenticationService()->clearIdentity();

            $routeMatch = $this->getEvent()->getRouteMatch();
            $this->getRequest()->setPost(new Parameters($post));
            $this->options->setLoginRoute($routeMatch->getMatchedRouteName());
            $this->forwardingController = $routeMatch->getParam('controller');

            return $this->forward()->dispatch(
                $this->forwardingController,
                ['action' => 'authenticate']
            );
        }

        $this->forwardingController = null;

        $registrationRoute    = $this->options->getRegistrationRoute();
        $resetCredentialRoute = $this->options->getResetCredentialRoute();

        return new ViewModel(compact('form', 'registrationRoute', 'resetCredentialRoute'));
    }
23090
public function loginpageAction()
    {
        $view = $this->forward()->dispatch('MelisCore\Controller\PluginView',
            [
                'action' => 'generate',
                'appconfigpath' => '/meliscore_login',
                'keyview' => 'meliscore_login',
            ]);

        $background = '';
        $melisMelisCoreConfig = $this->serviceLocator->get('MelisCoreConfig');
        $appConfigForm = $melisMelisCoreConfig->getItem('/meliscore_login');
        if (!empty($appConfigForm['datas']['login_background'])) {
            $background = $appConfigForm['datas']['login_background'];
        }

        $schemeSvc = $this->getServiceLocator()->get('MelisCorePlatformSchemeService');
        $schemeData = $schemeSvc->getCurrentScheme();

        $bundleAsset = $this->getServiceLocator()->get('MelisAssetManagerWebPack')->getAssets();


        $this->layout()->addChild($view, 'content');

        $this->layout()->isLogin = 1;
        $this->layout()->login_background = $background;
        $this->layout()->schemes = $schemeData;
        $this->layout()->bundle = $bundleAsset;

        return $view;

    }
175174
public function authenticateAction()
    {
        if ($this->zfcUserAuthentication()->hasIdentity()) {
            return $this->redirect()->toRoute($this->getOptions()->getLoginRedirectRoute());
        }

        $adapter = $this->zfcUserAuthentication()->getAuthAdapter();
        $redirect = $this->params()->fromPost('redirect', $this->params()->fromQuery('redirect', false));

        $result = $adapter->prepareForAuthentication($this->getRequest());

        // Return early if an adapter returned a response
        if ($result instanceof Response) {
            return $result;
        }

        $auth = $this->zfcUserAuthentication()->getAuthService()->authenticate($adapter);

        if (!$auth->isValid()) {
            $this->flashMessenger()->setNamespace('zfcuser-login-form')->addMessage($this->failedLoginMessage);
            $adapter->resetAdapters();
            return $this->redirect()->toUrl(
                $this->url()->fromRoute(static::ROUTE_LOGIN) .
                ($redirect ? '?redirect='. rawurlencode($redirect) : '')
            );
        }

        $redirect = $this->redirectCallback;

        return $redirect();
    }
278759
public function login()
    {
        $this->authSessionId = $this->requestAuthSessionID($this->user,
            $this->password);
        return $this->lastResponseCode == 200;
    }
745539
public function actionLogin()
	{
		$model=Yii::createComponent('gii.models.LoginForm');

		// collect user input data
		if(isset($_POST['LoginForm']))
		{
			$model->attributes=$_POST['LoginForm'];
			// validate user input and redirect to the previous page if valid
			if($model->validate() && $model->login())
				$this->redirect(array('index'));
		}
		// display the login form
		$this->render('login',array('model'=>$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' ]
        );
    }
730800
public function actionLogin()
    {
        /** @var \amnah\yii2\user\models\forms\LoginForm $model */
        $model = $this->module->model("LoginForm");

        // load post data and login
        $post = Yii::$app->request->post();
        if ($model->load($post) && $model->validate()) {
            $returnUrl = $this->performLogin($model->getUser(), $model->rememberMe);
            return $this->redirect($returnUrl);
        }

        return $this->render('login', compact("model"));
    }
382670
public function loginAction()
    {
        $request = $this->getRequest();
        $session = $request->getSession();
        if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
            $error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
        } else {
            $error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
            $session->remove(SecurityContext::AUTHENTICATION_ERROR);
        }

        $view = $this
            ->view()
            ->setTemplate($this->config->getTemplate('login.html'))
            ->setTemplateVar($this->config->getPluralResourceName())
            ->setData(array(
                'last_username' => $session->get(SecurityContext::LAST_USERNAME),
                'error'         => $error
            ));

        return $this->handleView($view);
    }
1344081
public function loginAction()
    {
        if (!$this->getSecurityContext()->hasCustomerUser()) {
            $request = $this->getRequest();
            $customerLoginForm = new CustomerLogin($request);

            try {
                $form = $this->validateForm($customerLoginForm, "post");

                // If User is a new customer
                if ($form->get('account')->getData() == 0 && $form->get("email")->getErrors()->count() == 0) {
                    return $this->generateRedirectFromRoute(
                        "customer.create.process",
                        ["email" => $form->get("email")->getData()]
                    );
                } else {
                    try {
                        $authenticator = new CustomerUsernamePasswordFormAuthenticator($request, $customerLoginForm);

                        /** @var Customer $customer */
                        $customer = $authenticator->getAuthentifiedUser();

                        $this->processLogin($customer);

                        if (intval($form->get('remember_me')->getData()) > 0) {
                            // If a remember me field if present and set in the form, create
                            // the cookie thant store "remember me" information
                            $this->createRememberMeCookie(
                                $customer,
                                $this->getRememberMeCookieName(),
                                $this->getRememberMeCookieExpiration()
                            );
                        }

                        return $this->generateSuccessRedirect($customerLoginForm);

                    } catch (UsernameNotFoundException $e) {
                        $message = $this->getTranslator()->trans(
                            "Wrong email or password. Please try again",
                            [],
                            Front::MESSAGE_DOMAIN
                        );
                    } catch (WrongPasswordException $e) {
                        $message = $this->getTranslator()->trans(
                            "Wrong email or password. Please try again",
                            [],
                            Front::MESSAGE_DOMAIN
                        );
                    } catch (CustomerNotConfirmedException $e) {
                        if ($e->getUser() !== null) {
                            // Send the confirmation email again
                            $this->getDispatcher()->dispatch(
                                TheliaEvents::SEND_ACCOUNT_CONFIRMATION_EMAIL,
                                new CustomerEvent($e->getUser())
                            );
                        }
                        $message = $this->getTranslator()->trans(
                            "Your account is not yet confirmed. A confirmation email has been sent to your email address, please check your mailbox",
                            [],
                            Front::MESSAGE_DOMAIN
                        );
                    } catch (AuthenticationException $e) {
                        $message = $this->getTranslator()->trans(
                            "Wrong email or password. Please try again",
                            [],
                            Front::MESSAGE_DOMAIN
                        );
                    }

                }
            } catch (FormValidationException $e) {
                $message = $this->getTranslator()->trans(
                    "Please check your input: %s",
                    ['%s' => $e->getMessage()],
                    Front::MESSAGE_DOMAIN
                );
            } catch (\Exception $e) {
                $message = $this->getTranslator()->trans(
                    "Sorry, an error occured: %s",
                    ['%s' => $e->getMessage()],
                    Front::MESSAGE_DOMAIN
                );
            }

            Tlog::getInstance()->error(
                sprintf(
                    "Error during customer login process : %s. Exception was %s",
                    $message,
                    $e->getMessage()
                )
            );

            $customerLoginForm->setErrorMessage($message);

            $this->getParserContext()->addForm($customerLoginForm);

            if ($customerLoginForm->hasErrorUrl()) {
                return $this->generateErrorRedirect($customerLoginForm);
            }
        }
    }
1281541
private function authenticateWithPassword()
    {
        if ($this->credentials->havePassword()) {
            $authCommand = new Auth();
            $authCommand->setArguments([$this->credentials->getPassword()]);
            $authResponse = $this->connection->execute($authCommand);
            $response = $authCommand->parse($authResponse);
            if ($response !== self::AUTH_SUCCESS_MESSAGE) {
                throw new AuthenticationException();
            }
        }
    }
544894
public function onSignin()
    {
        try {
            /*
             * Validate input
             */
            $data = post();
            $rules = [];

            $rules['login'] = $this->loginAttribute() == UserSettings::LOGIN_USERNAME
                ? 'required|between:2,255'
                : 'required|email|between:6,255';

            $rules['password'] = 'required|between:4,255';

            if (!array_key_exists('login', $data)) {
                $data['login'] = post('username', post('email'));
            }

            $validation = Validator::make($data, $rules);
            if ($validation->fails()) {
                throw new ValidationException($validation);
            }

            /*
             * Authenticate user
             */
            $credentials = [
                'login'    => array_get($data, 'login'),
                'password' => array_get($data, 'password')
            ];

            Event::fire('rainlab.user.beforeAuthenticate', [$this, $credentials]);

            $user = Auth::authenticate($credentials, true);
            if ($user->isBanned()) {
                Auth::logout();
                throw new AuthException(/*Sorry, this user is currently not activated. Please contact us for further assistance.*/'rainlab.user::lang.account.banned');
            }

            /*
             * Redirect
             */
            if ($redirect = $this->makeRedirection(true)) {
                return $redirect;
            }
        }
        catch (Exception $ex) {
            if (Request::ajax()) throw $ex;
            else Flash::error($ex->getMessage());
        }
    }
914623
public function actionLogin()
    {
        if (! Yii::$app->getUser()->getIsGuest()) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->getRequest()->post()) && $model->login()) {
            return $this->goBack();
        } else {
            return $this->renderPartial('login', [
                'model' => $model,
            ]);
        }
    }
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;
    }
270323
public function headerLogoutAction()
    {
        $melisKey = $this->params()->fromRoute('melisKey', '');

        $view = new ViewModel();
        $view->melisKey = $melisKey;

        return $view;
    }
861312
public function authenticate()
	{
		// Already got some credentials stored?
		if ($this->token)
		{
			$response = $this->verifyCredentials();

			if ($response)
			{
				return $this->token;
			}
			else
			{
				$this->token = null;
			}
		}

		// Check for callback.
		if (strcmp($this->version, '1.0a') === 0)
		{
			$verifier = $this->input->get('oauth_verifier');
		}
		else
		{
			$verifier = $this->input->get('oauth_token');
		}

		if (empty($verifier))
		{
			// Generate a request token.
			$this->_generateRequestToken();

			// Authenticate the user and authorise the app.
			$this->_authorise();
		}

		// Callback
		else
		{
			$session = $this->application->getSession();

			// Get token form session.
			$this->token = array('key' => $session->get('key', null, 'oauth_token'), 'secret' => $session->get('secret', null, 'oauth_token'));

			// Verify the returned request token.
			if (strcmp($this->token['key'], $this->input->get('oauth_token')) !== 0)
			{
				throw new \DomainException('Bad session!');
			}

			// Set token verifier for 1.0a.
			if (strcmp($this->version, '1.0a') === 0)
			{
				$this->token['verifier'] = $this->input->get('oauth_verifier');
			}

			// Generate access token.
			$this->_generateAccessToken();

			// Return the access token.
			return $this->token;
		}
	}
1244343
public function login()
    {
        $this->loadModel('CakeManager.Roles');

        // Redirect if user is already logged in
        if ($this->authUser) {
            $redirect = $this->Roles->redirectFrom($this->authUser['role_id']);
            return $this->redirect($redirect);
        }

        if ($this->request->is('post')) {
            $user = $this->Auth->identify();
            if ($user) {
                $this->Auth->setUser($user);

                $redirect = $this->Roles->redirectFrom($user['role_id']);

                // firing an event: afterLogin
                $_event = new Event('Controller.Users.afterLogin', $this, [
                    'user' => $user
                ]);
                $this->eventManager()->dispatch($_event);

                return $this->redirect($redirect);
            }

            // firing an event: afterInvalidLogin
            $_event = new Event('Controller.Users.afterInvalidLogin', $this, [
                'user' => $user
            ]);
            $this->eventManager()->dispatch($_event);

            $this->Flash->error(__('Your username or password is incorrect.'));
        }

        $this->set('registerEnabled', Configure::read('CM.Register'));

        $this->render(Configure::read('CM.UserViews.login'));
    }
393004
public function actionLogin()
    {
        if (!Yii::$app->user->isGuest) {
            Yii::$app->session->setFlash('danger', Yii::t('user', 'You are already logged in.'));
            return $this->goHome();
        }
        if (Yii::$app->request->isGet) {
            Yii::$app->user->setReturnUrl(Yii::$app->request->getReferrer());
        }

        /**
         * @var LoginForm $model
         */
        $model = new LoginForm();
        if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($model->load(Yii::$app->getRequest()->post()) && $model->login()) {
            return $this->goBack(Yii::$app->getHomeUrl());
        }
        if (Yii::$app->request->isAjax) {
            return $this->renderAjax('login_modal', [
                'model' => $model,
                'module' => $this->module,
            ]);
        }
        return $this->render('login', ['model' => $model, 'module' => $this->module]);
    }