forked from auth0/wordpress
-
Notifications
You must be signed in to change notification settings - Fork 0
/
WP_Auth0.php
453 lines (368 loc) · 15.3 KB
/
WP_Auth0.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
<?php
/**
* Plugin Name: Wordpress Auth0 Integration
* Description: Implements the Auth0 Single Sign On solution into Wordpress
* Version: 1.0.1
* Author: 1337 ApS
* Author URI: http://1337.dk
*/
define('WPA0_PLUGIN_FILE', __FILE__);
define('WPA0_PLUGIN_DIR', trailingslashit(plugin_dir_path(__FILE__)));
define('WPA0_PLUGIN_URL', trailingslashit(plugin_dir_url(__FILE__) ));
define('WPA0_LANG', 'wp-auth0');
define('AUTH0_DB_VERSION', 2);
class WP_Auth0 {
public static function init(){
spl_autoload_register(array(__CLASS__, 'autoloader'));
// WP_Auth0_Referer_Check::init();
WP_Auth0_Ip_Check::init();
add_action( 'init', array(__CLASS__, 'wp_init') );
// Add hooks for clear up session
add_action( 'wp_logout', array(__CLASS__, 'logout') );
add_action( 'wp_login', array(__CLASS__, 'end_session') );
// Add hooks for install uninstall and update
register_activation_hook( WPA0_PLUGIN_FILE, array(__CLASS__, 'install') );
register_deactivation_hook( WPA0_PLUGIN_FILE, array(__CLASS__, 'uninstall') );
add_action( 'plugins_loaded', array(__CLASS__, 'check_update'));
add_action( 'plugins_loaded', array(__CLASS__, 'initialize_wpdb_tables'));
add_action( 'template_redirect', array(__CLASS__, 'init_auth0'), 1 );
add_filter( 'login_message', array(__CLASS__, 'render_form') );
// Add hook to redirect directly on login auto
add_action('login_init', array(__CLASS__, 'login_auto'));
// Add hook to handle when a user is deleted
add_action( 'delete_user', array(__CLASS__, 'delete_user') );
add_shortcode( 'auth0', array(__CLASS__, 'shortcode' ) );
add_action( 'wp_enqueue_scripts', array(__CLASS__, 'wp_enqueue'));
WP_Auth0_Admin::init();
}
public static function wp_enqueue(){
$activated = absint(WP_Auth0_Options::get( 'active' ));
if(!$activated) {
return;
}
wp_enqueue_style( 'auth0-widget', WPA0_PLUGIN_URL . 'assets/css/main.css' );
}
public static function shortcode( $atts ){
ob_start();
include WPA0_PLUGIN_DIR . 'templates/login-form.php';
$html = ob_get_clean();
return $html;
}
public static function login_auto() {
$auto_login = absint(WP_Auth0_Options::get( 'auto_login' ));
if ($auto_login && $_GET["action"] != "logout") {
$stateObj = array("interim" => false, "uuid" =>uniqid());
$state = $_SESSION['auth0_state'] = json_encode($stateObj);
// Create the link to log in
$login_url = "https://". WP_Auth0_Options::get('domain') .
"/authorize?response_type=code&scope=openid%20profile".
"&client_id=".WP_Auth0_Options::get('client_id') .
"&redirect_uri=".site_url('/index.php?auth0=1') .
"&state=".urlencode($state).
"&connection=".WP_Auth0_Options::get('auto_login_method');
wp_redirect($login_url);
die();
}
}
public static function logout() {
self::end_session();
$auto_login = absint(WP_Auth0_Options::get( 'auto_login' ));
if ($auto_login) {
wp_redirect(home_url());
die();
}
}
public static function render_form( $html ){
$activated = absint(WP_Auth0_Options::get( 'active' ));
if(!$activated)
return $html;
ob_start();
include WPA0_PLUGIN_DIR . 'templates/login-form.php';
$html = ob_get_clean();
return $html;
}
public static function init_auth0(){
global $wp_query;
if(!isset($wp_query->query_vars['auth0']) || $wp_query->query_vars['auth0'] != '1') {
return;
}
$code = $wp_query->query_vars['code'];
$state = $wp_query->query_vars['state'];
$stateFromGet = json_decode(stripcslashes($state));
$stateFromSession = json_decode($_SESSION['auth0_state']);
$domain = WP_Auth0_Options::get( 'domain' );
$endpoint = "https://" . $domain . "/";
$client_id = WP_Auth0_Options::get( 'client_id' );
$client_secret = WP_Auth0_Options::get( 'client_secret' );
if(empty($client_id)) wp_die(__('Error: Your Auth0 Client ID has not been entered in the Auth0 SSO plugin settings.', WPA0_LANG));
if(empty($client_secret)) wp_die(__('Error: Your Auth0 Client Secret has not been entered in the Auth0 SSO plugin settings.', WPA0_LANG));
if(empty($domain)) wp_die(__('Error: No Domain defined in Wordpress Administration!', WPA0_LANG));
if ($stateFromSession->uuid != $stateFromGet->uuid)
wp_die(__('Error: The state code doesn\'t match! Are you sure you are comming from the page?', WPA0_LANG));
$body = array(
'client_id' => $client_id,
'redirect_uri' => home_url(),
'client_secret' => $client_secret,
'code' => $code,
'grant_type' => 'authorization_code'
);
$headers = array(
'content-type' => 'application/x-www-form-urlencoded'
);
$response = wp_remote_post( $endpoint . 'oauth/token', array(
'headers' => $headers,
'body' => $body
));
if ($response instanceof WP_Error) {
error_log($response->get_error_message());
$msg = __('Sorry. There was a problem logging you in.', WPA0_LANG);
$msg .= '<br/><br/>';
$msg .= '<a href="' . wp_login_url() . '">' . __('← Login', WPA0_LANG) . '</a>';
wp_die($msg);
}
$data = json_decode( $response['body'] );
if(isset($data->access_token)){
// Get the user information
$response = wp_remote_get( $endpoint . 'userinfo/?access_token=' . $data->access_token );
if ($response instanceof WP_Error) {
error_log($response->get_error_message());
$msg = __('Sorry, there was a problem logging you in.', WPA0_LANG);
$msg .= '<br/><br/>';
$msg .= '<a href="' . wp_login_url() . '">' . __('← Login', WPA0_LANG) . '</a>';
wp_die($msg);
}
$userinfo = json_decode( $response['body'] );
if (self::login_user($userinfo, $data)) {
if ($stateFromGet->interim) {
include WPA0_PLUGIN_DIR . 'templates/login-interim.php';
exit();
} else {
wp_safe_redirect( home_url() );
}
}
}else{
// Login failed!
wp_redirect( home_url() . '?message=' . $data->error_description );
//echo "Error logging in! Description received was:<br/>" . $data->error_description;
}
exit();
}
private static function findAuth0User($id) {
global $wpdb;
$sql = 'SELECT u.*
FROM ' . $wpdb->auth0_user .' a
JOIN ' . $wpdb->users . ' u ON a.wp_id = u.id
WHERE a.auth0_id = %s';
$userRow = $wpdb->get_row($wpdb->prepare($sql, $id));
if (is_null($userRow) || $userRow instanceof WP_Error ) {
return null;
}
$user = new WP_User();
$user->init($userRow);
return $user;
}
private static function insertAuth0User($userinfo, $user_id) {
global $wpdb;
$wpdb->insert(
$wpdb->auth0_user,
array(
'auth0_id' => $userinfo->user_id,
'wp_id' => $user_id,
'auth0_obj' => serialize($userinfo)
),
array(
'%s',
'%d',
'%s'
)
);
}
private static function updateAuth0Object($userinfo) {
global $wpdb;
$wpdb->update(
$wpdb->auth0_user,
array(
'auth0_obj' => serialize($userinfo)
),
array( 'auth0_id' => $userinfo->user_id ),
array( '%s' ),
array( '%s' )
);
}
public static function delete_user ($user_id) {
global $wpdb;
$wpdb->delete( $wpdb->auth0_user, array( 'wp_id' => $user_id), array( '%d' ) );
}
private static function dieWithVerifyEmail($userinfo, $data) {
ob_start();
$domain = WP_Auth0_Options::get( 'domain' );
$token = $data->id_token;
$email = $userinfo->email;
$connection = $userinfo->identities[0]->connection;
$userId = $userinfo->user_id;
include WPA0_PLUGIN_DIR . 'templates/verify-email.php';
$html = ob_get_clean();
wp_die($html);
}
private static function login_user( $userinfo, $data ){
// If the userinfo has no email or an unverified email, and in the options we require a verified email
// notify the user he cant login until he does so.
if (WP_Auth0_Options::get( 'requires_verified_email' )){
if (empty($userinfo->email)) {
$msg = __('This account does not have an email associated. Please login with a different provider.', WPA0_LANG);
$msg .= '<br/><br/>';
$msg .= '<a href="' . site_url() . '">' . __('← Go back', WPA0_LANG) . '</a>';
wp_die($msg);
}
if (!$userinfo->email_verified) {
self::dieWithVerifyEmail($userinfo, $data);
}
}
// See if there is a user in the auth0_user table with the user info client id
$user = self::findAuth0User($userinfo->user_id);
if (!is_null($user)) {
// User exists! Log in
self::updateAuth0Object($userinfo);
wp_set_auth_cookie( $user->ID );
return true;
} else {
// If the user doesn't exist we need to either create a new one, or asign him to an existing one
$isDatabaseUser = false;
foreach ($userinfo->identities as $identity) {
if ($identity->provider == "auth0") {
$isDatabaseUser = true;
}
}
$joinUser = null;
// 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 ($userinfo->email_verified || $isDatabaseUser) {
$joinUser = get_user_by( 'email', $userinfo->email );
}
if (!is_null($joinUser) && $joinUser instanceof WP_User) {
// 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 (!$userinfo->email_verified) {
self::dieWithVerifyEmail($userinfo, $data);
}
$user_id = $joinUser->ID;
} else {
// If we are here, we need to create the user
$user_id = (int)WP_Auth0_Users::create_user($userinfo);
// Check if user was created
if($user_id == -2){
$msg = __('Error: Could not create user. The registration process were rejected. Please verify that your account is whitelisted for this system.', WPA0_LANG);
$msg .= '<br/><br/>';
$msg .= '<a href="' . site_url() . '">' . __('← Go back', WPA0_LANG) . '</a>';
wp_die($msg);
}elseif ($user_id <0){
$msg = __('Error: Could not create user.', WPA0_LANG);
$msg .= '<br/><br/>';
$msg .= '<a href="' . site_url() . '">' . __('← Go back', WPA0_LANG) . '</a>';
wp_die($msg);
}
}
// If we are here we should have a valid $user_id with a new user or an existing one
// log him in, and update the auth0_user table
self::insertAuth0User($userinfo, $user_id);
wp_set_auth_cookie( $user_id );
return true;
}
}
public static function wp_init(){
self::setup_rewrites();
// Initialize session
if(!session_id()) {
session_start();
}
}
public static function end_session() {
session_destroy ();
}
private static function setup_rewrites(){
add_rewrite_tag('%auth0%', '([^&]+)');
add_rewrite_tag('%code%', '([^&]+)');
add_rewrite_tag('%state%', '([^&]+)');
add_rewrite_tag('%auth0_error%', '([^&]+)');
add_rewrite_rule('^auth0', 'index.php?auth0=1', 'top');
}
public static function install(){
self::install_db();
self::setup_rewrites();
flush_rewrite_rules();
}
public static function uninstall(){
flush_rewrite_rules();
}
private static function install_db(){
global $wpdb;
self::initialize_wpdb_tables();
$sql = array();
$sql[] = "CREATE TABLE ".$wpdb->auth0_log." (
id INT(11) AUTO_INCREMENT NOT NULL,
event VARCHAR(100) NOT NULL,
level VARCHAR(100) NOT NULL DEFAULT 'notice',
description TEXT,
details LONGTEXT,
logtime INT(11) NOT NULL,
PRIMARY KEY (id)
);";
$sql[] = "CREATE TABLE ".$wpdb->auth0_user." (
auth0_id VARCHAR(100) NOT NULL,
wp_id INT(11) NOT NULL,
auth0_obj TEXT,
PRIMARY KEY (auth0_id)
);";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
foreach($sql as $s) {
dbDelta($s);
}
update_option( "auth0_db_version", AUTH0_DB_VERSION );
}
public static function check_update() {
if ( get_site_option( 'auth0_db_version' ) !== AUTH0_DB_VERSION) {
self::install_db();
}
}
public static function initialize_wpdb_tables(){
global $wpdb;
$wpdb->auth0_log = $wpdb->prefix."auth0_log";
$wpdb->auth0_user = $wpdb->prefix."auth0_user";
}
private static function autoloader($class){
$path = WPA0_PLUGIN_DIR;
$paths = array();
$exts = array('.php', '.class.php');
$paths[] = $path;
$paths[] = $path.'lib/';
foreach($paths as $p)
foreach($exts as $ext){
if(file_exists($p.$class.$ext)){
require_once($p.$class.$ext);
return true;
}
}
return false;
}
}
if ( !function_exists('get_currentauth0userinfo') ) :
function get_currentauth0userinfo() {
global $current_user;
global $currentauth0_user;
global $wpdb;
get_currentuserinfo();
if ($current_user instanceof WP_User && $current_user->ID > 0 ) {
$sql = 'SELECT auth0_obj
FROM ' . $wpdb->auth0_user .'
WHERE wp_id = %d';
$result = $wpdb->get_row($wpdb->prepare($sql, $current_user->ID));
if (is_null($result) || $result instanceof WP_Error ) {
return null;
}
$currentauth0_user = unserialize($result->auth0_obj);
}
}
endif;
WP_Auth0::init();