@param ApiClientInterface $client
@param UserInterface      $user

@return TokenInterface
345418
public function createWithExpirationDate(ApiClientInterface $client, UserInterface $user = null)
    {
        $accessToken = $this->create($client, $user);
        $accessToken->setExpiredAt(new \DateTime($this->tokenExpiration));

        return $accessToken;
    }
416279
public static function fromToken(TokenInterface $token)
    {
        $user = $token->getUser();

        if ($user instanceof UserInterface) {
            return self::fromAccount($user);
        }

        throw new InvalidArgumentException('The user class must implement "Fxp\Component\Security\Model\UserInterface"');
    }
1069333
public static function create(UserInterface $user): UserMetaInterface
    {
        /** @var AbstractUser $user */
        $user_meta = static::findOne(['user_id' => $user->id]);
        if ($user_meta instanceof UserMetaInterface) {
            return $user_meta;
        }
        $user_meta = new static([
            'user_id' => $user->id,
            'notification_email' => $user->email,
            'display_name' => $user->username,
        ]);
        (new UserMetaHandler($user_meta))->create();
        $user_meta->refresh();
        return $user_meta;
    }
450999
public function checkCode(UserInterface $user, $code)
    {
        return $this->authenticator->checkCode($user->getTwoStepVerificationCode(), $code);
    }
577799
public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey)
    {
        if (empty($this->secretKey) == false) {
            $captcha = $this->request->get('g-recaptcha-response');

            $reCaptcha = new ReCaptcha($this->secretKey);
            $response = $reCaptcha->verify($captcha, $this->request->getClientIp());

            if ($response->isSuccess() == false) {
                throw new AuthenticationException('Captcha not passed');
            }
        }

        try {
            $user = $userProvider->loadUserByUsername($token->getUsername());
        } catch (UsernameNotFoundException $e) {
            throw new AuthenticationException('Invalid username or password');
        }

        $passwordValid = $this->encoder->isPasswordValid($user, $token->getCredentials());

        if ($passwordValid) {
            return new UsernamePasswordToken(
                $user,
                $user->getPassword(),
                $providerKey,
                $user->getRoles()
            );
        }

        throw new AuthenticationException('Invalid username or password');
    }
1049906
public function create(ClientInterface $client): ClientInterface
    {
        try {
            $now    = $this->ignoreException(function (): DateTimeImmutable {
                return new DateTimeImmutable();
            });
            $schema = $this->getDatabaseSchema();
            $values = [
                $schema->getClientsIdentityColumn()               => $client->getIdentifier(),
                $schema->getClientsNameColumn()                   => $client->getName(),
                $schema->getClientsDescriptionColumn()            => $client->getDescription(),
                $schema->getClientsCredentialsColumn()            => $client->getCredentials(),
                $schema->getClientsIsConfidentialColumn()         => $client->isConfidential(),
                $schema->getClientsIsScopeExcessAllowedColumn()   => $client->isScopeExcessAllowed(),
                $schema->getClientsIsUseDefaultScopeColumn()      => $client->isUseDefaultScopesOnEmptyRequest(),
                $schema->getClientsIsCodeGrantEnabledColumn()     => $client->isCodeGrantEnabled(),
                $schema->getClientsIsImplicitGrantEnabledColumn() => $client->isImplicitGrantEnabled(),
                $schema->getClientsIsPasswordGrantEnabledColumn() => $client->isPasswordGrantEnabled(),
                $schema->getClientsIsClientGrantEnabledColumn()   => $client->isClientGrantEnabled(),
                $schema->getClientsIsRefreshGrantEnabledColumn()  => $client->isRefreshGrantEnabled(),
                $schema->getClientsCreatedAtColumn()              => $now,
            ];

            $identifier = $client->getIdentifier();
            if (empty($scopeIdentifiers = $client->getScopeIdentifiers()) === true) {
                $this->createResource($values);
            } else {
                $this->inTransaction(function () use ($identifier, $values, $scopeIdentifiers) {
                    $this->createResource($values);
                    $this->bindScopeIdentifiers($identifier, $scopeIdentifiers);
                });
            }
            $client->setCreatedAt($now);

            return $client;
        } catch (RepositoryException $exception) {
            $message = 'Client creation failed.';
            throw new RepositoryException($message, 0, $exception);
        }
    }
286279
public function updateRememberToken(UserInterface $user, $token)
    {
        $user->setRememberToken($token);
        $this->entityManager->persist($user);
        $this->entityManager->flush();
    }
1117610
public function update(ServerRequestInterface $request, UserInterface $user): ResponseInterface
    {
        $user_id        = (int) $request->getParsedBody()['user_id'];
        $username       = $request->getParsedBody()['username'];
        $real_name      = $request->getParsedBody()['real_name'];
        $email          = $request->getParsedBody()['email'];
        $password       = $request->getParsedBody()['password'];
        $theme          = $request->getParsedBody()['theme'];
        $language       = $request->getParsedBody()['language'];
        $timezone       = $request->getParsedBody()['timezone'];
        $contact_method = $request->getParsedBody()['contact_method'];
        $comment        = $request->getParsedBody()['comment'];
        $auto_accept    = (bool) ($request->getParsedBody()['auto_accept'] ?? false);
        $canadmin       = (bool) ($request->getParsedBody()['canadmin'] ?? false);
        $visible_online = (bool) ($request->getParsedBody()['visible_online'] ?? false);
        $verified       = (bool) ($request->getParsedBody()['verified'] ?? false);
        $approved       = (bool) ($request->getParsedBody()['approved'] ?? false);

        $edit_user = $this->user_service->find($user_id);

        if ($edit_user === null) {
            throw new NotFoundHttpException(I18N::translate('%1$s does not exist', 'user_id:' . $user_id));
        }

        // We have just approved a user.  Tell them
        if ($edit_user->getPreference('verified_by_admin') !== '1' && $approved) {
            I18N::init($edit_user->getPreference('language'));

            Mail::send(
                Auth::user(),
                $edit_user,
                Auth::user(),
                /* I18N: %s is a server name/URL */
                I18N::translate('New user at %s', WT_BASE_URL),
                view('emails/approve-user-text', ['user' => $edit_user, 'site_url' => WT_BASE_URL]),
                view('emails/approve-user-html', ['user' => $edit_user, 'site_url' => WT_BASE_URL])
            );
        }

        $edit_user
            ->setRealName($real_name)
            ->setPreference('theme', $theme)
            ->setPreference('language', $language)
            ->setPreference('TIMEZONE', $timezone)
            ->setPreference('contactmethod', $contact_method)
            ->setPreference('comment', $comment)
            ->setPreference('auto_accept', (string) $auto_accept)
            ->setPreference('visibleonline', (string) $visible_online)
            ->setPreference('verified', (string) $verified)
            ->setPreference('verified_by_admin', (string) $approved);

        if ($password !== '') {
            $edit_user->setPassword($password);
        }

        // We cannot change our own admin status. Another admin will need to do it.
        if ($edit_user->id() !== $user->id()) {
            $edit_user->setPreference('canadmin', $canadmin ? '1' : '0');
        }

        foreach (Tree::getAll() as $tree) {
            $path_length = (int) $request->getParsedBody()['RELATIONSHIP_PATH_LENGTH' . $tree->id()];
            $gedcom_id   = $request->getParsedBody()['gedcomid' . $tree->id()];
            $can_edit    = $request->getParsedBody()['canedit' . $tree->id()];

            // Do not allow a path length to be set if the individual ID is not
            if ($gedcom_id === '') {
                $path_length = 0;
            }

            $tree->setUserPreference($edit_user, 'gedcomid', $gedcom_id);
            $tree->setUserPreference($edit_user, 'canedit', $can_edit);
            $tree->setUserPreference($edit_user, 'RELATIONSHIP_PATH_LENGTH', (string) $path_length);
        }

        if ($edit_user->email() !== $email && $this->user_service->findByEmail($email) instanceof User) {
            FlashMessages::addMessage(I18N::translate('Duplicate email address. A user with that email already exists.') . $email, 'danger');

            return redirect(route('admin-users-edit', ['user_id' => $edit_user->id()]));
        }

        if ($edit_user->userName() !== $username && $this->user_service->findByUserName($username) instanceof User) {
            FlashMessages::addMessage(I18N::translate('Duplicate username. A user with that username already exists. Please choose another username.'), 'danger');

            return redirect(route('admin-users-edit', ['user_id' => $edit_user->id()]));
        }

        $edit_user
            ->setEmail($email)
            ->setUserName($username);

        return redirect(route('admin-users'));
    }
826130
public function handleLogin(UserEntity $user)
    {
        $accessToken = new AccessToken($this->tokenStorage, $this->tokenStorage);
        $token = $accessToken->createAccessToken('', $user->getId(), null, true);

        return $token;
    }
937665
public function authenticateToken(TokenInterface $token,
                                      UserProviderInterface $userProvider,
                                      $providerKey)
    {
        if (($user = $userProvider->loadUserByUsername($token->getUsername())) && ($user->getPassword()
            == $token->getCredentials())) {
            return new UsernamePasswordToken(
                $user, $user->getPassword(), $providerKey, $user->getRoles()
            );
        }
        throw new BadCredentialsException('The presented password is invalid.');
    }
864045
public static function fromToken(TokenInterface $token)
    {
        $user = $token->getUser();

        if ($user instanceof UserInterface) {
            return self::fromAccount($user);
        }

        return new self((string) $user, is_object($user) ? ClassUtils::getRealClass($user) : ClassUtils::getRealClass($token));
    }
904536
private function _getClient(): ClientInterface
    {
        if (! $this->client instanceof ClientInterface) $this->client = new Client($this->clientConfig);
        return $this->client;
    }
270261
public function createTokenResponse(
        ServerRequestInterface $request,
        Client $client = null,
        TokenOwnerInterface $owner = null
    ): ResponseInterface {
        $postParams = $request->getParsedBody();

        $code = $postParams['code'] ?? null;

        if (null === $code) {
            throw OAuth2Exception::invalidRequest('Could not find the authorization code in the request');
        }

        /* @var \ZfrOAuth2\Server\Model\AuthorizationCode $authorizationCode */
        $authorizationCode = $this->authorizationCodeService->getToken($code);

        if (null === $authorizationCode || $authorizationCode->isExpired()) {
            throw OAuth2Exception::invalidGrant('Authorization code cannot be found or is expired');
        }

        $clientId = $postParams['client_id'] ?? null;

        if ($authorizationCode->getClient()->getId() !== $clientId) {
            throw OAuth2Exception::invalidRequest(
                'Authorization code\'s client does not match with the one that created the authorization code'
            );
        }

        // If owner is null, we reuse the same as the authorization code
        $owner = $owner ?: $authorizationCode->getOwner();

        // Everything is okey, let's start the token generation!
        $scopes = $authorizationCode->getScopes(); // reuse the scopes from the authorization code

        $accessToken = $this->accessTokenService->createToken($owner, $client, $scopes);

        // Before generating a refresh token, we must make sure the authorization server supports this grant
        $refreshToken = null;

        if ($this->authorizationServer->hasGrant(RefreshTokenGrant::GRANT_TYPE)) {
            $refreshToken = $this->refreshTokenService->createToken($owner, $client, $scopes);
        }

        return $this->prepareTokenResponse($accessToken, $refreshToken);
    }
1067492
public static function getHttpClient($token, $client = null)
    {
        if ($client == null) {
            $client = new Zend_Gdata_HttpClient();
        }
        if (!$client instanceof Zend_Gdata_HttpClient) {
            require_once 'Zend/Gdata/App/HttpException.php';
            throw new Zend_Gdata_App_HttpException('Client is not an instance of Zend_Gdata_HttpClient.');
        }
        $useragent = 'Zend_Framework_Gdata/' . Zend_Version::VERSION;
        $client->setConfig(array(
                'strictredirects' => true,
                'useragent' => $useragent
            )
        );
        $client->setAuthSubToken($token);
        return $client;
    }
651703
public function getToken(UserSession $user): Token
    {
        // @todo Test that the expiresAfter() call works. We don't want to be caught
        // by cron etc.
        $item = $this->cacheItemPool->getItem($this->cacheKey($user));

        if (!$item->isHit()) {
            throw new TokenNotFoundException($user);
        }

        return $item->get();
    }
1358236
public function register(ClientInterface $client)
    {
        $client = $this->decorate($client);

        array_push($this->clients, $client);

        return $client;
    }
438938
protected function validateUser(ServerRequestInterface $request, ClientEntityInterface $client)
    {
        $username = $this->getRequestParameter('username', $request);
        if (is_null($username)) {
            throw OAuthServerException::invalidRequest('username');
        }

        $password = $this->getRequestParameter('password', $request);
        if (is_null($password)) {
            throw OAuthServerException::invalidRequest('password');
        }

        $user = $this->userRepository->getUserEntityByUserCredentials(
            $username,
            $password,
            $this->getIdentifier(),
            $client
        );
        if ($user instanceof UserEntityInterface === false) {
            $this->getEmitter()->emit(new RequestEvent(RequestEvent::USER_AUTHENTICATION_FAILED, $request));

            throw OAuthServerException::invalidCredentials();
        }

        return $user;
    }