Login user

 Логин пользователя

 @see https://api.cryptoprocessing.io/#e88a61dc-bb8f-e9cf-0e56-2729f200be9d
972829
def login(options)
      out = nil
      post('/auth/login', options) do |resp|
        @access_token = resp.body['auth_token']
        out = Cryptoprocessing::User.new self, resp.data
        yield(resp) if block_given?
      end
      out
    end
496945
public function getUser()
    {

        // destroy previous content
        $this->destroyUserData();

        if ($this->user === false) {

            // get user

            $url = 'http://ulogin.ru/token.php?token=' . $this->getToken() . '&host=' . (new Request())->getHttpHost();
            $content = file_get_contents($url);
            $this->user = json_decode($content, true);

            // if use has error , destroy user data
            if ($this->destroyUserData() === true) {
                $this->logout();
            }
        }

        return $this->user;
    }
183855
public function validateStatusApi(): bool
    {
        /** @var AbstractUser $user */
        $user = $this->getUser();
        if ($user && $user->status_id === AbstractUser::STATUS_BLOCKED) {
            throw new InvalidArgumentException(\Yii::t('app', 'Ваш аккаунт заблокирован. Обратитесь к тех.поддержке.'));
        }
        if ($user && $user->status_id === AbstractUser::STATUS_WAIT_EMAIL) {
            throw new InvalidArgumentException(\Yii::t('app', 'Ваш аккаунт не подтвержден. Необходимо подтвердить e-mail.'));
        }
        return true;
    }
1172870
function run()
	{
		if(!$this->is_initialized)
			$this->init();

		if(!defined('BORS_SITE'))
			define('BORS_SITE', COMPOSER_ROOT);

		// Пробуем искать по-новому
		// ...
		// https://github.com/phpixie/http
		// http://habrahabr.ru/post/256639/

//		PHPixie пока не трогаем, там какой-то свой PSR-7.
//		$slice = new \PHPixie\Slice();
//		$http = new \PHPixie\HTTP($slice);
//		$request = $http->request();
//		r($request->server()->get('http_host'));
//		r($request->query()->uri());
//		r((string)$request->uri());

		$view = NULL;

		if($this->cfg('view.preset'))
			$view = $this->cfg('view.preset');

		// composer: zendframework/zend-diactoros
		if(!$view && class_exists('\\Zend\\Diactoros\\ServerRequestFactory'))
		{
			$request = \Zend\Diactoros\ServerRequestFactory::fromGlobals();
//			$request = \Slim\Http\Request::createFromEnvironment(new \Slim\Http\Environment($_SERVER));

//			r((string)$request->getUri());
//			r((string)$request->getMethod());

			$view = $this->route_view($request);
		}

		if($view)
		{
			$ret = $view->pre_show();

			if($ret)
				return $ret;

//			r($view);
			$response = $view->response();
			if($response)
			{
				// composer: slim/slim>3
				$app = new \Slim\App;
				$app->respond($response);
				return;
			}
		}

		// Если ничего не нашли, то запускаем старый движок.
		return \bors::run();
	}
931609
private function cookieLogin()
    {
        $read = new Read();
        $prazoTokenExpira = date('Y-m-d H:i:s', strtotime("-2 months", strtotime(date("Y-m-d H:i:s"))));
        $read->exeRead("usuarios", "WHERE token = :to", "to={$_COOKIE['token']}");

        if ($read->getResult() && $read->getResult()[0]['status'] === 1 && $read->getResult()[0]['token_expira'] > $prazoTokenExpira) {
            $login = new Login();
            $login->setLogin(["user" => $read->getResult()[0]['nome'], "password" => $read->getResult()[0]['password']]);
        } else {
            new Logout();
        }
    }
293406
public function login() : string {
		$token = bin2hex(random_bytes(64));
		$loginHash = password_hash($token, PASSWORD_BCRYPT);

		$stmt = $this->db->prepare(
			"INSERT INTO sessions (user_id, login_hash, api_hash) " .
			"VALUES (?, ?, NULL) " .
			"ON DUPLICATE KEY UPDATE login_hash=?;"
		);
		$stmt->bind_param("iss",
			$this->user->id, $loginHash, $loginHash);
		$stmt->execute();
		$this->db->commit();

		return $token;
	}
459567
public function login()
    {
        if ($this->request->is('post')) {
            $user = $this->Auth->identify();
            if ($user !== false) {
                $this->Auth->setUser($user);
                return $this->redirect($this->Auth->redirectUrl());
            }

            $this->Flash->error(__d('community', 'Login or password is incorrect'));
        }

        $this->set('page_title', __d('community', 'Authorize profile'));
    }
197625
public function doLogin()
    {
        $remember = Input::post('remember', false);
        $email    = Input::post('email');
        $redirect = Input::post('redirect');
        $redirect = ($redirect) ? $redirect : 'admin';

        try{
            $credential = array(
                'email'     => $email,
                'password'  => Input::post('password')
            );

            // Try to authenticate the user
            $user = Sentry::authenticate($credential, false);

            if($remember){
                Sentry::loginAndRemember($user);
            }else{
                Sentry::login($user, false);
            }

            Response::redirect($this->siteUrl($redirect));
        }catch(\Exception $e){
            App::flash('message', $e->getMessage());
            App::flash('email', $email);
            App::flash('redirect', $redirect);
            App::flash('remember', $remember);

            Response::redirect($this->siteUrl('login'));
        }
    }
977843
public function login()
    {
        if ($this->validate()) {
            return Podium::getInstance()->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
        }
        return false;
    }
236845
public function logSuccess()
    {
        /** @var XM\SecurityBundle\Entity\User $user */
        $user = $this->tokenStorage->getToken()->getUser();

        if ($user instanceof \XM\SecurityBundle\Entity\User) {
            $user->incrementLoginCount();

            $this->userManager->updateUser($user);

            $this->addLogSuccess($user);
        }
    }
732733
public function authenticate() {
        $currentStage = $this->_multiFactorStages['current'];
        
        //set stage as inactive
        if ($currentStage == 1) {
            $this->_multiFactorStages[1]['statuss'] = parent::authenticate();
            
            //stage one sucessfull, bootstrap stage 2
            if ($this->_multiFactorStages[1]['statuss'] === true ) {
                $this->_multiFactorStages[2] = array (
                    'enc_key' => \openssl_random_pseudo_bytes($this->getEncKeyLength()),
                    'statuss' => false
                );                
            }

            return $this->_multiFactorStages;
        } elseif ($currentStage != 2) {
            throw new UserCredentialException('The current stage of the multi factor auth process is in an unknown state', 2101);
        }
        
        //authenticate stage 2
        $totpTimestamp = $this->userTotpProfile['totp_timestamp'];
        $totpTimelimit = $this->userTotpProfile['totp_timelimit'];
        $currDateTime = new \DateTime();
        $totpTimeElapsed = $currDateTime->getTimestamp() - $totpTimestamp->getTimestamp();
        $encKey = $this->userTotpProfile['enc_key'];
        $verificationHash = $this->getVerificationHash();
        $comparisonHash = \crypt($this->getCurrentPassword(), $encKey);
        $currentOneTimeToken = $this->getCurrentOneTimeToken();
        $oneTimeToken = $this->oneTimeToken;
        
        //initialize verification - comparison
        $verificationEqualsComparison = false;
        
        //verify if verification hash equals comparison hash. Use hash_equals function if exists
        if (!\function_exists('hash_equals')) {
            if ($verificationHash === $comparisonHash) {
                $verificationEqualsComparison = true;
            }
        } else {
            if (\hash_equals($verificationHash, $comparisonHash)) {
                $verificationEqualsComparison = true;
            }
        }

        if (
            !($totpTimeElapsed < $totpTimelimit)
            || !($verificationEqualsComparison === true)
            || !(\password_verify($oneTimeToken,$currentOneTimeToken))
        ) {
            return false;
        } else {
            return true;
        }
    }
273618
static function activate()
    {
        if (get_magic_quotes_gpc()){
            $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
            while (list($key, $val) = each($process)){
                foreach ($val as $k => $v){
                    unset($process[$key][$k]);
                    if (is_array($v)){
                        $process[$key][stripslashes($k)] = $v;
                        $process[] = &$process[$key][stripslashes($k)];
                    }else{
                        $process[$key][stripslashes($k)] = stripslashes($v);
                    }
                }
            }
            unset($process);
        }
        // Нормализация массива $_FILES в соответствии с именованием полей формы
        if (isset($_FILES)){
            // Перегруппировка элементов массива $_FILES
            $rec_to_array = function ($array, $name) use (&$rec_to_array){
                $result = [];
                foreach ($array as $key => $value){
                    if (is_array($value)){
                        $result[$key] = $rec_to_array($value, $name);
                    }else{
                        $result[$key][$name] = $value;
                    }
                }
                return $result;
            };
            $files = [];
            foreach ($_FILES as $field => $data){
                $files[$field] = [];
                foreach ($data as $name => $value){
                    if (is_array($value)){
                        $files[$field] = F::arrayMergeRecursive($files[$field], $rec_to_array($value, $name));
                    }else{
                        $files[$field][$name] = $value;
                    }
                }
            }
        }else{
            $files = [];
        }

        self::$source = array(
            'REQUEST' => [],
            'FILES' => $files,
            'COOKIE' => isset($_COOKIE)? $_COOKIE : [],
            'RAW' => file_get_contents("php://input"), // Неформатированные данные
            'SERVER' => $_SERVER
        );
        if (isset($_SERVER['REQUEST_URI'])){
            $_SERVER['REQUEST_URI'] = preg_replace('#\?{1}#u', '&', $_SERVER['REQUEST_URI'], 1);
//            $request_uri = preg_replace('#^'.preg_quote(DIR_WEB).'#u', '/', $_SERVER['REQUEST_URI'], 1);
            parse_str('path='.$_SERVER['REQUEST_URI'], self::$source['REQUEST']);
            self::$source['SERVER']['argv'] = self::$source['REQUEST'];
            self::$source['SERVER']['argc'] = sizeof(self::$source['REQUEST']);
        }
        // Элементы пути URI
        if (isset(self::$source['REQUEST']['path']) && (self::$source['REQUEST']['path'] = rtrim(self::$source['REQUEST']['path'],'/ '))){
            self::$source['PATH'] = explode('/', trim(self::$source['REQUEST']['path'],' /'));
        }else{
            self::$source['PATH'] = [];
        }
        if (isset($_POST)){
            self::$source['REQUEST'] = array_replace_recursive(self::$source['REQUEST'], $_POST);
        }
        // Аргументы из консоли (режим CLI)
        if (php_sapi_name() == 'cli' && isset($_SERVER['argv'])){
            self::$source['REQUEST']['method'] = 'CLI';
            self::$source['SERVER']['argv'] = $_SERVER['argv'];
            self::$source['SERVER']['argc'] = $_SERVER['argc'];
        }
        self::$source['ARG'] = self::$source['SERVER']['argv'];
        // Метод запроса
        if (isset(self::$source['SERVER']['REQUEST_METHOD']) && !isset(self::$source['REQUEST']['method'])){
            self::$source['REQUEST']['method'] = self::$source['SERVER']['REQUEST_METHOD'];
        }
    }
1284583
public function login()
    {
        // grab credentials from the request
        $credentials = Input::only('email', 'password');

        try {
            // attempt to verify the credentials and create a token for the user
            if (! $token = JWTAuth::attempt($credentials)) {
                return response()->json(arrayView('phpsoft.users::errors/authenticate', [
                    'error' => 'Invalid Credentials.'
                ]), 401);
            }
        } catch (JWTException $e) {
            // something went wrong whilst attempting to encode the token
            return response()->json(arrayView('phpsoft.users::errors/authenticate', [
                'error' => 'Could not create token.'
            ]), 500);
        }

        // all good so return the token
        return response()->json(arrayView('phpsoft.users::tokens/show', compact('token')));
    }
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'));
    }
283529
private function init_request()
	{
		global $request;

		# Значения по умолчанию
		$request = array(
			'method' => $_SERVER['REQUEST_METHOD'],
			'scheme' => isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) ? 'https' : 'http',
			'host' => strtolower($_SERVER['HTTP_HOST']),
			'port' => '',
			'user' => isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : '',
			'pass' => isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : '',
			'path' => '',
			'query' => '',
			'fragment' => '',
			'referer' => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '',
		);

		$request['url'] = $request['scheme'] . '://' . $request['host'] . $_SERVER['REQUEST_URI'];

		$request = array_merge($request, parse_url($request['url']));
		$request['file'] = substr($request['path'], strrpos($request['path'], '/')+1);
		if ($request['file'])
		{
			$request['path'] = substr($request['path'], 0, -strlen($request['file']));
		}

		# Создаем заготовку URL для GET-запросов с параметрами
		$request['link'] = $request['url'];
		if (substr($request['link'], -1) == '/')
		{
			$request['link'] .= '?';
		}
		elseif (strpos($request['link'], '?') === false)
		{
			$request['link'] .= '?';
		}
		else
		{
			$request['link'] .= '&';
		}

		if (is_null($this->path))
		{
			$s = $this->froot;
			$s = substr($s,
				strlen(realpath($_SERVER['DOCUMENT_ROOT'])) - (Eresus_Kernel::isWindows() ? 2 : 0));
			if (!strlen($s) || substr($s, -1) != '/')
			{
				$s .= '/';
			}
			$this->path = (substr($s, 0, 1) != '/' ? '/' : '').$s;
		}

		/*
		 * Установка свойств объекта $Eresus
		 * Должна выполняться ДО вызова __clearargs
		 */
		$root = $request['scheme'] . '://' . $request['host'] .
			($request['port'] ? ':'.$request['port'] : '');
		$this->root = $root.$this->path;
		$this->data = $this->root.'data/';
		$this->style = $this->root.'style/';


		# Сбор аргументов вызова
		$request['arg'] = __clearargs(array_merge($_GET, $_POST));
		# Разбивка параметров вызова скрипта
		$s = substr($request['path'], strlen($this->path));
		$request['params'] = $s ? explode('/', substr($s, 0, -1)) : array();

		$request['path'] = $root.$request['path'];

		# Обратная совместимость
		# <= 2.9
		$this->request = &$request;
        /**
         * @deprecated с 3.01
         */
		define('httpPath', $this->path);
        /**
         * @deprecated с 3.01
         */
		define('httpHost', $this->request['host']);
        /**
         * @deprecated с 3.01
         */
        define('httpRoot', $this->root);
        /**
         * @deprecated с 3.01
         */
		define('styleRoot', $this->style);
        /**
         * @deprecated с 3.01
         */
		define('dataRoot', $this->data);
        /**
         * @deprecated с 3.01
         */
		define('cookieHost', $this->request['host']);
        /**
         * @deprecated с 3.01
         */
		define('cookiePath', $this->path);
	}
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);
    }
1079356
public function getToken(): string
    {
        if (\Yii::$app->session->get('auth_token')) { // берем из куки
            $token = $this->__userAccessTokenClass::findOne(['access_token' => \Yii::$app->session->get('auth_token')]);
            return $token->access_token;
        }
        return '';
    }