Creates an auto-login key for the current user, this key is restricted by time and ip address.

@return string the key
@since Moodle 3.2
3395
public static function get_autologin_key() {
        global $USER;
        // Delete previous keys.
        delete_user_key('tool_mobile', $USER->id);

        // Create a new key.
        $iprestriction = getremoteaddr();
        $validuntil = time() + self::LOGIN_KEY_TTL;
        return create_user_key('tool_mobile', $USER->id, null, $iprestriction, $validuntil);
    }
561422
private function getKeyPair()
    {
        $config = $this->app->make('config/database');

        // Seee if we already have a kypair
        $keyPair = $config->get('api.keypair');

        if (!$keyPair) {
            $rsa = $this->app->make(RSA::class);

            // Generate a new RSA key
            $keyPair = $rsa->createKey(2048);

            foreach ($keyPair as &$item) {
                $item = str_replace("\r\n", "\n", $item);
            }

            // Save the keypair
            $config->save('api.keypair', $keyPair);
        }

        return $keyPair;
    }
1012456
public function loginAction()
    {
        if ($this->getUser()) {
            return $this->redirectToRoute($this->get(Configuration::class)->getHomeRoute());
        }
        $authenticationUtils = $this->get('security.authentication_utils');

        // get the login error if there is one
        $error = $authenticationUtils->getLastAuthenticationError();

        // last username entered by the user
        $lastUsername = $authenticationUtils->getLastUsername();

        return [
            'last_username' => $lastUsername,
            'error' => $error,
        ];
    }
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;
	}
730481
public function login()
    {
        //Get the hidden value from login page.
        $response = $this->client->get($this->login_uri);
        $viewstate = $this->parserHiddenValue($response->getBody());


        //The default login post param
        $loginParam = [
            'viewstate' => '__VIEWSTATE',
            'stu_id' => 'TextBox1',
            'passwod' => 'TextBox2',
            'role' => 'RadioButtonList1',
            'button' => 'Button1'
        ];

        if (!empty($this->loginParam)) {
            $loginParam = $this->loginParam;
        }

        $form_params = [
            $loginParam['viewstate'] => $viewstate,
            $loginParam['stu_id'] => $this->stu_id,
            $loginParam['passwod'] => $this->password,
            $loginParam['role'] => iconv('utf-8', 'gb2312', '学生'),
            $loginParam['button'] => iconv('utf-8', 'gb2312', '登录'),
        ];

        $query = [
            'form_params' => $form_params
        ];

        //If set to cache cookie
        if ($this->cacheCookie) {
            $jar = new \GuzzleHttp\Cookie\CookieJar;
            $query['cookies'] = $jar;
        }
        //Post to login
        $result = $this->client->request('POST', $this->login_uri, $query);

        //Is logining successful?
        $response = $this->client->get($this->main_page_uri, ['allow_redirects' => false, 'query' => ['xh' => $this->stu_id]]);

        switch ($response->getStatusCode()) {
            case 200:
                return $this->cacheCookie ? $jar : $this;
                break;
            case 302:
                Log::info('The password is wrong!', $query);
                throw new \Exception('The password is wrong!', 1);
                break;
            default:
                Log::error('Maybe the data source is broken!', $response);
                throw new \Exception('Maybe the data source is broken!', 1);
                break;
        }
    }
1353101
public function getPrivateKey()
    {
        if ("---" !== substr($this->privateKey, 0, 3) && is_file($this->privateKey)) {
            $this->privateKey = file_get_contents($this->privateKey);
        }

        $key = new RSA();

        if ($password = $this->getPassword()) {
            $key->setPassword($password);
        }

        $key->loadKey($this->privateKey);

        return $key;
    }
830579
public function trySubdomainUnauthenticatedGet()
    {
        $this->reset();
        $url = 'http://autodiscover.' . $this->tld . self::AUTODISCOVER_PATH;
        $ch = curl_init();
        $opts = array(
            CURLOPT_URL                 => $url,
            CURLOPT_HTTPGET             => true,
            CURLOPT_RETURNTRANSFER      => true,
            CURLOPT_TIMEOUT             => 4,
            CURLOPT_CONNECTTIMEOUT      => $this->connection_timeout,
            CURLOPT_FOLLOWLOCATION      => false,
            CURLOPT_HEADER              => false,
            CURLOPT_HEADERFUNCTION      => array($this, 'readHeaders'),
            CURLOPT_HTTP200ALIASES      => array(301, 302),
            CURLOPT_IPRESOLVE           => CURL_IPRESOLVE_V4
        );
        curl_setopt_array($ch, $opts);
        $this->last_response    = curl_exec($ch);
        $this->last_info        = curl_getinfo($ch);
        $this->last_curl_errno  = curl_errno($ch);
        $this->last_curl_error  = curl_error($ch);

        if ($this->last_info['http_code'] == 302
            || $this->last_info['http_code'] == 301) {
            if ($this->tryViaUrl($this->last_response_headers['location'])) {
                return self::AUTODISCOVERED_VIA_UNAUTHENTICATED_GET;
            }
        }

        return false;
    }
627472
public static function CurrentUser()
    {
        if (static::IsAuthenticatedRequest()) {
            $cryptor = new GnCryptor();
            $cookie = $cryptor->decrypt($_COOKIE['GpsNoseAuthentication']);
            $json = json_decode($cookie);
            $gnPrincipal = new GnPrincipal();
            $gnPrincipal->LoginName = $json->{"LoginName"};
            $gnPrincipal->LoginId = $json->{"LoginId"};
            $gnPrincipal->ProfileTags = $json->{"ProfileTags"};
            return $gnPrincipal;
        }
        return NULL;
    }
982901
public function doAutoLogin()
    {
        // User already logged in?
        if ($this->session['logged_in']) {
            return true;
        }

        // No autologin when autologin already failed
        if (isset($this->session['autologin_failed'])) {

            // Remove fragments/all of autologin cookies
            setcookie($this->cookie_name, '', 1);

            // Remove the flag which forces the log off
            unset($this->session['autologin_failed']);

            return false;
        }

        // No autologin cookie no autologin ;)
        if (!isset($_COOKIE[$this->cookie_name])) {
            return false;
        }

        // Let's find the user for the token in cookie
        list ($selector, $token) = explode(':', $_COOKIE[$this->cookie_name]);

        $this->db->qb([
            'table' => 'core_auth_tokens',
            'fields' => [
                'id_auth_token',
                'id',
                'token',
                'selector',
                'expires'
            ],
            'filter' => 'selector=:selector',
            'params' => [
                ':selector' => $selector
            ]
        ]);
        $data = $this->db->all();

        foreach ($data as $auth_token) {

            // Check if token is expired?
            if (strtotime($auth_token['expires']) < time()) {
                $this->removeAutoLoginTokenAndCookie($auth_token['id']);
                continue;
            }

            // Matches the hash in db with the provided token?
            if (hash_equals($auth_token['token'], $token)) {

                // Refresh session id and delete old session
                session_regenerate_id(true);

                // Refresh autologin cookie so the user stays logged in
                // as long as he comes back before his cookie has been expired.
                $this->createAutoLoginTokenAndCookie($auth_token['id']);

                // Login user, set session flags and return true
                $this->session['logged_in'] = true;
                $this->session['user'] = $auth_token['id'];

                // Remove possible autologin failed flag
                unset($this->session['autologin_failed']);

                return $this->session['user'];
            }
        }

        // !!! Reaching this point means autologin validation failed in all ways
        // Clean up the mess and return a big bad fucking false as failed autologin result.

        // Remove token cookie
        if (isset($_COOKIE[$this->cookie_name])) {
            unset($_COOKIE[$this->cookie_name]);
        }

        // Set flag that autologin failed
        $this->session['autologin_failed'] = true;

        // Set logged in flag explicit to false
        $this->session['logged_in'] = false;

        // Set id of user explicit to 0 (guest)
        $this->session['user'] = 0;

        // sorry, no autologin
        return false;
    }
1317531
public function generateNewApiKey() : ? string {

		if ($this->confirmed) {
			$apiKey = bin2hex(random_bytes(64));
			$this->sessionManager->storeApiKey($apiKey);
			return $apiKey;
		} else {
			return null;
		}

	}
764119
protected function getSessionKey()
	{
		return self::SESSION_VAR_PREFIX . Yii::app()->getId() . '.' . $this->getController()->getUniqueId() . '.' . $this->getId();
	}
735974
public function _autoConnect() {
		$cookie = $this->getCookieUser ();
		if (isset ( $cookie )) {
			$user = $this->fromCookie ( $cookie );
			if (isset ( $user )) {
				USession::set ( $this->_getUserSessionKey (), $user );
			}
		}
	}
617460
public function actionLastLogins()
    {
        return UserLogin::find()->select(['user_id', 'max(timestamp_create) as maxdate'])->joinWith(['user' => function ($q) {
            $q->select(['id', 'firstname', 'lastname']);
        }])->limit(10)->groupBy(['user_id'])->orderBy(['maxdate' => SORT_DESC])->asArray()->all();
    }
1215264
public function createUserAction()
    {
        if(!$this->identity()) {
          return $this->redirect()->toRoute($this->getOptions()->getLoginRedirectRoute());
        }
      
        try {
            $user = new User;
            
            $form = $this->getUserFormHelper()->createUserForm($user, 'CreateUser');
            $request = $this->getRequest();
            if ($request->isPost()) {
                $form->setValidationGroup('username', 'email', 'firstName', 'lastName', 'password', 'passwordVerify', 'language', 'state', 'role', 'question', 'answer', 'csrf');
                $form->setData($request->getPost());
                if ($form->isValid()) {
                    $entityManager = $this->getEntityManager();
                    $user->setEmailConfirmed(false);
                    $user->setRegistrationDate(new \DateTime());
                    $user->setRegistrationToken(md5(uniqid(mt_rand(), true)));
                    $user->setPassword(UserCredentialsService::encryptPassword($user->getPassword()));
                    $entityManager->persist($user);
                    $entityManager->flush();
                    $this->flashMessenger()->addSuccessMessage($this->getTranslatorHelper()->translate('User created Successfully'));
                    return $this->redirect()->toRoute('user-admin');                                        
                }
            }        
        }
        catch (\Exception $e) {
            return $this->getServiceLocator()->get('csnuser_error_view')->createErrorView(
                $this->getTranslatorHelper()->translate('Something went wrong during user creation! Please, try again later.'),
                $e,
                $this->getOptions()->getDisplayExceptions(),
                false
            );
        }
        
        $viewModel = new ViewModel(array('form' => $form));
        $viewModel->setTemplate('csn-user/admin/new-user-form');
        return $viewModel;
    }
1252195
public function getPrivateMasterKey()
    {
        if (!$this->privateMasterKey) {
            $masterKey = $this->getMasterKey();
            openssl_pkey_export($masterKey, $this->privateMasterKey);
        }
        return $this->privateMasterKey;
    }
601799
protected function getSessionKeyByOwner()
    {
        if ($this->sessionKey) {
            return $this->sessionKey;
        }

        if ($this->owner instanceof Controller) {
            return $this->owner->module->id;
        }

        return 'generic';
    }
958764
public function getAuthKey()
    {
        $authKeyAttribute = $this->authKeyAttribute;
        return (is_string($authKeyAttribute) && !empty($authKeyAttribute)) ? $this->$authKeyAttribute : null;
    }