Action to setup two factor authentication

@return string
@throws \Exception
424999
public function setupTwoFactorAuth($standalone = false)
    {
        $this->validator->checkCanUseTwoFa();

        if ($standalone) {
            $view = new View('@TwoFactorAuth/setupTwoFactorAuthStandalone');
            $this->setBasicVariablesView($view);
            $view->submitAction = 'onLoginSetupTwoFactorAuth';
        } else {
            $view = new View('@TwoFactorAuth/setupTwoFactorAuth');
            $this->setGeneralVariablesView($view);
            $view->submitAction = 'setupTwoFactorAuth';

            $redirectParams = array('module' => 'TwoFactorAuth', 'action' => 'setupTwoFactorAuth');
            if (!$this->passwordVerify->requirePasswordVerified($redirectParams)) {
                // should usually not go in here but redirect instead
                throw new Exception('You have to verify your password first.');
            }
        }

        $session = $this->make2faSession();

        if (empty($session->secret)) {
            $session->secret = $this->twoFa->generateSecret();
        }

        $secret = $session->secret;
        $session->setExpirationSeconds(60 * 15, 'secret');

        $authCode = Common::getRequestVar('authCode', '', 'string');
        $authCodeNonce = Common::getRequestVar('authCodeNonce', '', 'string');
        $hasSubmittedForm = !empty($authCodeNonce) || !empty($authCode);
        $accessErrorString = '';
        $login = Piwik::getCurrentUserLogin();

        if (!empty($secret) && !empty($authCode)
            && Nonce::verifyNonce(self::AUTH_CODE_NONCE, $authCodeNonce)) {
            if ($this->twoFa->validateAuthCodeDuringSetup(trim($authCode), $secret)) {
                $this->twoFa->saveSecret($login, $secret);
                $fingerprint = new SessionFingerprint();
                $fingerprint->setTwoFactorAuthenticationVerified();
                unset($session->secret);
                $this->passwordVerify->forgetVerifiedPassword();

                Piwik::postEvent('TwoFactorAuth.enabled', array($login));

                if ($standalone) {
                    $this->redirectToIndex('CoreHome', 'index');
                    return;
                }

                $view = new View('@TwoFactorAuth/setupFinished');
                $this->setGeneralVariablesView($view);
                return $view->render();
            } else {
                $accessErrorString = Piwik::translate('TwoFactorAuth_WrongAuthCodeTryAgain');
            }
        } elseif (!$standalone) {
            // the user has not posted the form... at least not with a valid nonce... we make sure the password verify
            // is valid for at least another 15 minutes and if not, ask for another password confirmation to avoid
            // the user may be posting a valid auth code after rendering this screen but the password verify is invalid
            // by then.
            $redirectParams = array('module' => 'TwoFactorAuth', 'action' => 'setupTwoFactorAuth');
            if (!$this->passwordVerify->requirePasswordVerifiedRecently($redirectParams)) {
                throw new Exception('You have to verify your password first.');
            }
        }

        if (!$this->recoveryCodeDao->getAllRecoveryCodesForLogin($login)
            || (!$hasSubmittedForm && !$this->twoFa->isUserUsingTwoFactorAuthentication($login))) {
            // we cannot generate new codes after form has been submitted and user is not yet using 2fa cause we would
            // change recovery codes in the background without the user noticing... we cannot simply do this:
            // if !getAllRecoveryCodesForLogin => createRecoveryCodesForLogin. Because it could be a security issue that
            // user might start the setup but never finishes. Before setting up 2fa the first time we have to change
            // the recovery codes
            $this->recoveryCodeDao->createRecoveryCodesForLogin($login);
        }

        $view->title = $this->settings->twoFactorAuthTitle->getValue();
        $view->description = $login;
        $view->authCodeNonce = Nonce::getNonce(self::AUTH_CODE_NONCE);
        $view->AccessErrorString = $accessErrorString;
        $view->isAlreadyUsing2fa = $this->twoFa->isUserUsingTwoFactorAuthentication($login);
        $view->newSecret = $secret;
        $view->twoFaBarCodeSetupUrl = $this->getTwoFaBarCodeSetupUrl($secret);
        $view->codes = $this->recoveryCodeDao->getAllRecoveryCodesForLogin($login);
        $view->standalone = $standalone;

        return $view->render();
    }
465276
private static function auth()
    {
        $files = ['Auth'];
        $folder = static::$root.'Authentication'.'/';

        self::call($files, $folder);

        $files = ['AuthenticationModelNotFoundException'];
        $folder = static::$root.'Authentication/Exceptions'.'/';

        self::call($files, $folder);
    }
697869
public function post2faRegister(Request $request) {

        // Did the user take too much time to fill out the form?
        if ($this->twoFactorAuthHelper->isTwoFactorAuthFormTimeout(null, $request->input('formStartDateTime'))) {

            $this->twoFactorAuthHelper->clearTwoFactorAuthCodeToInput();

            return view('usermanagement::frontend.'.$this->frontend_template_name.'.register.register', [
                'title'                    => 'Register',
                'two_factor_auth_workflow' => true,
            ])
            ->withInput($request->only('name', 'email', 'phone_country_code', 'phone_number'))
            ->withErrors([
                'Two Factor Authorization' => 'Your two factor authorization code expired. Please re-start your registration.'
            ]);
        }

        if (!$this->twoFactorAuthHelper->isInputtedTwoFactorAuthCodeCorrect()) {

            $this->twoFactorAuthHelper->clearTwoFactorAuthCodeToInput();

            return view('usermanagement::frontend.' . $this->frontend_template_name . '.register.two_factor_auth', [
                'title'                    => 'Register',
                'two_factor_auth_workflow' => true,
                'name'                     => $request->input('name'),
                'email'                    => $request->input('email'),
                'password'                 => $request->input('password'),
                'password_confirmation'    => $request->input('password_confirmation'),
                'phone_country_code'       => $request->input('phone_country_code'),
                'phone_number'             => $request->input('phone_number'),
                'formStartDateTime'        => $request->input('formStartDateTime'),
            ])
            ->withErrors([
                'Two Factor Authorization' => 'Your entered an incorrect two factor authorization code. Please try again.'
            ]);
        }

        $response = $this->dispatchFrom(CreateRegisterUserCommand::class, $request);

        Session::flash('status_code', $response['status_code'] );

        if ($response['status_text'] == "validation_failed") {
            Session::flash('message', $response['errorMessages']->first());
            // Return to the edit form with error messages
            return Redirect::back()
                ->withInput($response['data'])
                ->withErrors($response['errorMessages']);
        }

        if ($response['status_text'] == "persist_failed") {
            $message = "Processing error. Please try again.";
            Session::flash('message', $message);
            // Return to the edit form with error messages
            return Redirect::back()
                ->withInput($response['data'])
                ->withErrors($message);
        }

        // User registration was successful


        // Login registrant
        if (config('lasallecmsusermanagement.auth_frontend_registration_successful_auto_login')) {
            $userId = $this->userRepository->findUserIdByEmail($response['data']['email']);
            Auth::loginUsingId($userId);
        }


        // Fire the custom event
        event(new FrontendRegistrationWasSuccessful($response));


        if (config('auth.auth_display_register_confirmation_view_after_successful_frontend_registration')) {
            return view('usermanagement::frontend.'.$this->frontend_template_name.'.register_confirmed.register_confirmed', [
                'title'          => 'Register Confirmation',
                'username'       => strtoupper($response['data']['name']),
                'isUserLoggedIn' => Auth::check(),
            ]);
        }

        // $name = strtoupper($response['data']['name']);
        $message = 'You successfully registered!';
        Session::flash('message', $message);

        return Redirect::route('home');
    }
574336
public function authenticate() {

		if (!empty($_REQUEST['openid_mode'])) {
			switch ($_REQUEST['openid_mode']) {
				case 'id_res':
					try {
						$this->auth->returnUrl = $this->getState('returnUrl');
						if ($this->auth->validate()) {
							$this->attributes['id'] = $this->auth->identity;

							$attributes = $this->auth->getAttributes();
							foreach ($this->requiredAttributes as $key => $attr) {
								if (isset($attributes[$attr[1]])) {
									$this->attributes[$key] = $attributes[$attr[1]];
								}
								else {
									throw new EAuthException(Yii::t('eauth', 'Unable to complete the authentication because the required data was not received.', array('{provider}' => $this->getServiceTitle())));
									return false;
								}
							}

							foreach ($this->optionalAttributes as $key => $attr) {
								if (isset($attributes[$attr[1]])) {
									$this->attributes[$key] = $attributes[$attr[1]];
								}
							}

							$this->authenticated = true;
							return true;
						}
						else {
							throw new EAuthException(Yii::t('eauth', 'Unable to complete the authentication because the required data was not received.', array('{provider}' => $this->getServiceTitle())));
							return false;
						}
					} catch (Exception $e) {
						throw new EAuthException($e->getMessage(), $e->getCode());
					}
					break;

				case 'cancel':
					$this->cancel();
					break;

				default:
					throw new CHttpException(400, Yii::t('yii', 'Your request is invalid.'));
					break;
			}
		}
		else {
			$this->auth->identity = $this->url; //Setting identifier
			$this->auth->required = array(); //Try to get info from openid provider
			foreach ($this->requiredAttributes as $attribute) {
				$this->auth->required[$attribute[0]] = $attribute[1];
			}
			foreach ($this->optionalAttributes as $attribute) {
				$this->auth->required[$attribute[0]] = $attribute[1];
			}

			if (isset($this->realm)) {
				if (!preg_match('#^[a-z]+\://#', $this->realm)) {
					$this->auth->realm = 'http' . (Yii::app()->request->getIsSecureConnection() ? 's' : '') . '://' . $this->realm;
				}
				else {
					$this->auth->realm = $this->realm;
				}
			}
			else {
				$this->auth->realm = Yii::app()->request->hostInfo;
			}

			$this->auth->returnUrl = Yii::app()->request->hostInfo . Yii::app()->request->url; //getting return URL
			$this->setState('returnUrl', $this->auth->returnUrl);

			try {
				$url = $this->auth->authUrl();
				Yii::app()->request->redirect($url);
			} catch (Exception $e) {
				throw new EAuthException($e->getMessage(), $e->getCode());
			}
		}

		return false;
	}
869586
public function connect()
    {
        if ( ! ($this->connection = ssh2_connect($this->host, $this->port))) {
            throw new \Exception('Cannot connect to server');
        }
        
        if ( ! ssh2_auth_pubkey_file($this->connection, $this->authUser, $this->authPub, $this->authPriv,
            $this->authPass)
        ) {
            throw new \Exception('Autentication rejected by server');
        }
    }
1238412
public function authenticate()
    {
        $code = $this->getMvcEvent()->getRequest()->getQuery('code');
        if(!$code) {
            return new Result(
                $this->authenticationService,
                Result::FAILURE_CREDENTIAL_INVALID,
                array(),
                array("No 'code' available")
            );
        }
        
        try {
            $provider = $this->getProvider();
            $token = $provider->getAccessToken('authorization_code', ['code' => $code]);
            
            $userProfile = $provider->getUserDetails($token);
            
            $res = new OAuth2Result(
                $this->authenticationService,
                Result::SUCCESS,
                $userProfile->uid
            );
            $res->setUserProfile($this->createUserProfile($userProfile));
            
            $res->setAccessToken($token->accessToken);
            $res->setRefreshToken($token->refreshToken);
            $res->setExpiresIn($token->expires);
            
            return $res;
            
        } catch(\Exception $e) {
            return new Result(
                $this->authenticationService,
                Result::FAILURE_CREDENTIAL_INVALID,
                $code,
                array($e->getMessage())
            );
        }
    }
286418
protected function auth()
    {
        return Cache::remember('b2', 1320, function () {
            return $this->client->request('GET', 'https://api.backblaze.com/b2api/v1/b2_authorize_account', [
                'auth' => [$this->accountId, $this->applicationKey]
            ]);
        });
    }
412630
public function authenticate()
    {
        if (!is_null($this->token)) {
            return;
        }

        $response = $this->authenticationResponse();

        if (!$response->hasHeader('X-Auth-Token')) {
            throw new AuthenticationFailedException('Given credentials are wrong.', 403);
        }

        if (!$response->hasHeader('X-Storage-Url')) {
            throw new RuntimeException('Storage URL is missing.', 500);
        }

        $this->token = $response->getHeaderLine('X-Auth-Token');
        $this->storageUrl = $response->getHeaderLine('X-Storage-Url');
    }
1039364
public function loginAction()
    {
        $ref = urldecode($this->getRequest()->getBasePath().$this->params()->fromQuery('ref'));
        $provider = $this->params('provider', '--keiner--');
        $hauth = $this->hybridAuthAdapter;
        $hauth->setProvider($provider);
        $auth = $this->auth;
        
        $result = $auth->authenticate($hauth);
        $resultMessage = $result->getMessages();

        if (array_key_exists('firstLogin', $resultMessage) && $resultMessage['firstLogin'] === true) {
            try {
                $user          = $auth->getUser();
                $password      = substr(md5(uniqid()), 0, 6);
                $login         = uniqid() . ($this->options->auth_suffix != "" ? '@' . $this->options->auth_suffix : '');
                $externalLogin = $user->getLogin() ?: '-- not communicated --';
                $this->logger->debug('first login via ' . $provider . ' as: ' . $externalLogin);

                $user->setLogin($login);
                $user->setPassword($password);
                $user->setRole($this->options->getRole());

                $mail = $this->mailer('htmltemplate');
                $mail->setTemplate('mail/first-socialmedia-login');
                $mail->setSubject($this->options->getMailSubjectRegistration());
                $mail->setVariables(
                    array(
                                'displayName'=> $user->getInfo()->getDisplayName(),
                                'provider' => $provider,
                                'login' => $login,
                                'password' => $password,
                    )
                );
                $mail->addTo($user->getInfo()->getEmail());

                $loggerId = $login . ' (' . $provider . ': ' . $externalLogin . ')';
                if (isset($mail) && $this->mailer($mail)) {
                    $this->logger->info('Mail first-login for ' . $loggerId . ' sent to ' . $user->getInfo()->getEmail());
                } else {
                    $this->logger->warn('No Mail was sent for ' . $loggerId);
                }
            } catch (\Exception $e) {
                $this->logger->crit($e);
                $this->notification()->danger(
                    /*@translate*/ 'An unexpected error has occurred, please contact your system administrator'
                );
            }
        }
        
        $user = $auth->getUser();
        $this->logger->info('User ' . $auth->getUser()->getInfo()->getDisplayName() . ' logged in via ' . $provider);
        $settings = $user->getSettings('Core');
        if (null !== $settings->localization->language) {
            $basePath = $this->getRequest()->getBasePath();
            $ref = preg_replace('~^'.$basePath . '/[a-z]{2}(?=/|$)~', $basePath . '/' . $settings->localization->language, $ref);
        }
        return $this->redirect()->toUrl($ref);
    }
133038
function _setup()
    {
        return (Auth_OpenID::ensureDir($this->nonce_dir) &&
                Auth_OpenID::ensureDir($this->association_dir) &&
                Auth_OpenID::ensureDir($this->temp_dir));
    }
472272
public function setupAuthentication() {
		if (!in_array('Auth', $this->components()->loaded())) {
			$this->components()->load('Auth');
		}

		$this->components()->Auth->setConfig('authenticate', [
			'Form' => [
				'userModel' => 'Users',
				'fields' => [
					'username' => 'email',
					'password' => 'password'
				],
				'scope' => [
					'Users.email_verified' => 1
				]
			]
		]);
	}
1091196
public function getJWT()
	{
		if($this->personalKeyPair === NULL)
			throw new \Exception("JWT cannot be built without the personalKey");
		
		// create and sign JWT
		$signer = new Sha512();
		
		$personalPrivateKey = PrivateKey::formatPEM($this->personalKeyPair->getPrivateKey());
		
		$token = (new Builder())
			->set('socialRecord', base64_encode($this->socialRecord->getJSONString()))
			->sign($signer, $personalPrivateKey)
			->getToken();
		
		return $token->__toString();
	}
894251
public function reset2faAction()
    {
        $user = $this->getSelectedUser();
        $user->clearTwoFactorKey();
        $this->addMessage(
                sprintf($this->_('Two factor key cleared for user %s'),
                        $user->getLoginName()),
                'success');
        $router = \Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
        $router->gotoRoute(['controller'=>'staff', 'action'=>'show'], null, false);
    }
814157
public function login() {
        $username = $this->getAuthenticator()->getPasswordAuthentication()->getUsername();
        $password = $this->getAuthenticator()->getPasswordAuthentication()->getPassword();
        if (false === ssh2_auth_password($this->getConnection(), $username, $password)) {
            throw $this->newFTPException("login failed");
        }
        return $this;
    }
1054502
public function postTwoFactor()
    {
        // Check that we have a session.
        if ($userId = Session::pull('2fa_id')) {
            $code = str_replace(' ', '', Binput::get('code'));

            // Maybe a temp login here.
            Auth::loginUsingId($userId);

            $user = Auth::user();

            $valid = Google2FA::verifyKey($user->google_2fa_secret, $code);

            if ($valid) {
                event(new UserPassedTwoAuthEvent($user));

                event(new UserLoggedInEvent($user));

                return Redirect::intended('dashboard');
            } else {
                event(new UserFailedTwoAuthEvent($user));

                // Failed login, log back out.
                Auth::logout();

                return cachet_redirect('auth.login')->withError(trans('forms.login.invalid-token'));
            }
        }

        return cachet_redirect('auth.login')->withError(trans('forms.login.invalid-token'));
    }
1217256
public function authenticate()
	{
		// Backwards compatibility for Contao 4.4
		if (!$this instanceof UserInterface) {
			if ($this->frontendHelperUserAuthenticated === null) {
				$this->frontendHelperUserAuthenticated = \User::authenticate();
			}
			return $this->frontendHelperUserAuthenticated;
		}

		return $this->username && $this->intId;
	}
531269
public function getAuthenticatedUser ()
    {
        $curUserEntity = $this->ServiceContainer->get('security.context')->getToken()->getUser();
        if (!is_object($curUserEntity)) {
            throw new Exception("No authenticated user found");
        }

        $CurUser = $this->getModelRepository('User')->getById($curUserEntity->getId());
        return $CurUser;
    }