Completed
Pull Request — master (#295)
by Anton
14:50
created

Token   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 8

Importance

Changes 0
Metric Value
dl 0
loc 47
c 0
b 0
f 0
rs 10
wmc 5
lcom 1
cbo 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
A authenticate() 0 8 1
A verify() 0 12 3
A create() 0 20 1
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
    public static function create($user) : Row
50
    {
51
        // clear previous generated Auth record
52
        self::remove($user->id);
53
54
        $ttl = Auth::getInstance()->getOption('token', 'ttl');
55
56
        // new auth row
57
        $row = new Row();
58
        $row->userId = $user->id;
59
        $row->foreignKey = $user->login;
60
        $row->provider = Table::PROVIDER_TOKEN;
61
        $row->tokenType = Table::TYPE_ACCESS;
62
        $row->expired = gmdate('Y-m-d H:i:s', time() + $ttl);
63
        $row->token = bin2hex(random_bytes(32));
64
65
        $row->save();
66
67
        return $row;
68
    }
69
}
70