Completed
Push — master ( 138234...77e005 )
by Anton
12s
created

Cookie::verify()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 20
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
nc 4
dl 0
loc 20
ccs 0
cts 10
cp 0
c 0
b 0
f 0
cc 4
eloc 10
nop 1
crap 20
rs 9.2
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
use Bluz\Proxy\Response;
17
18
/**
19
 * Cookie Provider
20
 *
21
 * @package  Application\Auth
22
 * @author   Anton Shevchuk
23
 */
24
class Cookie extends AbstractProvider
25
{
26
    const PROVIDER = Table::PROVIDER_COOKIE;
27
28
    public static function authenticate($token)
29
    {
30
        $authRow = self::verify($token);
31
        $user = UsersTable::findRow($authRow->userId);
32
33
        // try to login
34
        Table::tryLogin($user);
35
    }
36
37
    public static function verify($token) : Row
38
    {
39
        /* @var Row $authRow */
40
        $authRow = Table::findRowWhere(['token' => $token, 'provider' => Table::PROVIDER_COOKIE]);
41
42
        if (!$authRow) {
43
            throw new AuthException('User can\'t login with cookies');
44
        }
45
46
        if (strtotime($authRow->expired) < time()) {
47
            self::remove($authRow->userId);
48
            throw new AuthException('Token has expired');
49
        }
50
51
        if ($authRow->token !== hash('md5', $token . $authRow->tokenSecret)) {
52
            throw new AuthException('Incorrect token');
53
        }
54
55
        return $authRow;
56
    }
57
58
    public static function create($user) : Row
59
    {
60
        // remove old Auth record
61
        self::remove($user->id);
62
63
        $ttl = Auth::getInstance()->getOption('cookie', 'ttl');
64
65
        // create new auth row
66
        $authRow = new Row();
67
        $authRow->userId = $user->id;
68
        $authRow->foreignKey = $user->login;
69
        $authRow->provider = Table::PROVIDER_COOKIE;
70
        $authRow->tokenType = Table::TYPE_ACCESS;
71
        $authRow->expired = gmdate('Y-m-d H:i:s', time() + $ttl);
72
73
        // generate secret part is not required
74
        // encrypt password and save as token
75
        $authRow->token = bin2hex(random_bytes(32));
76
        $authRow->save();
77
78
        Response::setCookie('aToken', $authRow->token, time() + $ttl);
79
80
        return $authRow;
81
    }
82
}
83