Completed
Push — master ( 889011...d668d0 )
by Razon
02:49
created

SessionFactory::generateToken()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 1
ccs 2
cts 2
cp 1
crap 1
1
<?php
2
namespace App\Factory;
3
4
use App\Model\Session;
5
use Ramsey\Uuid\Uuid;
6
use yii\web\Request;
7
use Yii;
8
9
class SessionFactory
10
{
11
    /**
12
     * Creates a session from request.
13
     *
14
     * @param int     $userId          user ID.
15
     * @param int     $duration        session duration
16
     * @param int     $refreshDuration session fresh duration
17
     * @param Request $request
18
     *
19
     * @return Session
20
     */
21 1
    public static function createByRequest(int $userId, int $duration, int $refeshDuration, Request $request): Session
22
    {
23 1
        $ip = $request->getUserIP();
24 1
        $userAgent = mb_substr($request->getUserAgent(), 0, 255);
25 1
        $token = static::generateToken($userId);
26 1
        $refeshToken = static::generateRefreshToken($userId);
27 1
        $now = time();
28 1
        return new Session([
29 1
            'id' => Uuid::uuid4()->toString(),
30 1
            'token' => $token,
31 1
            'refresh_token' => $refeshToken,
32 1
            'user_id' => $userId,
33 1
            'expire_time' => $now + $duration,
34 1
            'refresh_token_expire_time' => $now + $refeshDuration,
35 1
            'ip_address' => $ip,
36 1
            'user_agent' => $userAgent,
37
        ]);
38
    }
39
40
    /**
41
     * Generates access token.
42
     *
43
     * @param int $userId user ID.
44
     *
45
     * @return string
46
     */
47 1
    public static function generateToken(int $userId): string
48
    {
49 1
        return ($userId % 10) . Yii::$app->getSecurity()->generateRandomString(31);
50
    }
51
52
    /**
53
     * Generates refresh token.
54
     *
55
     * @param int $userId user ID.
56
     *
57
     * @return string
58
     */
59 1
    public static function generateRefreshToken(int $userId): string
60
    {
61 1
        return ($userId % 10) . Yii::$app->getSecurity()->generateRandomString(63);
62
    }
63
}
64