Generate verification token.

@author Paulius Navickas <pana@nodes.dk>

@param  \Illuminate\Database\Eloquent\Model $user
@return string
775070
protected function generateEmailVerificationToken(IlluminateModel $user)
    {
        // Generate new token using Laravel's encryption key
        $token = hash_hmac('sha256', str_random(40), config('app.key'));

        // Expire timestamp
        $expire = Carbon::now()->addDays(config('nodes.api.email-verification.expire', 1));

        // If user has previously tried to reset his/her password
        // we should just update the token of the previous entry
        // instead of creating a new one
        $verificationToken = $this->where('email', '=', $user->email)->first();
        if (! empty($verificationToken)) {
            $verificationToken->update(['token' => $token, 'used' => 0, 'expire_at' => $expire->format('Y-m-d H:i:s')]);
        } else {
            $this->create(['email' => $user->email, 'token' => $token, 'expire_at' => $expire->format('Y-m-d H:i:s')]);
        }

        return $token;
    }
339763
public static function getAccountChecksum(int $node, int $user): string
    {
        return sprintf('%04X', self::crc16(sprintf('%04X%08X', $node, $user)));
    }
241637
public function verifyEmail(User $user, $token)
    {
        $this->_prepareEmail($user, __d('wasabi_core', 'Verify your email address'));
        $this->_email->template('Wasabi/Core.User/verify');
        $this->_email->viewVars([
            'user' => $user,
            'verifyEmailLink' => [
                'plugin' => 'Wasabi/Core',
                'controller' => 'Users',
                'action' => 'verifyByToken',
                'token' => $token
            ],
            'instanceName' => Wasabi::getInstanceName()
        ]);
    }
547019
public function sendCreationMessage(User $user)
    {
        $locale = $this->container->get('claroline.manager.locale_manager')->getLocale($user);
        $url = $this->router->generate(
            'claro_security_validate_email',
            ['hash' => $user->getEmailValidationHash()],
            UrlGeneratorInterface::ABSOLUTE_URL
        );
        $placeholders = [
            'first_name' => $user->getFirstName(),
            'last_name' => $user->getLastName(),
            'username' => $user->getUsername(),
            'password' => $user->getPlainPassword(),
            'validation_mail' => $url,
        ];
        $subject = $this->templateManager->getTemplate('claro_mail_registration', $placeholders, $locale, 'title');
        $body = $this->templateManager->getTemplate('claro_mail_registration', $placeholders, $locale);

        return $this->send($subject, $body, [$user], null, [], true);
    }
816924
public function getNotification($user)
    {
        return MessageNotification::where('user_id', $user->getKey())
            ->where('message_id', $this->id)
            ->select(['mc_message_notification.*', 'mc_message_notification.updated_at as read_at'])
            ->first();
    }
1347984
public function publicKey(User $user, $reset = false)
    {
        $model = ApiPublicPrivate::query()->firstOrNew(['user_id' => $user->id]);
        if (!$model->exists or $reset) {
            $model->public_key = hash('sha256', openssl_random_pseudo_bytes(32));
            $model->save();
        }
        return $model->public_key;
    }
1338954
public function verify( $user, $token ) {

		// Check Token
		if( $user->isVerifyTokenValid( $token ) ) {

			$modelClass	= static::$modelClass;

			// Find existing user
			$userToUpdate = $modelClass::findById( $user->id );

			// User need admin approval
			if( Yii::$app->core->isUserApproval() ) {

				$userToUpdate->verify();
			}
			// Direct approval and activation
			else {

				$userToUpdate->status = User::STATUS_ACTIVE;
			}

			$userToUpdate->unsetVerifyToken();

			$userToUpdate->update();

			return true;
		}

		return false;
	}
474823
protected function getNameFromUser($user)
    {
        switch (true) {
            // favour (potentially) unchanging user credentials
            case $user instanceof Contracts\UniversallyIdentifiable:
                return $user->getUuid();

            case $user instanceof AuthenticatableContract:
                return $user->getAuthIdentifier();

            case $user instanceof Contracts\Identifiable:
                return $user->getId();

            case $user instanceof Contracts\Nameable:
                return $user->getName();

            default:
                return null;
        }
    }
459635
public function createUser(User $user, $password)
    {
        $request = $user->toJson();
        $request['password'] = $password;
        $response = $this->client->post('/v2/user', $request);

        return $response['id'];
    }
1284227
public static function generate_token($user) {
        $generator = new \RandomGenerator();
        $tokenString = $generator->randomToken();
        $e = \PasswordEncryptor::create_for_algorithm('blowfish');
        $salt = $e->salt($tokenString);
        $token = sha1($e->encrypt($tokenString, $salt)) . substr(md5($user->Created.$user->LastEdited.$user->ID), 7);
        return $token;
    }
448558
protected function afterRegister($user)
    {
        /** @var \amnah\yii2\user\models\UserToken $userToken */
        $userToken = $this->module->model("UserToken");

        // determine userToken type to see if we need to send email
        $userTokenType = null;
        if ($user->status == $user::STATUS_INACTIVE) {
            $userTokenType = $userToken::TYPE_EMAIL_ACTIVATE;
        } elseif ($user->status == $user::STATUS_UNCONFIRMED_EMAIL) {
            $userTokenType = $userToken::TYPE_EMAIL_CHANGE;
        }

        // check if we have a userToken type to process, or just log user in directly
        if ($userTokenType) {
            $userToken = $userToken::generate($user->id, $userTokenType);
            if (!$numSent = $user->sendEmailConfirmation($userToken)) {

                // handle email error
                //Yii::$app->session->setFlash("Email-error", "Failed to send email");
            }
        } else {
            Yii::$app->user->login($user, $this->module->loginDuration);
        }
    }
889958
protected function getUserId($user)
    {
        if (is_null($user))
        {
            $user = auth()->user();
        }

        if ($user instanceof Model)
        {
            $user = $user->getKey();
        }

        return $user;
    }
188256
protected function sendReactivationEmail(User $user)
    {
        $forum = Podium::getInstance()->podiumConfig->get('name');
        $email = Content::fill(Content::EMAIL_REACTIVATION);
        if ($email !== false) {
            $link = Url::to(['account/activate', 'token' => $user->activation_token], true);
            return Email::queue(
                $user->email,
                str_replace('{forum}', $forum, $email->topic),
                str_replace('{forum}', $forum, str_replace('{link}',
                    Html::a($link, $link), $email->content)),
                !empty($user->id) ? $user->id : null
            );
        }
        return false;
    }
843278
public function passwordConfirmation($user)
    {
        $mail = $this->getMailInstance();

        $from = Configure::read('CM.Mail.from');
        $options = Configure::read('CM.Mail.passwordConfirmation');

        if ($options) {
            $fullBaseUrl = Configure::read('App.fullBaseUrl');

            $mail->viewVars([
                'user' => $user,
                'fullBaseUrl' => $fullBaseUrl,
                'loginUrl' => $fullBaseUrl . '/login',
                'from' => reset($from),
            ]);

            $mail->template($options['template'], $options['layout']);

            $mail->emailFormat($this->config('emailFormat'));

            $mail->from($from);

            $mail->to($user['email']);

            $mail->subject($options['subject']);

            $mail->send();

            return $mail;
        }
    }
813022
public function generateEmailValidationCode(Garp_Db_Table_Row $user, $validationToken) {
        $authVars = Garp_Auth::getInstance()->getConfigValues();

        $validationCode  = '';
        $validationCode .= $validationToken;
        $validationCode .= md5($user->email);
        $validationCode .= md5($authVars['salt']);
        $validationCode .= md5($user->id);
        $validationCode = md5($validationCode);
        return $validationCode;
    }
476560
public function create(User $user)
    {
        /* handle encode */
        $user = $this->encode($user);

        $this->getEm()->persist($user);
        $this->getEm()->flush();

        return $user;
    }
914113
public function findValidToken($user, $client)
    {
        return $client->tokens()
                      ->whereUserId($user->getKey())
                      ->where('revoked', 0)
                      ->where('expires_at', '>', Carbon::now())
                      ->latest('expires_at')
                      ->first();
    }