forked from CakeDC/users
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSocialAuthenticate.php
More file actions
executable file
·488 lines (425 loc) · 15.8 KB
/
Copy pathSocialAuthenticate.php
File metadata and controls
executable file
·488 lines (425 loc) · 15.8 KB
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
<?php
/**
* Copyright 2010 - 2017, Cake Development Corporation (https://www.cakedc.com)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2010 - 2017, Cake Development Corporation (https://www.cakedc.com)
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
namespace CakeDC\Users\Auth;
use CakeDC\Users\Auth\Exception\InvalidProviderException;
use CakeDC\Users\Auth\Exception\InvalidSettingsException;
use CakeDC\Users\Auth\Exception\MissingProviderConfigurationException;
use CakeDC\Users\Auth\Social\Util\SocialUtils;
use CakeDC\Users\Controller\Component\UsersAuthComponent;
use CakeDC\Users\Exception\AccountNotActiveException;
use CakeDC\Users\Exception\MissingEmailException;
use CakeDC\Users\Exception\MissingProviderException;
use CakeDC\Users\Exception\UserNotActiveException;
use CakeDC\Users\Model\Table\SocialAccountsTable;
use Cake\Auth\BaseAuthenticate;
use Cake\Controller\ComponentRegistry;
use Cake\Core\Configure;
use Cake\Event\Event;
use Cake\Event\EventDispatcherTrait;
use Cake\Event\EventManager;
use Cake\Http\Response;
use Cake\Http\ServerRequest;
use Cake\Log\LogTrait;
use Cake\ORM\TableRegistry;
use Cake\Utility\Hash;
use League\OAuth2\Client\Provider\AbstractProvider;
/**
* Class SocialAuthenticate
*/
class SocialAuthenticate extends BaseAuthenticate
{
use EventDispatcherTrait;
use LogTrait;
/**
* Instance of OAuth2 provider.
*
* @var \League\OAuth2\Client\Provider\AbstractProvider
*/
protected $_provider;
/**
* Constructor
*
* @param \Cake\Controller\ComponentRegistry $registry The Component registry used on this request.
* @param array $config Array of config to use.
* @throws \Exception
*/
public function __construct(ComponentRegistry $registry, array $config = [])
{
$oauthConfig = Configure::read('OAuth');
$enabledNoOAuth2Provider = $this->_isProviderEnabled($oauthConfig['providers']['twitter']);
//We unset twitter from providers to exclude from OAuth2 config
unset($oauthConfig['providers']['twitter']);
$providers = [];
foreach ($oauthConfig['providers'] as $provider => $options) {
if ($this->_isProviderEnabled($options)) {
$providers[$provider] = $options;
}
}
$oauthConfig['providers'] = $providers;
Configure::write('OAuth2', $oauthConfig);
$config = $this->normalizeConfig(Hash::merge($config, $oauthConfig), $enabledNoOAuth2Provider);
parent::__construct($registry, $config);
}
/**
* Normalizes providers' configuration.
*
* @param array $config Array of config to normalize.
* @param bool $enabledNoOAuth2Provider True when any noOAuth2 provider is enabled
* @return array
* @throws \Exception
*/
public function normalizeConfig(array $config, $enabledNoOAuth2Provider = false)
{
$config = Hash::merge((array)Configure::read('OAuth2'), $config);
if (empty($config['providers']) && !$enabledNoOAuth2Provider) {
throw new MissingProviderConfigurationException();
}
if (!empty($config['providers'])) {
array_walk($config['providers'], [$this, '_normalizeConfig'], $config);
}
return $config;
}
/**
* Callback to loop through config values.
*
* @param array $config Configuration.
* @param string $alias Provider's alias (key) in configuration.
* @param array $parent Parent configuration.
* @return void
*/
protected function _normalizeConfig(&$config, $alias, $parent)
{
unset($parent['providers']);
$defaults = [
'className' => null,
'authParams' => [],
'options' => [],
'collaborators' => [],
'mapFields' => [],
] + $parent + $this->_defaultConfig;
$config = array_intersect_key($config, $defaults);
$config += $defaults;
array_walk($config, [$this, '_validateConfig']);
foreach (['options', 'collaborators'] as $key) {
if (empty($parent[$key]) || empty($config[$key])) {
continue;
}
$config[$key] = array_merge($parent[$key], $config[$key]);
}
}
/**
* Validates the configuration.
*
* @param mixed $value Value.
* @param string $key Key.
* @return void
* @throws \CakeDC\Users\Auth\Exception\InvalidProviderException
* @throws \CakeDC\Users\Auth\Exception\InvalidSettingsException
*/
protected function _validateConfig(&$value, $key)
{
if ($key === 'className' && !class_exists($value)) {
throw new InvalidProviderException([$value]);
} elseif (!is_array($value) && in_array($key, ['options', 'collaborators'])) {
throw new InvalidSettingsException([$key]);
}
}
/**
* Get the controller associated with the collection.
*
* @return \Cake\Controller\Controller Controller instance
*/
protected function _getController()
{
return $this->_registry->getController();
}
/**
* Returns when a provider has been enabled.
*
* @param array $options array of options by provider
* @return bool
*/
protected function _isProviderEnabled($options)
{
return !empty($options['options']['redirectUri']) && !empty($options['options']['clientId']) &&
!empty($options['options']['clientSecret']);
}
/**
* Get a user based on information in the request.
*
* @param \Cake\Http\ServerRequest $request Request object.
* @param \Cake\Http\Response $response Response object.
* @return bool
* @throws \RuntimeException If the `CakeDC/Users/OAuth2.newUser` event is missing or returns empty.
*/
public function authenticate(ServerRequest $request, Response $response)
{
return $this->getUser($request);
}
/**
* Authenticates with OAuth2 provider by getting an access token and
* retrieving the authorized user's profile data.
*
* @param \Cake\Http\ServerRequest $request Request object.
* @return array|bool
*/
protected function _authenticate(ServerRequest $request)
{
if (!$this->_validate($request)) {
return false;
}
$provider = $this->provider($request);
$code = $request->getQuery('code');
try {
$token = $provider->getAccessToken('authorization_code', compact('code'));
return compact('token') + $provider->getResourceOwner($token)->toArray();
} catch (\Exception $e) {
$message = sprintf(
"Error getting an access token / retrieving the authorized user's profile data. Error message: %s %s",
$e->getMessage(),
$e
);
$this->log($message);
return false;
}
}
/**
* Validates OAuth2 request.
*
* @param \Cake\Http\ServerRequest $request Request object.
* @return bool
*/
protected function _validate(ServerRequest $request)
{
if (!array_key_exists('code', $request->getQueryParams()) || !$this->provider($request)) {
return false;
}
$session = $request->getSession();
$sessionKey = 'oauth2state';
$state = $request->getQuery('state');
if ($this->getConfig('options.state') &&
(!$state || $state !== $session->read($sessionKey))) {
$session->delete($sessionKey);
return false;
}
return true;
}
/**
* Maps raw provider's user profile data to local user's data schema.
*
* @param array $data Raw user data.
* @return array
*/
protected function _map($data)
{
if (!$map = $this->getConfig('mapFields')) {
return $data;
}
foreach ($map as $dst => $src) {
$data[$dst] = $data[$src];
unset($data[$src]);
}
return $data;
}
/**
* Handles unauthenticated access attempts. Will automatically forward to the
* requested provider's authorization URL to let the user grant access to the
* application.
*
* @param \Cake\Http\ServerRequest $request Request object.
* @param \Cake\Http\Response $response Response object.
* @return \Cake\Http\Response|null
*/
public function unauthenticated(ServerRequest $request, Response $response)
{
$provider = $this->provider($request);
if (empty($provider) || !empty($request->getQuery('code'))) {
return null;
}
if ($this->getConfig('options.state')) {
$request->getSession()->write('oauth2state', $provider->getState());
}
$authParams = $this->getConfig(sprintf('providers.%s.authParams', $request->getParam('provider')), []);
$location = $provider->getAuthorizationUrl($authParams);
$this->dispatchEvent(UsersAuthComponent::EVENT_BEFORE_SOCIAL_LOGIN_REDIRECT, compact('location', 'request'));
return $response->withLocation($location);
}
/**
* Returns the `$request`-ed provider.
*
* @param \Cake\Http\ServerRequest $request Current HTTP request.
* @return \League\Oauth2\Client\Provider\GenericProvider|false
*/
public function provider(ServerRequest $request)
{
if (!$alias = $request->getParam('provider')) {
return false;
}
if (empty($this->_provider)) {
$this->_provider = $this->_getProvider($alias);
}
return $this->_provider;
}
/**
* Instantiates provider object.
*
* @param string $alias of the provider.
* @return \League\Oauth2\Client\Provider\GenericProvider
*/
protected function _getProvider($alias)
{
if (!$config = $this->getConfig('providers.' . $alias)) {
return false;
}
$this->setConfig($config);
if (is_object($config) && $config instanceof AbstractProvider) {
return $config;
}
$class = $config['className'];
return new $class($config['options'], $config['collaborators']);
}
/**
* Find or create local user
*
* @param array $data data
* @return array|bool|mixed
* @throws MissingEmailException
*/
protected function _touch(array $data)
{
try {
if (empty($data['provider']) && !empty($this->_provider)) {
$data['provider'] = SocialUtils::getProvider($this->_provider);
}
$user = $this->_socialLogin($data);
} catch (UserNotActiveException $ex) {
$exception = $ex;
} catch (AccountNotActiveException $ex) {
$exception = $ex;
} catch (MissingEmailException $ex) {
$exception = $ex;
}
if (!empty($exception)) {
$args = ['exception' => $exception, 'rawData' => $data];
$this->_getController()->dispatchEvent(UsersAuthComponent::EVENT_FAILED_SOCIAL_LOGIN, $args);
if (method_exists($this->_getController(), 'failedSocialLogin')) {
$this->_getController()->failedSocialLogin($exception, $data, true);
}
return false;
}
// If new SocialAccount was created $user is returned containing it
if ($user->get('social_accounts')) {
$this->_getController()->dispatchEvent(UsersAuthComponent::EVENT_AFTER_REGISTER, compact('user'));
}
return $this->_findUser($user->get(Configure::read('Auth.authenticate.Form.fields.username', 'username')));
}
/**
* Get a user based on information in the request.
*
* @param \Cake\Http\ServerRequest $request Request object.
* @return mixed Either false or an array of user information
* @throws \RuntimeException If the `CakeDC/Users/OAuth2.newUser` event is missing or returns empty.
*/
public function getUser(ServerRequest $request)
{
$data = $request->getSession()->read(Configure::read('Users.Key.Session.social'));
$requestDataEmail = $request->getData('email');
if (!empty($data) && empty($data['uid']) && (!empty($data['email']) || !empty($requestDataEmail))) {
if (!empty($requestDataEmail)) {
$data['email'] = $requestDataEmail;
}
$user = $data;
$request->getSession()->delete(Configure::read('Users.Key.Session.social'));
} else {
if (empty($data) && !$rawData = $this->_authenticate($request)) {
return false;
}
if (empty($rawData)) {
$rawData = $data;
}
$provider = $this->_getProviderName($request);
try {
$user = $this->_mapUser($provider, $rawData);
if ($this->_getController()->components()->has('Auth')) {
$this->_getController()->Auth->setConfig('authError', false);
}
} catch (MissingProviderException $ex) {
$request->getSession()->delete(Configure::read('Users.Key.Session.social'));
throw $ex;
}
if ($user['provider'] === SocialAccountsTable::PROVIDER_TWITTER) {
$request->getSession()->write(Configure::read('Users.Key.Session.social'), $user);
}
}
if (!$user || !$this->getConfig('userModel')) {
return false;
}
if (!$result = $this->_touch($user)) {
return false;
}
if ($request->getSession()->check(Configure::read('Users.Key.Session.social'))) {
$request->getSession()->delete(Configure::read('Users.Key.Session.social'));
}
$request->getSession()->write('Users.successSocialLogin', true);
return $result;
}
/**
* Get the provider name based on the request or on the provider set.
*
* @param \Cake\Http\ServerRequest $request Request object.
* @return mixed Either false or an array of user information
*/
protected function _getProviderName($request = null)
{
$provider = false;
if (!empty($request->getParam('provider'))) {
$provider = ucfirst($request->getParam('provider'));
} elseif (!is_null($this->_provider)) {
$provider = SocialUtils::getProvider($this->_provider);
}
return $provider;
}
/**
* Get the provider name based on the request or on the provider set.
*
* @param string $provider Provider name.
* @param array $data User data
* @throws MissingProviderException
* @return mixed Either false or an array of user information
*/
protected function _mapUser($provider, $data)
{
if (empty($provider)) {
throw new MissingProviderException(__d('CakeDC/Users', "Provider cannot be empty"));
}
$providerMapperClass = $this->getConfig('providers.' . strtolower($provider) . '.options.mapper') ?: "\\CakeDC\\Users\\Auth\\Social\\Mapper\\$provider";
$providerMapper = new $providerMapperClass($data);
$user = $providerMapper();
$user['provider'] = $provider;
return $user;
}
/**
* @param mixed $data data
* @return mixed
*/
protected function _socialLogin($data)
{
$options = [
'use_email' => Configure::read('Users.Email.required'),
'validate_email' => Configure::read('Users.Email.validate'),
'token_expiration' => Configure::read('Users.Token.expiration')
];
$userModel = Configure::read('Users.table');
$User = TableRegistry::getTableLocator()->get($userModel);
$user = $User->socialLogin($data, $options);
return $user;
}
}