/
GenericOauthTypeController.php
583 lines (483 loc) · 16.3 KB
/
GenericOauthTypeController.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
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
<?php
namespace Concrete\Core\Authentication\Type\OAuth;
use Concrete\Core\Authentication\AuthenticationType;
use Concrete\Core\Authentication\AuthenticationTypeController;
use Concrete\Core\Database\Connection\Connection;
use Concrete\Core\User\User;
use OAuth\Common\Exception\Exception;
use OAuth\Common\Service\AbstractService;
use OAuth\Common\Token\TokenInterface;
use OAuth\UserData\Extractor\Extractor;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;
use Concrete\Core\Validation\CSRF\Token;
abstract class GenericOauthTypeController extends AuthenticationTypeController
{
public $apiMethods = ['handle_error', 'handle_success', 'handle_register'];
/**
* @var \OAuth\Common\Service\AbstractService
*/
protected $service;
/**
* @var Extractor
*/
protected $extractor;
/**
* @var \OAuth\Common\Token\TokenInterface
*/
protected $token;
/* @var string $username */
protected $username;
/* @var string $email */
protected $email;
/* @var string $firstName */
protected $firstName;
/* @var string $lastName */
protected $lastName;
/* @var string $fullName */
protected $fullName;
/** @var BindingService|null The service used to manage oauth user bindings */
protected $bindingService;
public function __construct(AuthenticationType $type = null)
{
parent::__construct($type);
$manager = $this->app->make(Connection::class)->getSchemaManager();
if (!$manager->tablesExist('OauthUserMap')) {
$schema = new \Doctrine\DBAL\Schema\Schema();
$table = $schema->createTable('OauthUserMap');
$table->addColumn('user_id', 'integer', ['unsigned' => true]);
$table->addColumn('binding', 'string', ['length' => 255]);
$table->addColumn('namespace', 'string', ['length' => 255]);
$table->setPrimaryKey(['user_id', 'namespace']);
$table->addUniqueIndex(['binding', 'namespace'], 'oauth_binding');
$manager->createTable($table);
}
}
/**
* @return array
*/
public function getAdditionalRequestParameters()
{
return [];
}
public function handle_error($error = false)
{
if (!$error) {
$error = $this->app->make('session')->get('oauth_last_error');
$this->app->make('session')->set('oauth_last_error', null);
}
if (!$error) {
$error = 'An unexpected error occurred.';
}
$this->set('error', $error);
}
public function showError($error = null)
{
if ($error) {
$this->markError($error);
}
id(new \RedirectResponse(\URL::to('/login/callback/' . $this->getHandle() . '/handle_error')))->send();
}
public function markError($error)
{
$this->app->make('session')->set('oauth_last_error', $error);
}
public function handle_success($message = false)
{
if (!$message) {
$message = $this->app->make('session')->get('oauth_last_message');
$this->app->make('session')->set('oauth_last_message', null);
}
if ($message) {
$this->set('message', $message);
}
}
public function showSuccess($message = null)
{
if ($message) {
$this->markSuccess($message);
}
id(new \RedirectResponse(\URL::to('/login/callback/' . $this->getHandle() . '/handle_success')))->send();
}
public function markSuccess($message)
{
$this->app->make('session')->set('oauth_last_message', $message);
}
/**
* Empty because we don't use the authenticate entry point.
*/
public function authenticate()
{
}
/**
* Create a cookie hash to identify the user indefinitely.
*
* @param \User $u
*
* @return string Unique hash to be used to verify the users identity
*/
public function buildHash(User $u)
{
return '';
}
/**
* Hash authentication disabled for oauth.
*
* @param User $u object requesting verification
* @param string $hash
*
* @return bool returns true if the hash is valid, false if not
*/
public function verifyHash(User $u, $hash)
{
return false;
}
/**
* @return \OAuth\Common\Token\TokenInterface
*/
public function getToken()
{
return $this->token;
}
/**
* @param \OAuth\Common\Token\TokenInterface $token
*/
public function setToken(TokenInterface $token)
{
$this->token = $token;
}
/**
* We now check if the user allows access to email address as twitter does not provide this and users can deny access to on facebook).
*
* @return null|\User
*
* @throws Exception
*/
protected function attemptAuthentication()
{
$extractor = $this->getExtractor();
if (!$this->isValid()) {
throw new Exception(
'Invalid account, user cannot be logged in.');
}
$user_id = $this->getBoundUserID($extractor->getUniqueId());
if ($user_id && $user_id > 0) {
$user = User::loginByUserID($user_id);
if ($user && !$user->isError()) {
$this->app->make('session')->migrate();
return $user;
}
}
if ($extractor->supportsEmail() && $user = \UserInfo::getByEmail($extractor->getEmail())) {
if ($user && !$user->isError()) {
throw new Exception('A user account already exists for this email, please log in and attach from your account page.');
}
}
if ($this->supportsRegistration()) {
if ($extractor->getEmail() === null || empty($extractor->getEmail())) {
/** @var FlashBagInterface $flashbag */
$flashbag = $this->app->make('session')->getFlashBag();
if ($this->supportsFullName()) {
$flashbag->set('fullName', $this->getFullName());
} else {
$flashbag->set('firstName', $this->getFirstName());
$flashbag->set('lastName', $this->getLastName());
}
$flashbag->set('username', $this->getUsername());
$flashbag->set('token', $this->getToken());
$response = \Redirect::to('/login/callback/' . $this->getHandle() . '/handle_register/', id(new Token())->generate($this->getHandle() . '_register'));
$response->send();
exit;
} else {
$user = $this->createUser();
return $user;
}
}
return null;
}
public function handle_register($token = null)
{
/** @var FlashBagInterface $flashbag */
$flashbag = $this->app->make('session')->getFlashBag();
if ($this->supportsFullName()) {
$this->fullName = array_shift($flashbag->peek('fullName'));
} else {
$this->firstName = array_shift($flashbag->peek('firstName'));
$this->lastName = array_shift($flashbag->peek('lastName'));
}
$this->username = array_shift($flashbag->peek('username'));
$this->token = array_shift($flashbag->peek('token'));
$token_helper = new Token();
if (!$token_helper->validate($this->getHandle().'_register', $token) && !$token_helper->validate($this->getHandle().'_register') ||
!$this->token) {
$this->redirect('/login/');
exit;
}
if (\Request::request('uEmail', false)) {
$this->email = \Request::request('uEmail');
$user = $this->createUser();
if ($user && !$user->isError()) {
return $this->completeAuthentication($user);
}
}
if ($this->supportsFullName()) {
$this->set('fullName', $this->fullName);
}
$this->set('token', $token_helper);
$this->set('username', $this->username);
$this->set('show_email', true);
}
/**
* @return \OAuth\UserData\Extractor\ExtractorInterface
*
* @throws \OAuth\UserData\Exception\UndefinedExtractorException
*/
public function getExtractor($new = false)
{
if ($new || !$this->extractor) {
$this->extractor = $this->app->make('oauth_extractor', [$this->getService()]);
}
return $this->extractor;
}
public function form()
{
$this->set('user', $this->app->make(User::class));
$this->set('authenticationType', $this->getAuthenticationType());
}
/**
* @return AbstractService
*/
abstract public function getService();
protected function isValid()
{
return $this->extractor->supportsUniqueId();
}
/**
* @param $binding
*
* @return int|bool False if no user id is bound
*
* @throws \Doctrine\DBAL\DBALException
*/
public function getBoundUserID($binding)
{
$id = $this->getBindingService()->getBoundUserId($binding, $this->getHandle());
return $id === null ? false : $id;
}
/**
* Whether or not we will attempt to register the user.
*
* @return bool
*/
abstract public function supportsRegistration();
/**
* Whether or not we will attempt to register the user.
*
* @return bool
*/
abstract public function registrationGroupID();
protected function createUser()
{
// Make sure that this extractor supports everything we need.
if (!$this->supportsEmail() && $this->supportsUniqueId()) {
throw new Exception('Email and unique ID support are required for user creation.');
}
// Make sure that email is verified if the extractor supports it.
if ($this->supportsVerifiedEmail() && !$this->isEmailVerified()) {
throw new Exception('Please verify your email with this service before attempting to log in.');
}
$email = $this->getEmail();
if (\UserInfo::getByEmail($email)) {
throw new Exception('Email is already in use.');
}
$first_name = '';
$last_name = '';
$name_support = [
'full' => $this->supportsFullName(),
'first' => $this->supportsFirstName(),
'last' => $this->supportsLastName(),
];
if ($name_support['first'] && $name_support['last']) {
$first_name = $this->getFirstName();
$last_name = $this->getLastName();
} elseif ($name_support['full']) {
$reversed_full_name = strrev($this->getFullName());
list($reversed_last_name, $reversed_first_name) = explode(' ', $reversed_full_name, 2);
$first_name = strrev($reversed_first_name);
$last_name = strrev($reversed_last_name);
}
$userRegistration = $this->app->make('user/registration');
$username = null;
if ($this->supportsUsername()) {
$username = $this->getUsername();
}
$username = $userRegistration->getNewUsernameFromUserDetails($email, $username, $first_name, $last_name);
$data = [];
$data['uName'] = $username;
$data['uPassword'] = \Illuminate\Support\Str::random(256);
$data['uEmail'] = $email;
$data['uIsValidated'] = 1;
$user_info = $userRegistration->create($data);
if (!$user_info) {
throw new Exception('Unable to create new account.');
}
if ($group_id = intval($this->registrationGroupID(), 10)) {
$group = \Group::getByID($group_id);
if ($group && is_object($group) && !$group->isError()) {
$user = User::getByUserID($user_info->getUserID());
$user->enterGroup($group);
}
}
$attribs = \UserAttributeKey::getRegistrationList();
if (!empty($attribs)) {
$user_info->saveUserAttributesDefault($attribs);
}
$key = \UserAttributeKey::getByHandle('first_name');
if ($key) {
$user_info->setAttribute($key, $first_name);
}
$key = \UserAttributeKey::getByHandle('last_name');
if ($key) {
$user_info->setAttribute($key, $last_name);
}
User::loginByUserID($user_info->getUserID());
$this->bindUser($user = User::getByUserID($user_info->getUserID()), $this->getUniqueId());
return $user;
}
public function supportsEmail()
{
return $this->getExtractor()->supportsEmail();
}
public function supportsUniqueId()
{
return $this->getExtractor()->supportsUniqueId();
}
public function supportsVerifiedEmail()
{
return $this->getExtractor()->supportsVerifiedEmail();
}
public function isEmailVerified()
{
return $this->getExtractor()->isEmailVerified();
}
public function getEmail()
{
if ($this->email) {
return $this->email;
}
return $this->getExtractor()->getEmail();
}
public function supportsFullName()
{
return $this->getExtractor()->supportsFullName();
}
public function supportsFirstName()
{
return $this->getExtractor()->supportsFirstName();
}
public function supportsLastName()
{
return $this->getExtractor()->supportsLastName();
}
public function getFirstName()
{
return $this->getExtractor()->getFirstName();
}
public function getLastName()
{
return $this->getExtractor()->getLastName();
}
public function getFullName()
{
return $this->getExtractor()->getFullName();
}
public function supportsUsername()
{
return $this->getExtractor()->supportsUsername();
}
public function getUsername()
{
return $this->getExtractor()->getUsername();
}
/**
* @param User $user
* @param $binding
*
* @return int|null
*/
public function bindUser(User $user, $binding)
{
return $this->bindUserID(intval($user->getUserID(), 10), $binding);
}
/**
* @param $user_id
* @param $binding
*
* @return int|null
*/
public function bindUserID($user_id, $binding)
{
if (!$binding || !$user_id) {
return null;
}
if ($this->getBindingService()->bindUserId($user_id, $binding, $this->getHandle())) {
return 1;
}
return null;
}
/**
* Get the binding associated to a specific user.
*
* @param \Concrete\Core\User\User|\Concrete\Core\User\UserInfo|\Concrete\Core\Entity\User\User|int $user
*
* @return string|null
*/
public function getBindingForUser($user)
{
if (is_object($user)) {
$userID = $user->getUserID();
} else {
$userID = (int) $user;
}
return $this->getBindingService()->getUserBinding($userID, $this->getHandle());
}
public function getUniqueId()
{
return $this->getExtractor()->getUniqueId();
}
abstract public function handle_authentication_attempt();
abstract public function handle_authentication_callback();
abstract public function handle_attach_attempt();
abstract public function handle_attach_callback();
public function handle_detach_attempt()
{
$user = $this->app->make(User::class);
if (!$user->isRegistered()) {
$response = new RedirectResponse(\URL::to('/login'), 302);
$response->send();
exit;
}
$uID = $user->getUserID();
$namespace = $this->getHandle();
$binding = $this->getBindingForUser($user);
$this->getService()->request('/' . $binding . '/permissions', 'DELETE');
try {
$this->getBindingService()->clearBinding($uID, $namespace, $binding);
$this->showSuccess(t('Successfully detached.'));
exit;
} catch (\Exception $e) {
$this->logger->notice(t('Detach Error %s', $e->getMessage()));
$this->showError(t('Unable to detach account.'));
exit;
}
}
/**
* @return BindingService
*/
protected function getBindingService()
{
if (!$this->bindingService) {
$this->bindingService = $this->app->make(BindingService::class);
}
return $this->bindingService;
}
}