Passed
Pull Request — master (#255)
by
unknown
15:17 queued 11:42
created

GmailConnection::makeToken()   B

Complexity

Conditions 7
Paths 8

Size

Total Lines 27
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
cc 7
eloc 20
c 3
b 1
f 0
nc 8
nop 1
dl 0
loc 27
rs 8.6666
1
<?php
2
3
namespace Dacastro4\LaravelGmail;
4
5
use Dacastro4\LaravelGmail\Traits\Configurable;
6
use Dacastro4\LaravelGmail\Traits\HasLabels;
7
use Google_Client;
8
use Google_Service_Gmail;
9
use Google_Service_Gmail_WatchRequest;
10
use Illuminate\Container\Container;
11
use Illuminate\Support\Facades\Request;
12
use Illuminate\Support\Facades\Storage;
13
14
class GmailConnection extends Google_Client
15
{
16
	use HasLabels;
0 ignored issues
show
Bug introduced by
The trait Dacastro4\LaravelGmail\Traits\HasLabels requires the property $users_labels which is not provided by Dacastro4\LaravelGmail\GmailConnection.
Loading history...
17
	use Configurable {
0 ignored issues
show
Bug introduced by
The trait Dacastro4\LaravelGmail\Traits\Configurable requires the property $id which is not provided by Dacastro4\LaravelGmail\GmailConnection.
Loading history...
18
		__construct as configConstruct;
19
	}
20
21
22
	protected $emailAddress;
23
	protected $refreshToken;
24
	protected $app;
25
	protected $accessToken;
26
	protected $token;
27
	private $configuration;
28
	public $userId;
29
30
	public function __construct($config = null, $userId = null, array $configObject = [])
31
	{
32
		$this->app = Container::getInstance();
33
		$this->userId = $userId;
34
		if (!empty($configObject)) {
35
			$this->configObject = $configObject;
36
		}
37
		$this->configConstruct($config);
38
39
		$this->configuration = $config;
40
		parent::__construct($this->getConfigs());
41
42
		$this->configApi();
43
44
		if ($this->checkPreviouslyLoggedIn()) {
45
			$this->refreshTokenIfNeeded();
46
		}
47
	}
48
49
	/**
50
	 * Check and return true if the user has previously logged in without checking if the token needs to refresh
51
	 *
52
	 * @return bool
53
	 */
54
	public function checkPreviouslyLoggedIn()
55
	{
56
		$fileName = $this->getFileName();
57
		$file = "gmail/tokens/$fileName.json";
0 ignored issues
show
Unused Code introduced by
The assignment to $file is dead and can be removed.
Loading history...
58
		$allowJsonEncrypt = $this->_config['gmail.allow_json_encrypt'];
0 ignored issues
show
Unused Code introduced by
The assignment to $allowJsonEncrypt is dead and can be removed.
Loading history...
59
		if (!empty($this->configObject)) {
60
			return !empty($this->configObject['access_token']);
61
		}
62
		// if (Storage::disk('local')->exists($file)) {
63
		// 	if ($allowJsonEncrypt) {
64
		// 		$savedConfigToken = json_decode(decrypt(Storage::disk('local')->get($file)), true);
65
		// 	} else {
66
		// 		$savedConfigToken = json_decode(Storage::disk('local')->get($file), true);
67
		// 	}
68
69
		// 	return !empty($savedConfigToken['access_token']);
70
71
72
		// }
73
74
		return false;
75
	}
76
77
	/**
78
	 * Refresh the auth token if needed
79
	 *
80
	 * @return mixed|null
81
	 */
82
	private function refreshTokenIfNeeded()
83
	{
84
		if ($this->isAccessTokenExpired()) {
85
			$this->fetchAccessTokenWithRefreshToken($this->getRefreshToken());
86
			$token = $this->getAccessToken();
87
			$this->setBothAccessToken($token);
88
89
			return $token;
90
		}
91
92
		return $this->token;
93
	}
94
95
	/**
96
	 * Check if token exists and is expired
97
	 * Throws an AuthException when the auth file its empty or with the wrong token
98
	 *
99
	 *
100
	 * @return bool Returns True if the access_token is expired.
101
	 */
102
	public function isAccessTokenExpired()
103
	{
104
		$token = $this->getToken();
105
106
		if ($token) {
107
			$this->setAccessToken($token);
108
		}
109
110
		return parent::isAccessTokenExpired();
111
	}
112
113
	public function getToken()
114
	{
115
		return parent::getAccessToken() ?: $this->config();
116
	}
117
118
	public function setToken($token)
119
	{
120
		$this->setAccessToken($token);
121
	}
122
123
	public function getAccessToken()
124
	{
125
		$token = parent::getAccessToken() ?: $this->config();
126
127
		return $token;
128
	}
129
130
	/**
131
	 * @param array|string $token
132
	 */
133
	public function setAccessToken($token)
134
	{
135
		parent::setAccessToken($token);
136
	}
137
138
	/**
139
	 * @param $token
140
	 */
141
	public function setBothAccessToken($token)
142
	{
143
		$this->setAccessToken($token);
144
		$this->saveAccessToken($token);
145
	}
146
147
	/**
148
	 * Save the credentials in a file
149
	 *
150
	 * @param array $config
151
	 */
152
	public function saveAccessToken(array $config)
153
	{
154
		$disk = Storage::disk('local');
155
		$fileName = $this->getFileName();
156
		$file = "gmail/tokens/$fileName.json";
157
		$allowJsonEncrypt = $this->_config['gmail.allow_json_encrypt'];
158
		$config['email'] = $this->emailAddress;
159
160
		if ($disk->exists($file)) {
161
162
			if (empty($config['email'])) {
163
				if ($allowJsonEncrypt) {
164
					$savedConfigToken = json_decode(decrypt($disk->get($file)), true);
165
				} else {
166
					$savedConfigToken = json_decode($disk->get($file), true);
167
				}
168
				if (isset($savedConfigToken['email'])) {
169
					$config['email'] = $savedConfigToken['email'];
170
				}
171
			}
172
173
			$disk->delete($file);
174
		}
175
176
		if ($allowJsonEncrypt) {
177
			$disk->put($file, encrypt(json_encode($config)));
178
		} else {
179
			$disk->put($file, json_encode($config));
180
		}
181
182
	}
183
184
	/**
185
	 * @return array|string
186
	 * @throws \Exception
187
	 */
188
	public function makeToken($saveFile = true)
189
	{
190
		if (!$this->check()) {
191
			$request = Request::capture();
192
			$code = (string)$request->input('code', null);
193
			if (!is_null($code) && !empty($code)) {
0 ignored issues
show
introduced by
The condition is_null($code) is always false.
Loading history...
194
				$accessToken = $this->fetchAccessTokenWithAuthCode($code);
195
                $this->configObject = $accessToken;
196
				if ($this->haveReadScope()) {
197
					$me = $this->getProfile();
198
					if (property_exists($me, 'emailAddress')) {
199
						$this->emailAddress = $me->emailAddress;
200
						$accessToken['email'] = $me->emailAddress;
201
					}
202
				}
203
				if ($saveFile) {
204
					$this->setBothAccessToken($accessToken);
205
				} else {
206
					$this->setAccessToken($accessToken);
207
				}
208
209
				return $accessToken;
210
			} else {
211
				throw new \Exception('No access token');
212
			}
213
		} else {
214
			return $this->getAccessToken();
215
		}
216
	}
217
218
	/**
219
	 * Check
220
	 *
221
	 * @return bool
222
	 */
223
	public function check()
224
	{
225
		return !$this->isAccessTokenExpired();
226
	}
227
228
	/**
229
	 * Gets user profile from Gmail
230
	 *
231
	 * @return \Google_Service_Gmail_Profile
232
	 */
233
	public function getProfile()
234
	{
235
		$service = new Google_Service_Gmail($this);
236
237
		return $service->users->getProfile('me');
238
	}
239
240
	/**
241
	 * Revokes user's permission and logs them out
242
	 */
243
	public function logout()
244
	{
245
		$this->revokeToken();
246
	}
247
248
	/**
249
	 * Delete the credentials in a file
250
	 */
251
	public function deleteAccessToken()
252
	{
253
		$disk = Storage::disk('local');
254
		$fileName = $this->getFileName();
255
		$file = "gmail/tokens/$fileName.json";
256
257
		$allowJsonEncrypt = $this->_config['gmail.allow_json_encrypt'];
258
259
		if ($disk->exists($file)) {
260
			$disk->delete($file);
261
		}
262
263
		if ($allowJsonEncrypt) {
264
			$disk->put($file, encrypt(json_encode([])));
265
		} else {
266
			$disk->put($file, json_encode([]));
267
		}
268
269
	}
270
271
	private function haveReadScope()
272
	{
273
		$scopes = $this->getUserScopes();
274
275
		return in_array(Google_Service_Gmail::GMAIL_READONLY, $scopes);
276
	}
277
278
	/**
279
	 * users.stop receiving push notifications for the given user mailbox.
280
	 *
281
	 * @param string $userEmail Email address
282
	 * @param array $optParams
283
	 * @return \Google_Service_Gmail_Stop
0 ignored issues
show
Bug introduced by
The type Google_Service_Gmail_Stop was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
284
	 */
285
	public function stopWatch($userEmail, $optParams = [])
286
	{
287
		$service = new Google_Service_Gmail($this);
288
289
		return $service->users->stop($userEmail, $optParams);
290
	}
291
292
	/**
293
	 * Set up or update a push notification watch on the given user mailbox.
294
	 *
295
	 * @param string $userEmail Email address
296
	 * @param Google_Service_Gmail_WatchRequest $postData
297
	 *
298
	 * @return \Google_Service_Gmail_WatchResponse
299
	 */
300
	public function setWatch($userEmail, \Google_Service_Gmail_WatchRequest $postData): \Google_Service_Gmail_WatchResponse
301
	{
302
		$service = new Google_Service_Gmail($this);
303
304
		return $service->users->watch($userEmail, $postData);
305
	}
306
307
	/**
308
	 * Lists the history of all changes to the given mailbox. History results are returned in chronological order (increasing historyId).
309
	 * @param $userEmail
310
	 * @param $params
311
	 * @return \Google\Service\Gmail\ListHistoryResponse
312
	 */
313
	public function historyList($userEmail, $params)
314
	{
315
		$service = new Google_Service_Gmail($this);
316
317
		return $service->users_history->listUsersHistory($userEmail, $params);
318
	}
319
}
320