1
|
|
|
<?php |
2
|
|
|
namespace VideoPublisher\Security; |
3
|
|
|
|
4
|
|
|
use VideoPublisher\Exception\TokenCacheNotWritableException; |
5
|
|
|
use VideoPublisher\Exception\TokenNotFoundException; |
6
|
|
|
|
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Class TokenVault. |
10
|
|
|
* |
11
|
|
|
* @author Bart Malestein <[email protected]> |
12
|
|
|
*/ |
13
|
|
|
class TokenVault |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* @var string |
17
|
|
|
*/ |
18
|
|
|
private $tokenCacheLocation; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* TokenVault constructor. |
22
|
|
|
* @param $tokenCacheLocation |
23
|
|
|
* @throws TokenCacheNotWritableException |
24
|
|
|
*/ |
25
|
|
|
public function __construct($tokenCacheLocation) |
26
|
|
|
{ |
27
|
|
|
$this->tokenCacheLocation = rtrim($tokenCacheLocation, '/') . '/'; |
28
|
|
|
if (false === is_writable($tokenCacheLocation)) { |
29
|
|
|
throw new TokenCacheNotWritableException('token cache location isn\'t writable: ' . $tokenCacheLocation); |
30
|
|
|
} |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* @param string $consumerKey |
35
|
|
|
* @param Token $token |
36
|
|
|
*/ |
37
|
|
|
public function addToken($consumerKey, Token $token) |
38
|
|
|
{ |
39
|
|
|
file_put_contents($this->getPathForToken($consumerKey), $token->getValue()); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* @param string $consumerKey |
44
|
|
|
*/ |
45
|
|
|
public function removeToken($consumerKey) |
46
|
|
|
{ |
47
|
|
|
$location = $this->getPathForToken($consumerKey); |
48
|
|
|
if (file_exists($location)) { |
49
|
|
|
unlink($location); |
50
|
|
|
} |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* @param string $consumerKey |
55
|
|
|
* @return bool |
56
|
|
|
*/ |
57
|
|
|
public function hasToken($consumerKey) |
58
|
|
|
{ |
59
|
|
|
$location = $this->getPathForToken($consumerKey); |
60
|
|
|
|
61
|
|
|
return file_exists($location); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
/** |
65
|
|
|
* @param string $consumerKey |
66
|
|
|
* @return Token |
67
|
|
|
* @throws TokenNotFoundException |
68
|
|
|
*/ |
69
|
|
|
public function getToken($consumerKey) |
70
|
|
|
{ |
71
|
|
|
$location = $this->getPathForToken($consumerKey); |
72
|
|
|
if (false === file_exists($location)) { |
73
|
|
|
throw new TokenNotFoundException(); |
74
|
|
|
} |
75
|
|
|
return new Token(file_get_contents($location)); |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
/** |
79
|
|
|
* @param string $consumerKey |
80
|
|
|
* @return string |
81
|
|
|
*/ |
82
|
|
|
public function getPathForToken($consumerKey) |
83
|
|
|
{ |
84
|
|
|
return $this->tokenCacheLocation . sha1($consumerKey); |
85
|
|
|
} |
86
|
|
|
} |