-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathEncryptCookieTrait.php
More file actions
64 lines (57 loc) · 1.66 KB
/
Copy pathEncryptCookieTrait.php
File metadata and controls
64 lines (57 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<?php
declare(strict_types=1);
namespace RememberMe\Authenticator;
use ArrayAccess;
use Cake\Utility\Security;
use InvalidArgumentException;
/**
* Encrypt Cookie Utility
*/
trait EncryptCookieTrait
{
/**
* decode cookie
*
* @param string $cookie from request
* @return array ['username' => ..., 'series' => ..., 'token' => ...]
* @throws \InvalidArgumentException
* @throws \JsonException
*/
public static function decodeCookie(string $cookie): array
{
$decryptedValue = Security::decrypt(base64_decode($cookie), Security::getSalt());
if ($decryptedValue === null) {
throw new InvalidArgumentException('Can\'t decrypt cookie.');
}
return json_decode($decryptedValue, true, 512, JSON_THROW_ON_ERROR);
}
/**
* encode cookie
*
* @param string $username logged in user name
* @param string $series series string
* @param string $token login token
* @return string
* @throws \JsonException
*/
public static function encryptToken(string $username, string $series, string $token): string
{
return base64_encode(
Security::encrypt(
json_encode(compact('username', 'series', 'token'), JSON_THROW_ON_ERROR),
Security::getSalt(),
),
);
}
/**
* generate token
*
* @param \ArrayAccess|array $identity logged in user info
* @return string
*/
protected static function _generateToken(ArrayAccess|array $identity): string
{
$prefix = bin2hex(Security::randomBytes(16));
return Security::hash($prefix . serialize($identity));
}
}