Generate an access token for the specified user.

@param int $userId
@param int $lifetime
@return static
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;
    }
228995
private function getUserAccount($userId)
    {
        $user = $this->entityManager->getStorage('user')->load($userId);

        if (!$user) {
            throw new \InvalidArgumentException(sprintf("User %d does not exist", $userId));
        }

        return $user;
    }
72692
public function make($userId, $csrfToken)
    {
        $config = $this->config->get('session');

        $expiration = Carbon::now()->addMinutes($config['lifetime']);

        return new Cookie(
            Passport::cookie(),
            $this->createToken($userId, $csrfToken, $expiration),
            $expiration,
            $config['path'],
            $config['domain'],
            $config['secure'],
            true,
            false,
            $config['same_site'] ?? null
        );
    }
1233962
public function save($id, $data, $lifeTime = 0)
    {
        return $this->cacheProvider->save($id, $data, $lifeTime);
    }
301650
public static function create($user_id) {
	$text  = bootstrap::get_library('text');
	$mysql = bootstrap::get_library('mysql');
	
	$new_token  = $text::generate_token(self::TOKEN_LENGTH);
	$expiration = (time() + self::EXPIRATION);
	
	$sql   = "INSERT INTO `login_tokens` SET `code` = '%s', `user_id` = %d, `expire_at` = %d;";
	$binds = [$new_token, $user_id, $expiration];
	$mysql::query($sql, $binds);
	
	return new static($mysql::$insert_id);
}
1303618
public function generateToken($userID) {
		$token = uniqid();

		$stmntToken = $this->db->prepare("UPDATE " . $this->settings['db_login_table'] . " SET token = ?, tokentime = NOW() WHERE ID = ?");
		$this->db->update($stmntToken, array($token, $userID));

		return $token;
	}
1193425
public static function create(string $name, int $lifetime = 300): string
    {
        $token = sha1(microtime());
        $tokenData = [
            'token' => $token,
            'time' => time(),
            'lifetime' => $lifetime
        ];
        Session::set($name, $tokenData, self::$namespace);
        return $token;
    }
1120860
public UserEntity createNewUser(String userId) {
    checkAuthorization(Permissions.CREATE, Resources.USER, null);
    return new UserEntity(userId);
  }
701457
public function set($id, $data, $lifeTime = 0)
    {
        if (!function_exists('apc_store')) {
            throw new ApcCacheException('function [apc_store] not found !');
        }

        return apc_store($id, $data, $lifeTime);
    }
1067107
static public function create($groupId, $userId, $role)
    {
        $instance = new self();

        $instance->group_id = (int)$groupId;
        $instance->user_id = (int)$userId;
        $instance->role = (int)$role;

        return $instance;
    }
1354673
public function newAuthorizeRequest($owner, $owner_id, $options)
  {
    return $this->authServer->getGrantType('authorization_code')->newAuthoriseRequest($owner, $owner_id, $options);
  }
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;
        }
    }
1110325
public static function makeJWTByUser($userId, $email, $forever = false)
    {
        if (\Config::get('df.allow_forever_sessions') === false) {
            $forever = false;
        }
        $customClaims = ['user_id' => $userId, 'forever' => $forever];
        $customClaimFields = config('jwt.custom_claims');
        if (!empty($customClaimFields)) {
            /** @var User $user */
            $user = User::find($userId);
            if (!empty($user)) {
                $user = $user->toArray();
                foreach ($customClaimFields as $ccf) {
                    $value = array_get($user, $ccf);
                    if (!empty($value)) {
                        $customClaims[$ccf] = $value;
                    }
                }
            }
        }

        /** @type Payload $payload */
        /** @noinspection PhpUndefinedMethodInspection */
        $payload = JWTFactory::sub(md5($email))->customClaims($customClaims)->make();
        /** @type Token $token */
        $token = JWTAuth::manager()->encode($payload);
        $tokenValue = $token->get();
        static::setTokenMap($payload, $tokenValue);

        return $tokenValue;
    }
456679
public static function init($lifeTime = 0)
    {
        if (self::$sessionStarted == false) {
            session_set_cookie_params($lifeTime);
            session_start();

            return self::$sessionStarted = true;
        }

        return false;
    }
224958
public static function get_contexts_for_userid(int $userid) : contextlist {
        $params = ['userid' => $userid, 'contextcourse' => CONTEXT_COURSE];
        $sql = "SELECT ctx.id
                FROM {context} ctx
                JOIN {stats_user_daily} sud ON sud.courseid = ctx.instanceid AND sud.userid = :userid
                WHERE ctx.contextlevel = :contextcourse";

        $contextlist = new contextlist();
        $contextlist->add_from_sql($sql, $params);

        $sql = "SELECT ctx.id
                FROM {context} ctx
                JOIN {stats_user_weekly} suw ON suw.courseid = ctx.instanceid AND suw.userid = :userid
                WHERE ctx.contextlevel = :contextcourse";
        $contextlist->add_from_sql($sql, $params);

        $sql = "SELECT ctx.id
                FROM {context} ctx
                JOIN {stats_user_monthly} sum ON sum.courseid = ctx.instanceid AND sum.userid = :userid
                WHERE ctx.contextlevel = :contextcourse";
        $contextlist->add_from_sql($sql, $params);

        return $contextlist;
    }
888845
final function throttle(string $userID) {
        if(empty($this->throttling) || $this->client->isOwner($userID)) {
            return null;
        }
        
        if(!$this->throttles->has($userID)) {
            $this->throttles->set($userID, array(
                'start' => \time(),
                'usages' => 0,
                'timeout' => $this->client->addTimer($this->throttling['duration'], function () use ($userID) {
                    $this->throttles->delete($userID);
                })
            ));
        }
        
        return $this->throttles->get($userID);
    }
1237856
public function setUserId( $userId )
    {
        $this->_user    = null;
        $this->userId   = ( (int) $userId ) ?: null;
        return $this;
    }