Creates a new directive keeping the user logged in ("remember me")

@param int $userId the user ID to keep signed in
@param int $duration the duration in seconds
@throws AuthError if an internal problem occurred (do *not* catch)
767678
private function createRememberDirective($userId, $duration) {
		$selector = self::createRandomString(24);
		$token = self::createRandomString(32);
		$tokenHashed = \password_hash($token, \PASSWORD_DEFAULT);
		$expires = \time() + ((int) $duration);

		try {
			$this->db->insert(
				$this->makeTableNameComponents('users_remembered'),
				[
					'user' => $userId,
					'selector' => $selector,
					'token' => $tokenHashed,
					'expires' => $expires
				]
			);
		}
		catch (Error $e) {
			throw new DatabaseError($e->getMessage());
		}

		$this->setRememberCookie($selector, $token, $expires);
	}
456362
public function login(UserInterface $user, $remember = false)
	{
		if ( ! $user->isActivated())
		{
			$login = $user->getLogin();
			throw new UserNotActivatedException("Cannot login user [$login] as they are not activated.");
		}

		$this->user = $user;

		// Create an array of data to persist to the session and / or cookie
		$toPersist = array($user->getId(), $user->getPersistCode());

		// Set sessions
		$this->session->put($toPersist);

		if ($remember)
		{
			$this->cookie->forever($toPersist);
		}

		// The user model can attach any handlers
		// to the "recordLogin" event.
		$user->recordLogin();
	}
288500
public function createLoginToken($userID) {
        $user = $this->getFind($userID);

        $user->login_token            = hash_hmac('sha256', Str::random(40), 'secret');
        $user->login_token_created_at = Carbon::now();

        return $user->save();
    }
37695
protected function rememberMe($username, $password)
    {
        $melisCoreConfig = $this->serviceLocator->get('MelisCoreConfig');
        $authCookieConfig = $melisCoreConfig->getItem('meliscore/datas/default/auth_cookies');
        $remember = $authCookieConfig['remember'];

        $user = new SetCookie('cookie1', $this->crypt($username), strtotime($remember));
        $pass = new SetCookie('cookie2', $this->crypt($password), strtotime($remember));
        $remember = new SetCookie('remember', 1, strtotime($remember));

        $this->getResponse()->getHeaders()->addHeader($user);
        $this->getResponse()->getHeaders()->addHeader($pass);
        $this->getResponse()->getHeaders()->addHeader($remember);

        // add code here for the session
        $melisCoreConfig = $this->getServiceLocator()->get('MelisCoreConfig');
        $autoLogoutTimeConf = $melisCoreConfig->getItem('meliscore/datas/default/auto_logout');
        $autoLogoutTime = (int) $autoLogoutTimeConf['after'];

        // automatic logout
        $sessionManager = new SessionManager();
        $sessionManager->rememberMe($autoLogoutTime);
        Container::setDefaultManager($sessionManager);
    }
620427
public function onPreCreate(UserEvent $event)
    {
        /** @var \Ekyna\Bundle\UserBundle\Model\UserInterface $user */
        $user = $event->getResource();

        // Generates a secured password.
        if (0 === strlen($user->getPlainPassword())) {
            $this->userManager->generatePassword($user);
            $user->setEnabled(true);

            // Warn about the generated password
            $password = $user->getPlainPassword();
            $event
                ->addMessage(new ResourceMessage(
                    sprintf('Generated password : "%s".', $password),
                    ResourceMessage::TYPE_INFO
                ))
                ->addData('password', $password)
            ;
        }

        $this->userManager->updatePassword($user);
        $this->userManager->updateCanonicalFields($user);
    }
1002013
protected function createRememberMeCookie(UserInterface $user, $cookieName, $cookieExpiration)
    {
        $ctp = new CookieTokenProvider();

        $ctp->createCookie(
            $user,
            $cookieName,
            $cookieExpiration
        );
    }
874157
private static function rememberMe(array $authConfig, $user, $number_of_days = 14)
    {
        $key = static::getFields($authConfig, true);
        $token = encrypt($user->$key);

        setcookie('remember_token', $token, time() + (86400 * $number_of_days));
    }
564789
public function presenceAuth($channel, $socketId, $userId, $userInfo = null)
    {
        $userData = array('userId' => $userId);

        if (! is_null($userInfo)) {
            $userData['userInfo'] = $userInfo;
        }

        return $this->socketAuth($channel, $socketId, json_encode($userData));
    }
1237856
public function setUserId( $userId )
    {
        $this->_user    = null;
        $this->userId   = ( (int) $userId ) ?: null;
        return $this;
    }
357644
public function saveSubscription(int $userId = null) : void
    {
        $json = \file_get_contents('php://input');

        if (!$json)
        {
            return;
        }

        $data = \json_decode($json, true);

        if (!$data || empty($data['endpoint']) || empty($data['publicKey']) || empty($data['authToken']))
        {
            return;
        }

        $row = $this->subscriptionTable->findActive()->where('endpoint', $data['endpoint'])->fetch();

        switch ($this->request->getMethod()) {
            case 'POST':
            case 'PUT':
            {
                if ($row)
                {
                    $row->update([
                        'user_id' => $userId ?: $row->user_id ?: null,
                        'key' => $data['publicKey'],
                        'token' => $data['authToken'],
                        'encoding' => $data['contentEncoding']
                    ]);
                    
                    return;
                }

                $row = $this->subscriptionTable->insert([
                    'user_id' => $userId,
                    'endpoint' => $data['endpoint'],
                    'key' => $data['publicKey'],
                    'token' => $data['authToken'],
                    'encoding' => $data['contentEncoding']
                ]);

                $this->sendNotification($row, 'Notifications enabled!', true);

                return;
            }
            case 'DELETE':
            {
                if ($row)
                {
                    $row->update([
                        'active' => 0
                    ]);
                }

                return;
            }
            default:
                throw new \Nette\Application\BadRequestException();
        }
    }
490710
public function doTwoFactorAuthLogin($userId) {

        // Get the 2FA code
        $codeToInput = $this->getCodeToInput();

        // Update the user's database record wtih the 2FA code & timestamp
        $this->updateUserRecordWithTwoFactorAuthCode($codeToInput, $userId);

        // Put together the SMS message
        $message  = config('lasallecmsfrontend.site_name');
        $message .= ". Your two factor authorization login code is ";
        $message .= $codeToInput;

        $this->shortMessageService->sendSMS($this->getUserPhoneCountryCode($userId), $this->getUserPhoneNumber($userId), $message);
    }
311351
public function generateToken($userId)
    {
        $user = $this->users->find($userId);

        if (! is_null($user)) {
            $user->generateInvitationToken();
            $user->trackTime('invited_at');
            $user->setStatus(Status::INACTIVE);
        }
    }
484085
public function buildLink($userId, $ip, $userAgent)
    {
        $link = new UserLink();
        $link->user_id = $userId;
        $link->type = UserLink::FORGOT_PASSWORD;

        try {
            $link->save();
        } catch (\Exception $e) {
            throw new \Exception("Could not create reset password link for user # $userId: ".$e->getMessage());
        }

        // record the reset password request event
        $event = new AccountSecurityEvent();
        $event->user_id = $userId;
        $event->type = AccountSecurityEvent::RESET_PASSWORD_REQUEST;
        $event->ip = $ip;
        $event->user_agent = $userAgent;
        $event->save();

        return $link;
    }
33625
public function createOrUpdateAuthRecord($userId) {
        $token = $this->_getToken($userId);
        $authPwlessModel = new Model_AuthPasswordless();
        $select = $authPwlessModel->select()->where('user_id = ?', $userId);
        if ($authRecord = $authPwlessModel->fetchRow($select)) {
            $authPwlessModel->update(
                array(
                    'token' => $token,
                    'token_expiration_date' => $this->_getExpirationDate(),
                    'claimed' => 0
                ), 'id = ' . $authRecord->id
            );
            return $token;
        }
        $authPwlessModel->insert(
            array(
                'user_id' => $userId,
                'token' => $token,
                'token_expiration_date' => $this->_getExpirationDate()
            )
        );
        return $token;
    }
1235623
public function setDuration($duration)
    {
        // get dom element
        $durationDomElement = $this->getDomElement()->getElementsByTagName('Duration')->item(0);
        if (!$durationDomElement) {
            $durationDomElement = $this->getDomElement()->ownerDocument->createElement('Duration');
            $this->getDomElement()->firstChild->appendChild($durationDomElement);
        }

        // set value
        if (is_numeric($duration)) {
            // in seconds
            $duration = $this->secondsToString($duration);
        }

        $durationDomElement->nodeValue = $duration;

        return $this;
    }
191252
public function enableCmdlCaching($duration = null)
    {
        if ($duration == null) {
            $duration = $this->duration;
        }
        $this->cmdlCaching = $duration;

        $checkLastModifiedDate = false;
        if ($this->hasLastModifiedCacheStrategy()) {
            $checkLastModifiedDate = true;
        }

        $this->readConnection->enableCMDLCaching($duration, $checkLastModifiedDate);
        if ($this->writeConnection) {
            $this->writeConnection->enableCMDLCaching($duration, $checkLastModifiedDate);
        }
    }
958144
public static function save($key, $value, $duration = null) {
        self::setLifetime($duration);
        static::init();
        $_SESSION[self::$prepend . $key] = $value;
    }