Completed
Pull Request — master (#295)
by Anton
04:43
created

Token::create()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 1

Importance

Changes 0
Metric Value
nc 1
dl 0
loc 20
ccs 12
cts 12
cp 1
c 0
b 0
f 0
cc 1
eloc 12
nop 1
crap 1
rs 9.4285
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
    const PROVIDER = Table::PROVIDER_TOKEN;
26
27
    public static function authenticate($token)
28
    {
29
        $authRow = self::verify($token);
30
        $user = UsersTable::findRow($authRow->userId);
31
32
        // try to login
33
        $user->tryLogin();
34
    }
35
36
    public static function verify($token) : Row
37
    {
38
        if (!$authRow = Table::findRowWhere(['token' => $token, 'provider' => self::PROVIDER])) {
39
            throw new AuthException('Invalid token');
40
        }
41
42
        if ($authRow->expired < gmdate('Y-m-d H:i:s')) {
43
            throw new AuthException('Token has expired');
44
        }
45
46
        return $authRow;
47
    }
48
49 1
    public static function create($user) : Row
50
    {
51
        // clear previous generated Auth record
52 1
        self::remove($user->id);
53
54 1
        $ttl = Auth::getInstance()->getOption('token', 'ttl');
55
56
        // new auth row
57 1
        $row = new Row();
58 1
        $row->userId = $user->id;
59 1
        $row->foreignKey = $user->login;
60 1
        $row->provider = Table::PROVIDER_TOKEN;
61 1
        $row->tokenType = Table::TYPE_ACCESS;
62 1
        $row->expired = gmdate('Y-m-d H:i:s', time() + $ttl);
63 1
        $row->token = bin2hex(random_bytes(32));
64
65 1
        $row->save();
66
67 1
        return $row;
68
    }
69
}
70