This repository has been archived by the owner on Jul 31, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 61
/
auth0.module
680 lines (586 loc) · 20.3 KB
/
auth0.module
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
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
<?php
// Define some module default settings
define('AUTH0_WIDGET_CDN', 'http://cdn.auth0.com/js/lock-7.min.js');
define('AUTH_LOGIN_CSS', "#a0-widget .a0-panel {
min-width: 90%;
padding: 5%;
box-shadow: none;
-webkit-box-shadow: none;
}
#a0-widget .a0-panel {
background-color: #f6f6f2;
border-color: #f9f9f9;
}");
/**
* Implements hook_menu().
*/
function auth0_menu() {
$items = array();
// Add the callback controller.
$items['auth0/callback'] = array(
'description' => 'Callback handler from auth0',
'page callback' => 'auth0_callback',
'access callback' => TRUE,
'type' => MENU_CALLBACK,
);
$items['auth0/verify_email'] = array(
'description' => 'Verify email action',
'page callback' => 'auth0_verify_email_page',
'access callback' => TRUE,
'type' => MENU_CALLBACK,
);
$items['user/%user/auth0'] = array(
'title' => 'Auth0',
'description' => 'Verify email action',
'page callback' => 'auth0_user_info_page',
'page arguments' => array(1),
'access arguments' => array('administer users'),
'type' => MENU_LOCAL_TASK,
'weight' => 100,
);
// Add an admin configuration page.
$items['admin/config/people/auth0'] = array(
'title' => 'Auth0 Login Settings',
'description' => 'Configure your auth0 account and widget.',
'page callback' => 'drupal_get_form',
'page arguments' => array('auth0_basic_settings_form'),
'access arguments' => array('administer site configuration'),
);
// Basic configuration tab.
$items['admin/config/people/auth0/basic'] = array(
'title' => 'Basic',
'description' => 'Configure your auth0 account and widget.',
'page callback' => 'drupal_get_form',
'page arguments' => array('auth0_basic_settings_form'),
'access arguments' => array('administer site configuration'),
'type' => MENU_DEFAULT_LOCAL_TASK,
);
// Advanced configuration tab.
$items['admin/config/people/auth0/advanced'] = array(
'title' => 'Advanced',
'description' => 'Configure your auth0 account and widget.',
'page callback' => 'drupal_get_form',
'page arguments' => array('auth0_advanced_settings_form'),
'access arguments' => array('administer site configuration'),
'type' => MENU_LOCAL_TASK,
'weight' => 10
);
return $items;
}
/**
* Display auth0 info for the given user.
*/
function auth0_user_info_page($user) {
if (!auth0_check_dependencies()) {
return drupal_goto();
}
if ($object = auth0_get_auth0_object_from_drupal_uid($user->uid)) {
if (defined('JSON_PRETTY_PRINT')) {
return '<pre>' . json_encode($object, JSON_PRETTY_PRINT) . '</pre>';
}
else {
return '<pre>' . print_r($object, true) . '</pre>';
}
}
else {
return t('This user has not authenticated with Auth0');
}
}
/**
* Verify email page callback.
*/
function auth0_verify_email_page() {
if (!auth0_enabled('login')) {
return drupal_goto();
}
$token = $_REQUEST['token'];
$secret = variable_get('auth0_client_secret', '');
try {
$user = \JWT::decode($token, base64_decode(strtr($secret, '-_', '+/')), array('HS256'));
$userId = $user->sub;
$domain = variable_get('auth0_domain', '');
$url = "https://$domain/api/users/$userId/send_verification_email";
$headers = array('Authorization' => "Bearer $token");
$result = drupal_http_request($url, array('headers' => $headers, 'method' => 'POST'));
if ($result->code == 200) {
drupal_set_message(t('A verification message with further instructions has been sent to your e-mail address.'));
}
else {
drupal_set_message(t('Sorry, we could not send a verification e-mail. Please try again later.'), 'error');
}
}
catch(Exception$e) {
drupal_set_message(t('Sorry, we could not send a verification e-mail. Please try again later.'), 'error');
}
return drupal_goto();
}
/**
* User login API callback.
*
* Checks the parameters passed by redirection from Auth0 and logs or registers
* the user if the parameters are valid.
*/
function auth0_callback() {
if (!auth0_enabled('login')) {
return drupal_goto();
}
$auth0 = new \Auth0SDK\Auth0(array(
'domain' => variable_get('auth0_domain', ''),
'client_id' => variable_get('auth0_client_id', ''),
'client_secret' => variable_get('auth0_client_secret', ''),
'redirect_uri' => url('auth0/callback', array('absolute' => TRUE)),
'store' => FALSE,
));
$user_info = NULL;
try {
$user_info = $auth0->getUserInfo();
$id_token = $auth0->getIdToken();
}
catch(Exception$e) {}
// var_dump($auth0); die;
$success = FALSE;
if ($user_info) {
$success = auth0_login_auth0_user($user_info, $id_token);
}
if (!$success) {
drupal_set_message(t('There was a problem logging you in, sorry for the inconvenience.'), 'error');
}
return drupal_goto();
}
/**
* Display a message and cancel login if the user does not have a verified email.
*/
function auth0_fail_with_verify_email($id_token) {
drupal_set_message(t('Please verify your e-mail address and log in again. <a href="@url">Resend verification e-mail.</a>', array('@url' => url('auth0/verify_email', array('query' => array('token' => $id_token))))), 'warning');
return drupal_goto();
}
/**
* Log in an Auth0 authenticated user.
*/
function auth0_login_auth0_user($user_info, $id_token) {
$requires_email = variable_get('auth0_requires_email', TRUE);
$requires_verified_email = $requires_email && variable_get('user_email_verification', TRUE);
// Allow other modules to modify the Auth0 user before processing the login.
drupal_alter('auth0_user_pre_login', $user_info, $id_token);
// Check that the user account has an e-mail address if one is required.
if ($requires_email && empty($user_info['email'])) {
return drupal_set_message(
t('This account does not have an e-mail address associated with it. Please log in with a different provider.'),
'error'
);
}
// Check that the user has a verified e-mail address if that is required.
if ($requires_verified_email && isset($user_info['email']) && empty($user_info['email_verified'])) {
return auth0_fail_with_verify_email($id_token);
}
// See if there is a user in the auth0_user table with the user info client id
$uid = auth0_find_auth0_user($user_info['user_id']);
if ($uid) {
// The user exists. Update the auth0_user with the new userInfo object.
auth0_update_auth0_object($user_info);
// Log in the user.
return auth0_authenticate_user($uid);
}
else {
// If the user doesn't exist we need to either create a new one, or assign
// him to an existing one.
$isDatabaseUser = FALSE;
foreach ($user_info['identities'] as $identity) {
if ($identity['provider'] == "auth0") {
$isDatabaseUser = TRUE;
}
}
$joinUser = FALSE;
// If the user has a verified email or is a database user try to see if there is
// a user to join with. The isDatabase is because we don't want to allow database
// user creation if there is an existing one with no verified email.
if (!empty($user_info['email_verified']) || $isDatabaseUser) {
$joinUser = user_load_by_mail($user_info['email']);
}
if ($joinUser) {
// If we are here, we have a potential join user.
// Don't allow creation or assignation of user if the email is not verified, that would
// be hijacking.
if (empty($user_info['email_verified'])) {
return auth0_fail_with_verify_email($id_token);
}
$uid = $joinUser->uid;
}
else {
// If we are here, we need to create the user.
// Check drupal settings to see if new users are allowed to register.
if (variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL) == USER_REGISTER_ADMINISTRATORS_ONLY) {
return drupal_set_message(t('Only site administrators can create new user accounts.'), 'error');
}
else {
$uid = auth0_create_user_from_auth0($user_info);
}
}
auth0_insert_auth0_user($user_info, $uid);
// Log in the user.
return auth0_authenticate_user($uid);
}
return FALSE;
}
/**
* Authenticate the given user.
*
* We use our own login form because user_external_login loads the login form which
* we are modifying.
*/
function auth0_authenticate_user($uid) {
$form_state['uid'] = $uid;
user_login_submit(array(), $form_state);
return TRUE;
}
/**
* Implements hook_user().
*/
function auth0_user($op, &$edit, &$account, $category = NULL) {
if ($op == 'delete') {
return auth0_user_delete($account);
}
}
/**
* Implements hook_user_delete().
*
* Removes the user from the auth0_user table.
*/
function auth0_user_delete($account) {
db_delete('auth0_user')->condition('drupal_id', $account->uid, '=')->execute();
}
/**
* Return the uid of the user with the given Auth0 id.
*/
function auth0_find_auth0_user($id) {
$rs = db_select('auth0_user', 'a')->fields('a', array('drupal_id'))->condition('auth0_id', $id, '=')->execute()->fetchAssoc();
return empty($rs) ? FALSE : $rs['drupal_id'];
}
/**
* Return the uid of the user with the given Auth0 id.
*/
function auth0_get_auth0_object_from_drupal_uid($uid) {
$rs = db_select('auth0_user', 'a')->fields('a')->condition('drupal_id', $uid, '=')->execute()->fetch();
$rs = drupal_unpack($rs, 'auth0_object');
unset($rs->auth0_object);
return $rs;
}
/**
* Save changes to the local cache of an Auth0 user object.
*/
function auth0_update_auth0_object($user_info) {
db_update('auth0_user')->fields(array(
'auth0_object' => serialize($user_info),
))->condition('auth0_id', $user_info['user_id'], '=')->execute();
}
/**
* Create a local cached Auth0 user object.
*/
function auth0_insert_auth0_user($user_info, $uid) {
$auth0_user = array(
'auth0_id' => $user_info['user_id'],
'drupal_id' => $uid,
'auth0_object' => serialize($user_info),
);
drupal_write_record('auth0_user', $auth0_user);
}
/**
* Create a new Drupal user for an authenticated Auth0 user.
*/
function auth0_create_user_from_auth0($user_info) {
$user = new stdClass();
if (isset($user_info['email']) && !empty($user_info['email'])) {
$email = $user_info['email'];
}
else {
$email = "";
}
$user->mail = $email;
$user->init = $email;
// If the username already exists, create a new random one.
$username = $user_info['nickname'];
if (user_load_by_name($username)) {
$username .= time();
}
$user->name = $username;
$user->is_new = TRUE;
$user->status = variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL) == USER_REGISTER_VISITORS;
$user->pass = user_password();
$new_user = user_save($user);
if ($user) {
watchdog('Auth0', 'Account created for %name', array('%name' => $user->name), WATCHDOG_NOTICE, l(t('edit'), 'user/'. $user->uid .'/edit'));
}
// Notify the user if they must have approval.
if (!$user->status) {
drupal_set_message(t('Thank you for applying for an account. Your account is currently pending approval by the site administrator.'));
}
return $new_user->uid;
}
/**
* Implements hook_theme().
*
* Define the template to use for the /user action.
*/
function auth0_theme() {
return array(
'auth0_lock' => array(
'variables' => array('mode' => 'signin'),
'template' => 'auth0-lock',
),
);
}
/**
* The Auth0 basic configuration settings form callback.
*/
function auth0_basic_settings_form($form, &$form_state) {
if (!auth0_check_dependencies()) {
// Set message.
auth0_missing_dependencies_message();
}
$form['auth0_domain'] = array(
'#type' => 'textfield',
'#title' => t('Domain'),
'#default_value' => variable_get('auth0_domain', ''),
'#description' => t('Your Auth0 domain, you can see it in the auth0 dashboard.'),
'#required' => TRUE,
);
$form['auth0_client_id'] = array(
'#type' => 'textfield',
'#title' => t('Client id'),
'#default_value' => variable_get('auth0_client_id', ''),
'#description' => t('Application id, copy from the auth0 dashboard.'),
'#required' => TRUE,
);
$form['auth0_client_secret'] = array(
'#type' => 'textfield',
'#title' => t('Client secret'),
'#default_value' => variable_get('auth0_client_secret', ''),
'#description' => t('Application secret, copy from the auth0 dashboard.'),
'#required' => TRUE,
);
return system_settings_form($form);
}
/**
* The Auth0 advanced configuration settings form callback.
*/
function auth0_advanced_settings_form($form, &$form_state) {
if (!auth0_check_dependencies()) {
// Set message.
auth0_missing_dependencies_message();
}
// Text field for the e-mail subject.
$form['auth0_form_title'] = array(
'#type' => 'textfield',
'#title' => t('Form title'),
'#default_value' => variable_get('auth0_form_title', 'Sign In'),
'#description' => t('This is the title for the login widget.'),
);
$form['auth0_allow_signup'] = array(
'#type' => 'checkbox',
'#title' => t('Allow user signup'),
'#default_value' => variable_get('auth0_allow_signup', TRUE),
'#description' => t('If you have database connection you can allow users to signup using the Auth0 widget.'),
);
$form['auth0_widget_cdn'] = array(
'#type' => 'textfield',
'#title' => t('Widget CDN'),
'#default_value' => variable_get('auth0_widget_cdn', AUTH0_WIDGET_CDN),
'#description' => t('Point this to the latest widget available in the CDN.'),
);
$form['auth0_requires_email'] = array(
'#type' => 'checkbox',
'#title' => t('Require an e-mail account'),
'#default_value' => variable_get('auth0_requires_email', TRUE),
'#description' => t('Require the user to have an e-mail address to login.'),
);
$form['auth0_sso'] = array(
'#type' => 'checkbox',
'#title' => t('SSO enabled'),
'#default_value' => variable_get('auth0_sso', FALSE),
'#description' => t('Enable Auth0 <a href="@url">Single Sign On</a> for this site.', array('@url' => 'https://auth0.com/docs/sso/single-sign-on')),
);
$form['auth0_login_css'] = array(
'#type' => 'textarea',
'#title' => t('Login widget CSS'),
'#default_value' => variable_get('auth0_login_css', AUTH_LOGIN_CSS),
'#description' => t('This CSS controls the widget look and feel.'),
);
return system_settings_form($form);
}
/**
* Implements hook_user_logout().
*
* Logs the user out of Auth0 if SSO is in use.
*/
function auth0_user_logout($account) {
// If Single Sign On is enabled then log the user out from Auth0.
if (variable_get("auth0_sso", FALSE)) {
session_destroy();
$domain = check_plain(variable_get("auth0_domain", ''));
drupal_goto("https://$domain/v2/logout?returnTo=" . urlencode(url('<front>', array('absolute' => TRUE))));
}
}
/**
* Implements hook_form_alter().
*
* Replace the user login forms with the Auth0 login widget.
*/
function auth0_form_alter(&$form, $form_state, $form_id) {
if (($form_id == 'user_login_block' || $form_id == 'user_login') && auth0_enabled('login')) {
_auth0_form_replace_with_lock($form, 'signin');
}
// If Auth0 controls the user database.
if ($form_id == 'user_register_form' && auth0_enabled('signup')) {
_auth0_form_replace_with_lock($form, 'signup');
}
if ($form_id == 'user_pass' && auth0_enabled('reset')) {
_auth0_form_replace_with_lock($form, 'reset');
}
// If the settings say to remove the signup altogether.
if (!variable_get('auth0_allow_signup', '')) {
if ($form_id == 'user_register_form' || $form_id == 'user_pass') {
// @TODO: Remove the user signup option.
drupal_goto('user/login');
}
}
}
/**
* Implements hook_user_form_user_profile_form_alter().
*
* Disable email and password fields for users who have logged in with Auth0.
*/
function auth0_form_user_profile_form_alter(&$form, $form_state) {
$user = $form_state['user'];
if ($object = auth0_get_auth0_object_from_drupal_uid($user->uid)) {
// If the user has an Auth0 profile then we simply disable the password/email fields.
// If this account was created without an email address hide the field,
// otherwise show it but disable it.
if ($user->mail) {
$form['account']['mail']['#disabled'] = TRUE;
}
else {
$form['account']['mail']['#access'] = FALSE;
}
// Remove the password field.
$form['account']['pass']['#access'] = FALSE;
// If there is no way to edit the mail/pass then we don't need the current pass f
if (isset($form['account']['current_pass'])) {
$form['account']['current_pass']['#access'] = FALSE;
}
// @TODO: Reenable the password/email editing ability if the connection providor is Auth0
// This will require using the API to update the info in Auth0
}
}
/**
* Replace a form with the lock widget.
*/
function _auth0_form_replace_with_lock(&$form, $mode = 'signin') {
// Remove the old form elements.
foreach (element_children($form) as $child) {
unset($form[$child]);
}
// Add an Auth0 Lock widget.
$form['auth0'] = array(
'#type' => 'markup',
'#markup' => theme('auth0_lock', array('mode' => $mode))
);
}
/**
* Preprocess the login widget.
*/
function template_preprocess_auth0_lock(&$vars) {
$vars['sso_enabled'] = (boolean)variable_get("auth0_sso", FALSE);
$vars['domain'] = check_plain(variable_get("auth0_domain", ''));
$vars['client_id'] = check_plain(variable_get("auth0_client_id", ''));
$vars['params'] = array(
'callbackURL' => url('auth0/callback', array('absolute' => TRUE, 'query' => drupal_get_destination())),
'authParams' => array(
'state' => drupal_get_token('auth0_state'),
),
'disableSignupAction' => TRUE,
'disableResetAction' => TRUE,
'container' => 'auth0-login-form',
'sso' => $vars['sso_enabled'],
'rememberLastLogin' => $vars['sso_enabled'],
'mode' => $vars['mode'],
);
if (auth0_enabled('signup')) {
$vars['params']['disableSignupAction'] = FALSE;
}
if (auth0_enabled('reset')) {
$vars['params']['disableResetAction'] = FALSE;
}
// Generate a link to a login form to be displayed as a no-js fallback.
$query = array(
'redirect_uri' => $vars['params']['callbackURL'],
'client_id' => $vars['client_id'],
'response_type' => 'code',
'state' => $vars['params']['authParams']['state']
);
$vars['login_link'] = l(t('Log in'), 'https://' . $vars['domain'] . '/authorize', array('query' => $query));
// Add the custom css if specified.
if ($css = variable_get("auth0_login_css", AUTH_LOGIN_CSS)) {
drupal_add_css($css, array('type' => 'inline'));
}
// Add the lock.js library from the specified CDN.
drupal_add_js(filter_var(variable_get('auth0_widget_cdn', AUTH0_WIDGET_CDN), FILTER_VALIDATE_URL), 'external');
// Add the auth0 js settings.
drupal_add_js(array(
'auth0' => array(
'client_id' => $vars['client_id'],
'domain' => $vars['domain'],
'options' => $vars['params']
)), 'setting');
// Add the Drupal behavior to initialize the widget.
drupal_add_js(drupal_get_path('module', 'auth0') . '/auth0.lock.js');
}
/**
* Determine if Auth0 is enabled and can be used.
*/
function auth0_enabled($operation = '') {
if (!auth0_check_dependencies()) {
return FALSE;
}
$out = FALSE;
// Check that the module has been configured.
if (
variable_get("auth0_domain", '') &&
variable_get("auth0_client_id", '') &&
variable_get('auth0_client_secret', '')
) {
// Default to on if the module is configured.
$out = TRUE;
// See if our settings allow us to override the registration form.
if ($operation == 'signup' || $operation == 'reset') {
$out = (bool)variable_get('auth0_allow_signup', '');
}
}
// Allow other modules to override the status.
drupal_alter('auth0_enabled', $out, $operation);
return $out;
}
/**
* Check that the dependencies were autoloaded.
*/
function auth0_check_dependencies() {
if (class_exists('\Auth0SDK\Auth0')) {
return TRUE;
}
if (file_exists(DRUPAL_ROOT . '/' . drupal_get_path('module', 'auth0') . '/vendor/autoload.php')) {
require_once DRUPAL_ROOT . '/' . drupal_get_path('module', 'auth0') . '/vendor/autoload.php';
return TRUE;
}
return FALSE;
}
/**
* Set a message explaining how to install the dependencies.
*/
function auth0_missing_dependencies_message() {
drupal_set_message(
t(
'Auth0 is not fully installed. See the module\'s INSTALL.txt file for installation instructions.',
array('!url' => 'https://www.drupal.org/project/composer_manager')
),
'warning'
);
}