Login user

@return New session ID on success, null otherwise.

@note When using Reference to log in, check returned Reference
object using Reference::isNullRef().

@see Timing attack prevention:
http://blog.ircmaxell.com/2014/11/its-all-about-time.html
765777
protected function login($ref, $user, $password)
	{
		// Get user
		$user_filters = $this->user_login_filters;
		$user_filters[$this->user_login_property] = $user;
		$user_list = $this->backend->createListing($user_filters)->fetchAll();
		if (empty($user_list)) {
			$user_ref = null;
		} else {
			$user_ref = reset($user_list);
		}

		// Check password
		$dummy_hash = password_hash((string) time(), PASSWORD_DEFAULT); // prevent timing attack to $user
		$passwd_hash = $user_ref ? $user_ref[$this->user_password_property] : $dummy_hash;
		$passwd_valid = $user_ref && password_verify($password, $passwd_hash);

		if (!$passwd_valid) {
			// One more protection against timing attack
			time_nanosleep(0, abs(crc32($user.$password.time().__FILE__) % 200000));
			return null;
		}

		// Login OK - generate session token
		$session_id = base64_encode(openssl_random_pseudo_bytes(12));
		$session_token = base64_encode(openssl_random_pseudo_bytes(24));

		// Store session token
		$n = $this->flupdo->insert()->into($this->flupdo->quoteIdent($this->table))
			->insert($this->flupdo->quoteIdent($this->table_columns['session_id']))
			->insert($this->flupdo->quoteIdent($this->table_columns['session_token']))
			->insert($this->flupdo->quoteIdent($this->table_columns['user_id']))
			->values([[$session_id, password_hash($session_token, PASSWORD_DEFAULT), $user_ref->id]])
			->exec();

		if ($n == 1) {
			return $session_id;
		} else {
			return null;
		}
	}
334297
public function getUserLoginAttempt()
    {
        if (!$this->_attempt) {
            $this->_attempt = new UserLoginAttempt;
            $this->_attempt->key = $this->getKey();
        }
        return $this->_attempt;
    }
1130892
public function login()
    {
        $response = parent::soapCall('login', array($this->getCredentials()));

        $this->setLoginResult($response->getResult());

        $this->setOption('location', $this->loginResult->getServerUrl());

        $this->lastLoginTime = time();

        return $response;
    }
730791
public function user()
    {
        if ($this->loggedOut) {
            return;
        }

        // If we have already retrieved the user for the current request we can just
        // return it back immediately. We do not want to pull the user data every
        // request into the method because that would tremendously slow an app.
        if (! is_null($this->user)) {
            return $this->user;
        }

        $id = $this->session->get($this->getName());

        // First we will try to load the user using the identifier in the session if
        // one exists. Otherwise we will check for a "remember me" cookie in this
        // request, and if one exists, attempt to retrieve the user using that.
        $user = null;

        if (! is_null($id)) {
            $user = $this->provider->retrieveByID($id);
        }

        // If the user is null, but we decrypt a "recaller" cookie we can attempt to
        // pull the user data on that cookie which serves as a remember cookie on
        // the application. Once we have a user we can return it to the caller.
        $recaller = $this->getRecaller();

        if (is_null($user) && ! is_null($recaller)) {
            $user = $this->getUserByRecaller($recaller);
        }

        return $this->user = $user;
    }
423251
public function user()
    {
        // If we've already retrieved the user for the current request we can just
        // return it back immediately. We do not want to fetch the user data on
        // every call to this method because that would be tremendously slow.
        if (!is_null($this->user)) {
            return $this->user;
        }
        $user = NULL;
        $token = $this->getTokenForRequest();
        if (!empty($token)) {
            $user = $this->retrieveByToken($token);
        }

        return $this->user = $user;
    }
274661
public function login()
    {
        if ($this->validate()) {
            $this->trigger(self::GET_ACCESS_TOKEN);
            if($this->_user != null) {
                $this ->_user = User::findByUsername($this->username);
            }
            return $this->_user;
        } else {
            return null;
        }
    }
1063369
protected function getLoggedUser()
    {
        $user = $this->get('security.token_storage')->getToken()->getUser();
        if (is_string($user)) {
            $user = null;
        }

        return $user;
    }
247542
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 = '$usernameOrEmail'")->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()
        ));
    }
903341
public function login()
	{
		return $this->select_logins()
			->where( 'restore_id', $this->user->{$this->config->user_key} )
			->where( 'restore_token', $this->restore_key( $this->user ) )
			->limit( 1 )
			->run();
	}
1200625
public function id()
	{
		if ($this->loggedOut)
		{
			return null;
		}

		if (!$this->user())
		{
			return null;
		}

		return $this->user()->ID;
	}
1172921
public function login()
    {
        $identity = $this->getIdentity();

        if ($identity->authenticate($this->newPassword)) {
            return $this->webUser->login($identity, 0);
        }

        return false;
    }
1047613
public function getSessionId()
    {
        if ($mauticSessionId = $this->get(self::MAUTIC_SESSION_ID)) {
            return $mauticSessionId;
        }

        if ($mauticSessionId = $this->get(self::MTC_SID)) {
            return $mauticSessionId;
        }

        return null;
    }
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);
            }
        }
    }
491911
protected function sessionUserId() {
		$userId = null;
		$request = $this->newRequest();

		if ($request->session()->started()) {
			$userId = $request->session()->read($this->_config['sessionUserIdKey']);
		} else {
			$this->log('The Session is not started. This typically means a User is not logged in. In this case there is no Session value for the currently active User and therefore we will set the `creator_id` and `modifier_id` to a null value. As a fallback, we are manually starting the session and reading the `$this->_config[sessionUserIdKey]` value, which is probably not correct.', 'debug');
			try {
				$request->session()->start();
				$userId = $request->session()->read($this->_config['sessionUserIdKey']);
			} catch (RuntimeException $e) {
			}
		}

		return $userId;
	}
490599
public function signup()
    {
        if (!$this->validate()) {
            return null;
        }

        $this->user = new UserModel();
        $this->user->setAttributes($this->attributes);
        $this->user->setPassword($this->password);
        $this->user->setLastLogin(time());
        $this->user->generateAuthKey();

        return $this->user->save() ? $this->user : null;
    }
116174
public function getAuthenticatedUser()
    {
        $user = $this->getStorage()
                     ->getAuthenticatedUser($this->request, $this->response);

        if ($user) {
            // check if the user needs 2FA verification
            $twoFactor = $this->getTwoFactorStrategy();
            if ($twoFactor && !$user->isTwoFactorVerified() && $twoFactor->needsVerification($user)) {
                $user->markSignedOut();
            }

            $this->setCurrentUser($user);
        } else {
            // if no current user then sign in a guest
            $user = $this->signInUser($this->getGuestUser());
        }

        return $user;
    }
1254552
public function getUserId() {
		if (isset($_SESSION) && isset($_SESSION[self::SESSION_FIELD_USER_ID])) {
			return $_SESSION[self::SESSION_FIELD_USER_ID];
		}
		else {
			return null;
		}
	}