Completed
Push — develop ( 3a7cc0...30ece7 )
by Anton
16:03 queued 14:14
created

Token::verify()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
nc 3
nop 1
dl 0
loc 12
ccs 0
cts 6
cp 0
crap 12
rs 9.8666
c 0
b 0
f 0
1
<?php
2
/**
3
 * @copyright Bluz PHP Team
4
 * @link      https://github.com/bluzphp/skeleton
5
 */
6
7
declare(strict_types=1);
8
9
namespace Application\Auth\Provider;
10
11
use Application\Auth\Row;
12
use Application\Auth\Table;
13
use Application\Users\Table as UsersTable;
14
use Bluz\Auth\AuthException;
15
use Bluz\Proxy\Auth;
16
17
/**
18
 * Token Provider
19
 *
20
 * @package  Application\Auth
21
 * @author   Anton Shevchuk
22
 */
23
class Token extends AbstractProvider
24
{
25
    public const PROVIDER = Table::PROVIDER_TOKEN;
26
27
    /**
28
     * {@inheritdoc}
29
     *
30
     * @throws AuthException
31
     * @throws \Bluz\Db\Exception\DbException
32
     * @throws \Bluz\Db\Exception\InvalidPrimaryKeyException
33
     */
34
    public static function authenticate($token): void
35
    {
36
        $authRow = self::verify($token);
37
        $user = UsersTable::findRow($authRow->userId);
38
39
        // try to login
40
        Table::tryLogin($user);
41
    }
42
43
    /**
44
     * {@inheritdoc}
45
     *
46
     * @return Row
47
     * @throws AuthException
48
     * @throws \Bluz\Db\Exception\DbException
49
     */
50
    public static function verify($token): Row
51
    {
52
        if (!$authRow = Table::findRowWhere(['token' => $token, 'provider' => self::PROVIDER])) {
53
            throw new AuthException('Invalid token');
54
        }
55
56
        if ($authRow->expired < gmdate('Y-m-d H:i:s')) {
57
            throw new AuthException('Token has expired');
58
        }
59
60
        return $authRow;
61
    }
62
63
    /**
64
     * {@inheritdoc}
65
     *
66
     * @return Row
67
     * @throws \Bluz\Db\Exception\DbException
68
     * @throws \Bluz\Db\Exception\InvalidPrimaryKeyException
69
     * @throws \Bluz\Db\Exception\TableNotFoundException
70
     */
71 1
    public static function create($user): Row
72
    {
73
        // clear previous generated Auth record
74 1
        self::remove($user->id);
75
76 1
        $ttl = Auth::getInstance()->getOption('token', 'ttl');
77
78
        // new auth row
79 1
        $row = new Row();
80 1
        $row->userId = $user->id;
81 1
        $row->foreignKey = $user->login;
82 1
        $row->provider = Table::PROVIDER_TOKEN;
83 1
        $row->tokenType = Table::TYPE_ACCESS;
84 1
        $row->expired = gmdate('Y-m-d H:i:s', time() + $ttl);
85 1
        $row->token = bin2hex(random_bytes(32));
86
87 1
        $row->save();
88
89 1
        return $row;
90
    }
91
}
92