-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathToken.php
93 lines (85 loc) · 2.22 KB
/
Token.php
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<?php
/**
* Description of Token
*
* @author ondrej-maxa
*/
class Token
{
/**
* Your google drive client.
*
* @var Google_Client
*/
private $client;
public function __construct(Google_Client $client)
{
$this->client = $client;
if (!is_null(filter_input(INPUT_COOKIE, 'token'))) {
// TOKEN EXISTS
$this->get();
}
if ($this->client->isAccessTokenExpired()) {
if ($this->client->getRefreshToken()) {
// TOKEN IS EXPIRED
$this->refresh();
} else {
// TOKEN IS NOT CREATED YET
$this->create();
}
}
}
/**
* Resets token.
*/
public function reset()
{
$this->setCookie(true);
}
/**
* Gets token.
* Called only if token exists.
*/
private function get()
{
$accessToken = json_decode(filter_input(INPUT_COOKIE, 'token'), true);
$this->client->setAccessToken($accessToken);
}
/**
* Refreshes token.
* Called only if token doesn't exist but refresh token does.
*/
private function refresh()
{
$this->client->fetchAccessTokenWithRefreshToken($this->client->getRefreshToken());
$this->setCookie();
}
/**
* Creates new token.
*/
private function create()
{
if (!is_null(filter_input(INPUT_GET, 'code'))) {
$this->client->authenticate(filter_input(INPUT_GET, 'code'));
$this->setCookie();
$redirectUri = json_decode(file_get_contents($this->pathToCredentials),
true)["web"]["redirect_uris"][0];
header("Location: $redirectUri?login");
} else {
$authUrl = $this->client->createAuthUrl();
header('Location: '.filter_var($authUrl, FILTER_SANITIZE_URL));
}
}
/**
* Stores or deletes token from Cookie
*
* @param bool $delete If the cookie should be unset.
*/
private function setCookie($delete = false)
{
$time = $delete ? time() - 3600 : time() + 3600;
setcookie(
"token", json_encode($this->client->getAccessToken()), $time
);
}
}