1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Charcoal\User; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* |
7
|
|
|
*/ |
8
|
|
|
trait AuthTokenCookieTrait |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* @return boolean |
12
|
|
|
*/ |
13
|
|
|
public function sendCookie() |
14
|
|
|
{ |
15
|
|
|
if (!$this->isEnabled()) { |
16
|
|
|
return false; |
17
|
|
|
} |
18
|
|
|
|
19
|
|
|
$metadata = $this->metadata(); |
20
|
|
|
|
21
|
|
|
$name = $metadata['tokenName']; |
22
|
|
|
$value = $this['ident'].';'.$this['token']; |
23
|
|
|
$expiry = isset($this['expiry']) ? $this['expiry']->getTimestamp() : null; |
24
|
|
|
$secure = $metadata['httpsOnly']; |
25
|
|
|
|
26
|
|
|
return setcookie($name, $value, $expiry, '', '', $secure); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @return boolean |
31
|
|
|
*/ |
32
|
|
|
public function deleteCookie() |
33
|
|
|
{ |
34
|
|
|
if (!$this->isEnabled()) { |
35
|
|
|
return false; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
$metadata = $this->metadata(); |
39
|
|
|
|
40
|
|
|
$name = $metadata['tokenName']; |
41
|
|
|
$expiry = (time() - 1000); |
42
|
|
|
$secure = $metadata['httpsOnly']; |
43
|
|
|
|
44
|
|
|
return setcookie($name, '', $expiry, '', '', $secure); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* @return array|null `[ 'ident' => '', 'token' => '' ] |
49
|
|
|
*/ |
50
|
|
|
public function getTokenDataFromCookie() |
51
|
|
|
{ |
52
|
|
|
if (!$this->isEnabled()) { |
53
|
|
|
return null; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
$metadata = $this->metadata(); |
57
|
|
|
|
58
|
|
|
$name = $metadata['tokenName']; |
59
|
|
|
if (!isset($_COOKIE[$name])) { |
60
|
|
|
return null; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
$cookie = $_COOKIE[$name]; |
64
|
|
|
$data = array_pad(explode(';', $cookie), 2, null); |
65
|
|
|
if (!isset($data[0]) || !isset($data[1])) { |
66
|
|
|
return null; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
return [ |
70
|
|
|
'ident' => $data[0], |
71
|
|
|
'token' => $data[1], |
72
|
|
|
]; |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
/** |
76
|
|
|
* Determine if authentication by token is supported. |
77
|
|
|
* |
78
|
|
|
* @return boolean |
79
|
|
|
*/ |
80
|
|
|
abstract public function isEnabled(); |
81
|
|
|
|
82
|
|
|
/** |
83
|
|
|
* @return \Charcoal\Model\MetadataInterface |
84
|
|
|
*/ |
85
|
|
|
abstract public function metadata(); |
86
|
|
|
} |
87
|
|
|
|