aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/OAuth2/Bridge/AccessTokenRepository.php
blob: 2762f6bbc49ca7b9ec975aa4054cd0b197a2c906 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?php

namespace Studip\OAuth2\Bridge;

use League\OAuth2\Server\Entities\AccessTokenEntityInterface;
use League\OAuth2\Server\Entities\ClientEntityInterface;
use League\OAuth2\Server\Entities\ScopeEntityInterface;
use League\OAuth2\Server\Exception\UniqueTokenIdentifierConstraintViolationException;
use League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface;
use Studip\OAuth2\Models\AccessToken;

class AccessTokenRepository implements AccessTokenRepositoryInterface
{
    use ScopesHelper;

    /**
     * Create a new access token.
     *
     * @param ScopeEntityInterface[] $scopes
     * @param mixed                  $userIdentifier
     *
     * @return AccessTokenEntityInterface
     */
    public function getNewToken(ClientEntityInterface $clientEntity, array $scopes, $userIdentifier = null)
    {
        return new AccessTokenEntity($userIdentifier, $scopes, $clientEntity);
    }

    /**
     * Persists a new access token to permanent storage.
     *
     * @throws UniqueTokenIdentifierConstraintViolationException
     */
    public function persistNewAccessToken(AccessTokenEntityInterface $accessTokenEntity): void
    {
        AccessToken::create([
            'id'         => $accessTokenEntity->getIdentifier(),
            'user_id'    => $accessTokenEntity->getUserIdentifier(),
            'client_id'  => $accessTokenEntity->getClient()->getIdentifier(),
            'scopes'     => $this->formatScopes($accessTokenEntity->getScopes()),
            'revoked'    => 0,
            'expires_at' => $accessTokenEntity->getExpiryDateTime()->getTimestamp(),
        ]);

        // TODO: Logging and metrics
    }

    /**
     * Revoke an access token.
     *
     * @param string $tokenId
     */
    public function revokeAccessToken($tokenId): void
    {
        $accesstoken = AccessToken::find($tokenId);
        if ($accesstoken) {
            $accesstoken->revoke();
        }
    }

    /**
     * Check if the access token has been revoked.
     *
     * @param string $tokenId
     *
     * @return bool Return true if this token has been revoked
     */
    public function isAccessTokenRevoked($tokenId): bool
    {
        $accesstoken = AccessToken::find($tokenId);

        return $accesstoken ? $accesstoken->isRevoked() : true;
    }
}