aboutsummaryrefslogtreecommitdiffstats
path: root/phpBB/phpbb/auth/provider/oauth/token_storage.php
blob: c0f585d7bb545930d7db0efa475b8ee9d4450c81 (plain)
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
<?php
/**
 *
 * This file is part of the phpBB Forum Software package.
 *
 * @copyright (c) phpBB Limited <https://www.phpbb.com>
 * @license GNU General Public License, version 2 (GPL-2.0)
 *
 * For full copyright and license information, please see
 * the docs/CREDITS.txt file.
 *
 */

namespace phpbb\auth\provider\oauth;

use OAuth\OAuth1\Token\StdOAuth1Token;
use OAuth\Common\Token\TokenInterface;
use OAuth\Common\Storage\TokenStorageInterface;
use OAuth\Common\Storage\Exception\TokenNotFoundException;
use OAuth\Common\Storage\Exception\AuthorizationStateNotFoundException;

/**
 * OAuth storage wrapper for phpBB's cache
 */
class token_storage implements TokenStorageInterface
{
	/** @var \phpbb\db\driver\driver_interface */
	protected $db;

	/** @var \phpbb\user */
	protected $user;

	/** @var string OAuth table: token storage */
	protected $oauth_token_table;

	/** @var string OAuth table: state */
	protected $oauth_state_table;

	/** @var TokenInterface OAuth token */
	protected $cachedToken;

	/** @var string OAuth state */
	protected $cachedState;

	/**
	 * Constructor.
	 *
	 * @param \phpbb\db\driver\driver_interface	$db					Database object
	 * @param \phpbb\user						$user				User object
	 * @param string							$oauth_token_table	OAuth table: token storage
	 * @param string							$oauth_state_table	OAuth table: state
	 */
	public function __construct(\phpbb\db\driver\driver_interface $db, \phpbb\user $user, $oauth_token_table, $oauth_state_table)
	{
		$this->db	= $db;
		$this->user	= $user;

		$this->oauth_token_table = $oauth_token_table;
		$this->oauth_state_table = $oauth_state_table;
	}

	/**
	 * {@inheritdoc}
	 */
	public function retrieveAccessToken($service)
	{
		$service = $this->get_service_name_for_db($service);

		if ($this->cachedToken instanceof TokenInterface)
		{
			return $this->cachedToken;
		}

		$data = [
			'user_id'	=> (int) $this->user->data['user_id'],
			'provider'	=> $service,
		];

		if ((int) $this->user->data['user_id'] === ANONYMOUS)
		{
			$data['session_id']	= $this->user->data['session_id'];
		}

		return $this->_retrieve_access_token($data);
	}

	/**
	 * {@inheritdoc}
	 */
	public function storeAccessToken($service, TokenInterface $token)
	{
		$service = $this->get_service_name_for_db($service);

		$this->cachedToken = $token;

		$data = [
			'oauth_token'	=> $this->json_encode_token($token),
		];

		$sql = 'UPDATE ' . $this->oauth_token_table . '
			SET ' . $this->db->sql_build_array('UPDATE', $data) . '
			WHERE user_id = ' . (int) $this->user->data['user_id'] . "
				AND provider = '" . $this->db->sql_escape($service) . "'";

		if ((int) $this->user->data['user_id'] === ANONYMOUS)
		{
			$sql .= " AND session_id = '" . $this->db->sql_escape($this->user->data['session_id']) . "'";
		}

		$this->db->sql_query($sql);

		if (!$this->db->sql_affectedrows())
		{
			$data = [
				'user_id'		=> (int) $this->user->data['user_id'],
				'provider'		=> $service,
				'oauth_token'	=> $this->json_encode_token($token),
				'session_id'	=> $this->user->data['session_id'],
			];

			$sql = 'INSERT INTO ' . $this->oauth_token_table . $this->db->sql_build_array('INSERT', $data);

			$this->db->sql_query($sql);
		}

		return $this;
	}

	/**
	 * {@inheritdoc}
	 */
	public function hasAccessToken($service)
	{
		$service = $this->get_service_name_for_db($service);

		if ($this->cachedToken)
		{
			return true;
		}

		$data = [
			'user_id'	=> (int) $this->user->data['user_id'],
			'provider'	=> $service,
		];

		if ((int) $this->user->data['user_id'] === ANONYMOUS)
		{
			$data['session_id']	= $this->user->data['session_id'];
		}

		return $this->has_access_token($data);
	}

	/**
	 * {@inheritdoc}
	 */
	public function clearToken($service)
	{
		$service = $this->get_service_name_for_db($service);

		$this->cachedToken = null;

		$sql = 'DELETE FROM ' . $this->oauth_token_table . '
			WHERE user_id = ' . (int) $this->user->data['user_id'] . "
				AND provider = '" . $this->db->sql_escape($service) . "'";

		if ((int) $this->user->data['user_id'] === ANONYMOUS)
		{
			$sql .= " AND session_id = '" . $this->db->sql_escape($this->user->data['session_id']) . "'";
		}

		$this->db->sql_query($sql);

		return $this;
	}

	/**
	 * {@inheritdoc}
	 */
	public function clearAllTokens()
	{
		$this->cachedToken = null;

		$sql = 'DELETE FROM ' . $this->oauth_token_table . ' 
			WHERE user_id = ' . (int) $this->user->data['user_id'];

		if ((int) $this->user->data['user_id'] === ANONYMOUS)
		{
			$sql .= " AND session_id = '" . $this->db->sql_escape($this->user->data['session_id']) . "'";
		}

		$this->db->sql_query($sql);

		return $this;
	}

	/**
	 * {@inheritdoc}
	 */
	public function storeAuthorizationState($service, $state)
	{
		$service = $this->get_service_name_for_db($service);

		$this->cachedState = $state;

		$data = [
			'user_id'		=> (int) $this->user->data['user_id'],
			'provider'		=> $service,
			'oauth_state'	=> $state,
			'session_id'	=> $this->user->data['session_id'],
		];

		$sql = 'INSERT INTO ' . $this->oauth_state_table . ' ' . $this->db->sql_build_array('INSERT', $data);
		$this->db->sql_query($sql);

		return $this;
	}

	/**
	 * {@inheritdoc}
	 */
	public function hasAuthorizationState($service)
	{
		$service = $this->get_service_name_for_db($service);

		if ($this->cachedState)
		{
			return true;
		}

		$data = [
			'user_id'	=> (int) $this->user->data['user_id'],
			'provider'	=> $service,
		];

		if ((int) $this->user->data['user_id'] === ANONYMOUS)
		{
			$data['session_id']	= $this->user->data['session_id'];
		}

		return (bool) $this->get_state_row($data);
	}

	/**
	 * {@inheritdoc}
	 */
	public function retrieveAuthorizationState($service)
	{
		$service = $this->get_service_name_for_db($service);

		if ($this->cachedState)
		{
			return $this->cachedState;
		}

		$data = [
			'user_id'	=> (int) $this->user->data['user_id'],
			'provider'	=> $service,
		];

		if ((int) $this->user->data['user_id'] === ANONYMOUS)
		{
			$data['session_id']	= $this->user->data['session_id'];
		}

		return $this->get_state_row($data);
	}

	/**
	 * {@inheritdoc}
	 */
	public function clearAuthorizationState($service)
	{
		$service = $this->get_service_name_for_db($service);

		$this->cachedState = null;

		$sql = 'DELETE FROM ' . $this->oauth_state_table . '
			WHERE user_id = ' . (int) $this->user->data['user_id'] . "
				AND provider = '" . $this->db->sql_escape($service) . "'";

		if ((int) $this->user->data['user_id'] === ANONYMOUS)
		{
			$sql .= " AND session_id = '" . $this->db->sql_escape($this->user->data['session_id']) . "'";
		}

		$this->db->sql_query($sql);

		return $this;
	}

	/**
	 * {@inheritdoc}
	 */
	public function clearAllAuthorizationStates()
	{
		$this->cachedState = null;

		$sql = 'DELETE FROM ' . $this->oauth_state_table . '
			WHERE user_id = ' . (int) $this->user->data['user_id'];

		if ((int) $this->user->data['user_id'] === ANONYMOUS)
		{
			$sql .= " AND session_id = '" . $this->db->sql_escape($this->user->data['session_id']) . "'";
		}

		$this->db->sql_query($sql);

		return $this;
	}

	/**
	 * Updates the user_id field in the database associated with the token.
	 *
	 * @param int		$user_id	The user identifier
	 * @return void
	 */
	public function set_user_id($user_id)
	{
		if (!$this->cachedToken)
		{
			return;
		}

		$data = [
			'user_id' => (int) $user_id,
		];

		$sql = 'UPDATE ' . $this->oauth_token_table . '
			SET ' . $this->db->sql_build_array('UPDATE', $data) . '
			WHERE user_id = ' . (int) $this->user->data['user_id'] . "
				AND session_id = '" . $this->db->sql_escape($this->user->data['session_id']) . "'";
		$this->db->sql_query($sql);
	}

	/**
	 * Checks to see if an access token exists solely by the session_id of the user.
	 *
	 * @param string	$service	The OAuth service name
	 * @return bool					true if the user's access token exists,
	 * 								false if the user's access token does not exist
	 */
	public function has_access_token_by_session($service)
	{
		$service = $this->get_service_name_for_db($service);

		if ($this->cachedToken)
		{
			return true;
		}

		$data = [
			'session_id'	=> $this->user->data['session_id'],
			'provider'		=> $service,
		];

		return $this->has_access_token($data);
	}

	/**
	 * Checks to see if a state exists solely by the session_id of the user.
	 *
	 * @param string	$service	The OAuth service name
	 * @return bool					true if the user's state exists,
	 * 								false if the user's state does not exist
	 */
	public function has_state_by_session($service)
	{
		$service = $this->get_service_name_for_db($service);

		if ($this->cachedState)
		{
			return true;
		}

		$data = [
			'session_id'	=> $this->user->data['session_id'],
			'provider'		=> $service,
		];

		return (bool) $this->get_state_row($data);
	}

	/**
	 * A helper function that performs the query for has access token functions.
	 *
	 * @param array		$data		The SQL WHERE data
	 * @return bool					true if the user's access token exists,
	 * 								false if the user's access token does not exist
	 */
	protected function has_access_token($data)
	{
		return (bool) $this->get_access_token_row($data);
	}

	/**
	 * A helper function that performs the query for retrieving access token functions by session.
	 * Also checks if the token is a valid token.
	 *
	 * @param string	$service	The OAuth service provider name
	 * @return TokenInterface
	 * @throws TokenNotFoundException
	 */
	public function retrieve_access_token_by_session($service)
	{
		$service = $this->get_service_name_for_db($service);

		if ($this->cachedToken instanceof TokenInterface)
		{
			return $this->cachedToken;
		}

		$data = [
			'session_id'	=> $this->user->data['session_id'],
			'provider'		=> $service,
		];

		return $this->_retrieve_access_token($data);
	}

	/**
	 * A helper function that performs the query for retrieving state functions by session.
	 *
	 * @param string	$service	The OAuth service provider name
	 * @return string				The OAuth state
	 * @throws AuthorizationStateNotFoundException
	 */
	public function retrieve_state_by_session($service)
	{
		$service = $this->get_service_name_for_db($service);

		if ($this->cachedState)
		{
			return $this->cachedState;
		}

		$data = [
			'session_id'	=> $this->user->data['session_id'],
			'provider'		=> $service,
		];

		return $this->_retrieve_state($data);
	}

	/**
	 * A helper function that performs the query for retrieve access token functions.
	 * Also checks if the token is a valid token.
	 *
	 * @param array		$data		The SQL WHERE data
	 * @return TokenInterface
	 * @throws TokenNotFoundException
	 */
	protected function _retrieve_access_token($data)
	{
		$row = $this->get_access_token_row($data);

		if (!$row)
		{
			throw new TokenNotFoundException('AUTH_PROVIDER_OAUTH_TOKEN_ERROR_NOT_STORED');
		}

		$token = $this->json_decode_token($row['oauth_token']);

		// Ensure that the token was serialized/unserialized correctly
		if (!($token instanceof TokenInterface))
		{
			$this->clearToken($data['provider']);

			throw new TokenNotFoundException('AUTH_PROVIDER_OAUTH_TOKEN_ERROR_INCORRECTLY_STORED');
		}

		$this->cachedToken = $token;

		return $token;
	}

	/**
	 * A helper function that performs the query for retrieve state functions.
	 *
	 * @param array		$data		The SQL WHERE data
	 * @return string				The OAuth state
	 * @throws AuthorizationStateNotFoundException
	 */
	protected function _retrieve_state($data)
	{
		$row = $this->get_state_row($data);

		if (!$row)
		{
			throw new AuthorizationStateNotFoundException();
		}

		$this->cachedState = $row['oauth_state'];

		return $this->cachedState;
	}

	/**
	 * A helper function that performs the query for retrieving an access token.
	 *
	 * @param array		$data		The SQL WHERE data
	 * @return array|false			array with the OAuth token row,
	 *                       		false if the token does not exist
	 */
	protected function get_access_token_row($data)
	{
		$sql = 'SELECT oauth_token 
			FROM ' . $this->oauth_token_table . '
			WHERE ' . $this->db->sql_build_array('SELECT', $data);
		$result = $this->db->sql_query($sql);
		$row = $this->db->sql_fetchrow($result);
		$this->db->sql_freeresult($result);

		return $row;
	}

	/**
	 * A helper function that performs the query for retrieving a state.
	 *
	 * @param array		$data		The SQL WHERE data
	 * @return array|false			array with the OAuth state row,
	 *                       		false if the state does not exist
	 */
	protected function get_state_row($data)
	{
		$sql = 'SELECT oauth_state 
			FROM ' . $this->oauth_state_table . '
			WHERE ' . $this->db->sql_build_array('SELECT', $data);
		$result = $this->db->sql_query($sql);
		$row = $this->db->sql_fetchrow($result);
		$this->db->sql_freeresult($result);

		return $row;
	}

	/**
	 * A helper function that JSON encodes a TokenInterface's data.
	 *
	 * @param TokenInterface	$token
	 * @return string					The json encoded TokenInterface's data
	 */
	public function json_encode_token(TokenInterface $token)
	{
		$members = [
			'accessToken'	=> $token->getAccessToken(),
			'endOfLife'		=> $token->getEndOfLife(),
			'extraParams'	=> $token->getExtraParams(),
			'refreshToken'	=> $token->getRefreshToken(),

			'token_class'	=> get_class($token),
		];

		// Handle additional data needed for OAuth1 tokens
		if ($token instanceof StdOAuth1Token)
		{
			$members['requestToken']		= $token->getRequestToken();
			$members['requestTokenSecret']	= $token->getRequestTokenSecret();
			$members['accessTokenSecret']	= $token->getAccessTokenSecret();
		}

		return json_encode($members);
	}

	/**
	 * A helper function that JSON decodes a data string and creates a TokenInterface.
	 *
	 * @param string	$json			The json encoded TokenInterface's data
	 * @return TokenInterface
	 * @throws TokenNotFoundException
	 */
	public function json_decode_token($json)
	{
		$token_data = json_decode($json, true);

		if ($token_data === null)
		{
			throw new TokenNotFoundException('AUTH_PROVIDER_OAUTH_TOKEN_ERROR_INCORRECTLY_STORED');
		}

		$token_class	= $token_data['token_class'];
		$access_token	= $token_data['accessToken'];
		$refresh_token	= $token_data['refreshToken'];
		$endOfLife		= $token_data['endOfLife'];
		$extra_params	= $token_data['extraParams'];

		/**
		 * Create the token
		 * @var TokenInterface	$token
		 */
		$token = new $token_class($access_token, $refresh_token, TokenInterface::EOL_NEVER_EXPIRES, $extra_params);
		$token->setEndOfLife($endOfLife);

		// Handle OAuth 1.0 specific elements
		if ($token instanceof StdOAuth1Token)
		{
			$token->setRequestToken($token_data['requestToken']);
			$token->setRequestTokenSecret($token_data['requestTokenSecret']);
			$token->setAccessTokenSecret($token_data['accessTokenSecret']);
		}

		return $token;
	}

	/**
	 * Returns the service name as it must be stored in the database.
	 *
	 * @param string	$provider	The OAuth provider name
	 * @return string				The OAuth service name
	 */
	protected function get_service_name_for_db($provider)
	{
		// Enforce the naming convention for oauth services
		if (strpos($provider, 'auth.provider.oauth.service.') !== 0)
		{
			$provider = 'auth.provider.oauth.service.' . strtolower($provider);
		}

		return $provider;
	}
}