Generate an MFA token

@param  int $iUserId The user ID to generate the token for

@return array|false
970920
public function mfaTokenGenerate($iUserId)
    {
        $oPasswordModel = Factory::model('UserPassword', 'nails/module-auth');
        $oNow           = Factory::factory('DateTime');
        $oInput         = Factory::service('Input');
        $oDb            = Factory::service('Database');

        $sSalt    = $oPasswordModel->salt();
        $sIp      = $oInput->ipAddress();
        $sCreated = $oNow->format('Y-m-d H:i:s');
        $sExpires = $oNow->add(new \DateInterval('PT10M'))->format('Y-m-d H:i:s');
        $aToken   = [
            'token' => sha1(sha1(APP_PRIVATE_KEY . $iUserId . $sCreated . $sExpires . $sIp) . $sSalt),
            'salt'  => md5($sSalt),
        ];

        //  Add this to the DB
        $oDb->set('user_id', $iUserId);
        $oDb->set('token', $aToken['token']);
        $oDb->set('salt', $aToken['salt']);
        $oDb->set('created', $sCreated);
        $oDb->set('expires', $sExpires);
        $oDb->set('ip', $sIp);

        if ($oDb->insert(NAILS_DB_PREFIX . 'user_auth_two_factor_token')) {
            $aToken['id'] = $oDb->insert_id();
            return $aToken;
        } else {
            $error = lang('auth_twofactor_token_could_not_generate');
            $this->setError($error);
            return false;
        }
    }
182611
public static function generate($userId, $lifetime = 3600)
    {
        $token = new static;

        $token->token = str_random(40);
        $token->user_id = $userId;
        $token->created_at = Carbon::now();
        $token->last_activity_at = Carbon::now();
        $token->lifetime_seconds = $lifetime;

        return $token;
    }
336691
public static function export_user_preferences(int $userid) {
        $accesstoken = get_user_preferences('repository_flickr_access_token', null, $userid);
        if ($accesstoken !== null) {
            writer::export_user_preference(
                'repository_flickr',
                'repository_flickr_access_token',
                $accesstoken,
                get_string('privacy:metadata:repository_flickr:preference:repository_flickr_access_token', 'repository_flickr')
            );
        }
        $accesstokensecret = get_user_preferences('repository_flickr_access_token_secret', null, $userid);
        if ($accesstokensecret !== null) {
            writer::export_user_preference(
                'repository_flickr',
                'repository_flickr_access_token_secret',
                '',
                get_string('privacy:metadata:repository_flickr:preference:repository_flickr_access_token_secret', 'repository_flickr')
            );
        }
    }
437311
public static function appSign_once($fileid, $userid = '0') {

        $secretId = Conf::SECRET_ID;
        $secretKey = Conf::SECRET_KEY;
		$appid = Conf::APPID;
		
        if (empty($secretId) || empty($secretKey) || empty($appid)) {
            return self::AUTH_SECRET_ID_KEY_ERROR;
        }
        
        $puserid = '';
        if (!empty($userid)) {
            if (strlen($userid) > 64) {
                return self::AUTH_URL_FORMAT_ERROR;
            }
            $puserid = $userid;
        }
                    
        $now = time();    
        $rdm = rand();

        $plainText = 'a='.$appid.'&k='.$secretId.'&e=0'.'&t='.$now.'&r='.$rdm.'&u='.$puserid.'&f='.$fileid;
        $bin = hash_hmac("SHA1", $plainText, $secretKey, true);
        $bin = $bin.$plainText;        
        $sign = base64_encode($bin);        
        return $sign;
    }
526834
public function expiresAfter($iGroupId)
    {
        if (empty($iGroupId)) {
            return null;
        }

        $oDb = Factory::service('Database');
        $oDb->select('password_rules');
        $oDb->where('id', $iGroupId);
        $oDb->limit(1);
        $oResult = $oDb->get(NAILS_DB_PREFIX . 'user_group');

        if ($oResult->num_rows() !== 1) {
            return null;
        }

        //  Decode the password rules
        $oGroupPwRules = json_decode($oResult->row()->password_rules);

        return empty($oGroupPwRules->expiresAfter) ? null : $oGroupPwRules->expiresAfter;
    }
461890
private function getUserNameById(int $userId): ?string
    {
        try {
            $user = $this->userService->loadUser($userId);

            return $user->getName();
        } catch (\Exception $e) {
            return $this->translator->trans(
                /** @Desc("another user") */
                'content_type.user_name.can_not_be_fetched',
                [],
                'content_type'
            );
        }
    }
1257044
public function userIsSuspended($iUserId)
    {
        $oDb = Factory::service('Database');
        $oDb->where('id', $iUserId);
        $oDb->where('is_suspended', true);
        return (bool) $oDb->count_all_results(NAILS_DB_PREFIX . 'user');
    }
785167
public function createLinkToken($userId)
    {
        $url = sprintf('%s/v2/bot/user/%s/linkToken', $this->endpointBase, urlencode($userId));
        return $this->httpClient->post($url, []);
    }
324407
public function getUser($userId)
    {
        $response = $this->client->get(sprintf('/v2/user/%s', $userId));

        return new User($response);
    }
909398
public function generateToken($userId, $timeOut = 7200, $prefix = '')
    {
        $token = md5($prefix . $this->randCode(32) . $this->saltToken . time());
        $freshTOken = md5($prefix . $this->randCode(32) . $this->saltToken . time());
        $permissionModel = new Permission($this->db);
        $permission = $permissionModel->getPermissionByUserId($userId);
        //无权限时为登录验证用
        if (!empty($permission)) {
            $newPermission = [];
            if (!empty($permission)) {
                foreach ($permission as $k=>$v)
                {
                    $newPermission[$v['path']] = $v;
                }
            }
            Cache::set($token, $newPermission, $timeOut);
        } else {
            //权限为空时token仅仅用作登录身份验证
            Cache::set($token, '', $timeOut);
        }
        Cache::set($freshTOken, $token, $timeOut);
        return [
            'token' => $token,
            'refresh_token' => $freshTOken,
            'expire' => $timeOut
        ];
    }
282227
public static function gentoken($uid = '')
    {
        $str = microtime() . (isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'unknow') . 
            $uid . '7200';

        $md5 = md5($str);

        $crypt = crypt($md5, 'CRYPT_SHA256');

        $md5 = md5($crypt);

        return substr(strrev($md5), 1);
    }
1263551
public function mfaTokenValidate($iUserId, $sSalt, $sToken, $sIp)
    {
        $oDb = Factory::service('Database');
        $oDb->where('user_id', $iUserId);
        $oDb->where('salt', $sSalt);
        $oDb->where('token', $sToken);

        $oToken  = $oDb->get(NAILS_DB_PREFIX . 'user_auth_two_factor_token')->row();
        $bReturn = true;

        if (!$oToken) {

            $this->setError(lang('auth_twofactor_token_invalid'));
            return false;

        } elseif (strtotime($oToken->expires) <= time()) {

            $this->setError(lang('auth_twofactor_token_expired'));
            $bReturn = false;

        } elseif ($oToken->ip != $sIp) {

            $this->setError(lang('auth_twofactor_token_bad_ip'));
            $bReturn = false;
        }

        //  Delete the token
        $this->mfaTokenDelete($oToken->id);

        return $bReturn;
    }
115170
public static function get_contexts_for_userid(int $userid) : \core_privacy\local\request\contextlist {
        $contextlist = new \core_privacy\local\request\contextlist();
        static::call_subplugins_method_with_args('add_contexts_for_userid', [$contextlist, $userid]);
        return $contextlist;
    }
813767
protected function createToken($userId, $csrfToken, Carbon $expiration)
    {
        return JWT::encode([
            'sub' => $userId,
            'csrf' => $csrfToken,
            'expiry' => $expiration->getTimestamp(),
        ], $this->encrypter->getKey());
    }
1261476
public function isExpired($iUserId)
    {
        if (empty($iUserId)) {
            return false;
        }

        $oDb = Factory::service('Database');
        $oDb->select('u.password_changed,ug.password_rules');
        $oDb->where('u.id', $iUserId);
        $oDb->join(NAILS_DB_PREFIX . 'user_group ug', 'ug.id = u.group_id');
        $oDb->limit(1);
        $oResult = $oDb->get(NAILS_DB_PREFIX . 'user u');

        if ($oResult->num_rows() !== 1) {
            return false;
        }

        //  Decode the password rules
        $oGroupPwRules = json_decode($oResult->row()->password_rules);

        if (empty($oGroupPwRules->expiresAfter)) {
            return false;
        }

        $sChanged = $oResult->row()->password_changed;

        if (is_null($sChanged)) {

            return true;

        } else {

            $oThen     = new \DateTime($sChanged);
            $oNow      = new \DateTime();
            $oInterval = $oNow->diff($oThen);

            return $oInterval->days >= $oGroupPwRules->expiresAfter;
        }
    }
420455
public function getToken($tokenId) {

		if($this->storage->hasToken($tokenId)) {
			return $this->storage->getToken($tokenId);
		}

		$token = new CsrfToken(
			$tokenId,
			$this->generateValue((int) $this->tokenLength)
		);

		$this->storage->setToken($tokenId, $token);

		return $token;
	}
766239
public function createReference($userId)
    {
        $myUserId = $userId;
        if(is_array($userId) && array_key_exists('id', $userId)){
            $myUserId = $userId['id'];
        }
        return 'SU:' . $myUserId;
    }