-
Notifications
You must be signed in to change notification settings - Fork 113
/
Copy pathclient.php
507 lines (419 loc) · 14.7 KB
/
client.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
<?php
/**
* Allows for Single Sign On between WordPress and Discourse with Discourse as SSO Provider
*
* @package WPDiscourse\sso
*/
namespace WPDiscourse\SSOClient;
/**
* Class Client
*/
class Client extends SSOClientBase {
/**
* Logger context
*
* @access protected
* @var string
*/
protected $logger_context = 'sso_client';
/**
* Constructor
*/
public function __construct() {
add_action( 'init', array( $this, 'setup_options' ), 4 );
add_action( 'init', array( $this, 'setup_logger' ), 4 );
add_action( 'init', array( $this, 'parse_request' ), 5 );
add_filter( 'wp_login_errors', array( $this, 'handle_login_errors' ) );
add_action( 'clear_auth_cookie', array( $this, 'logout_from_discourse' ) );
add_action( 'login_form', array( $this, 'discourse_sso_alter_login_form' ) );
add_action( 'show_user_profile', array( $this, 'discourse_sso_alter_user_profile' ) );
add_action( 'admin_notices', array( $this, 'set_user_notice' ) );
}
/**
* Sets a notice for users when they link their account with Discourse.
*/
public function set_user_notice() {
global $pagenow;
$sso_client_enabled = ! empty( $this->options['sso-client-enabled'] );
if ( $sso_client_enabled && 'profile.php' === $pagenow ) {
$user_id = get_current_user_id();
$mismatched_emails = get_user_meta( $user_id, 'discourse_mismatched_emails', true );
if ( $mismatched_emails ) {
$error_message = __(
'<div class="notice notice-error is-dismissible"><p>To link an existing WordPress account with Discourse,
the email addresses of both accounts must match. Make sure you are logged into the correct Discourse account.
If you are unable to edit your email addresses to match, contact a site administrator.</p></div>',
'wp-discourse'
);
delete_user_meta( $user_id, 'discourse_mismatched_emails' );
echo wp_kses_post( $error_message );
} else {
$user_synced = get_user_meta( $user_id, 'discourse_sso_client_synced', true );
if ( $user_synced ) {
$success_message = __(
'<div class="notice notice-success is-dismissible"><p>Your account is linked to Discourse!.</p></div>',
'wp-discourse'
);
delete_user_meta( $user_id, 'discourse_sso_client_synced' );
echo wp_kses_post( $success_message );
}
}
}
}
/**
* Decides if checkbox for login form alteration are enabled
*
* @return boolean
*/
protected function discourse_sso_auto_inject_button() {
return ! empty( $this->options['sso-client-enabled'] ) && ! empty( $this->options['sso-client-login-form-change'] );
}
/**
* Alter the login form
*/
public function discourse_sso_alter_login_form() {
if ( ! $this->discourse_sso_auto_inject_button() ) {
return null;
}
printf(
'<p>%s</p><p> </p>',
wp_kses_data(
$this->get_discourse_sso_link_markup(
array(
'redirect' => $this->options['sso-client-login-form-redirect'],
)
)
)
);
do_action( 'wpdc_sso_client_after_login_link' );
}
/**
* Alter user profile
*/
public function discourse_sso_alter_user_profile() {
$auto_inject_button = $this->discourse_sso_auto_inject_button();
$link_text = ! empty( self::get_text_options( 'link-to-discourse-text' ) ) ? self::get_text_options( 'link-to-discourse-text' ) : '';
$linked_text = ! empty( self::get_text_options( 'linked-to-discourse-text' ) ) ? self::get_text_options( 'linked-to-discourse-text' ) : '';
$user = wp_get_current_user();
if ( ! apply_filters( 'wpdc_sso_client_add_link_buttons_on_profile', $auto_inject_button ) ) {
return null;
}
?>
<table class="form-table">
<tr>
<th><?php echo wp_kses_post( $link_text ); ?></th>
<td>
<?php
if ( $user && get_user_meta( $user->ID, 'discourse_sso_user_id', true ) ) {
echo wp_kses_post( $linked_text );
} else {
echo wp_kses_data( $this->get_discourse_sso_link_markup() ) .
' <em>' . esc_html__( 'To link accounts, your Discourse email address needs to match your WordPress email address', 'wp-discourse' ) . '</em>';
}
?>
</td>
</tr>
</table>
<?php
}
/**
* Parse Request Hook
*/
public function parse_request() {
if ( empty( $this->options['sso-client-enabled'] ) || empty( $_GET['sso'] ) || empty( $_GET['sig'] ) ) {
return;
}
if ( ! $this->is_valid_signature() ) {
$this->logger->error( 'parse_request.invalid_signature' );
return;
}
$user_id = $this->get_user_id();
if ( is_wp_error( $user_id ) ) {
$this->handle_errors( $user_id, 'parse_request.get_user_id' );
return;
}
$updated_user = $this->update_user( $user_id );
if ( is_wp_error( $updated_user ) ) {
$this->handle_errors( $updated_user, 'parse_request.update_user' );
return;
}
return $this->auth_user( $user_id );
}
/**
* Validates SSO signature
*
* @return boolean
*/
private function is_valid_signature() {
$sso = urldecode( $this->get_sso_response( 'raw' ) );
return hash_hmac( 'sha256', $sso, $this->get_sso_secret() ) === $this->get_sso_signature();
}
/**
* Get user id or create a user.
*
* For logged in users, the function checks if the 'discourse_sso_user_id' is set. If it isn't set, the user's email
* is checked against the email from the SSO payload. If this doesn't match, the user is redirected to their profile
* page where an error notice is displayed.
*
* For non-logged-in users, the function checks if there's an existing user with the payload's 'discourse_sso_user_id',
* if there isn't, there is an optional check for a user with a matching email address. If both checks fail, a new user
* is created if not prohibited by configuration.
*
* @return int|\WP_Error
*/
private function get_user_id() {
if ( is_user_logged_in() ) {
$user_id = get_current_user_id();
$redirect = $this->get_sso_response( 'return_sso_url' );
if ( get_user_meta( $user_id, 'discourse_sso_user_id', true ) ) {
return $this->redirect_to( $redirect );
} else {
$discourse_email = $this->get_sso_response( 'email' );
$wp_email = wp_get_current_user()->user_email;
if ( $discourse_email === $wp_email ) {
update_user_meta( $user_id, 'discourse_sso_user_id', $this->get_sso_response( 'external_id' ) );
update_user_meta( $user_id, 'discourse_sso_client_synced', 1 );
return $this->redirect_to( $redirect );
} else {
update_user_meta( $user_id, 'discourse_mismatched_emails', 1 );
$profile_url = get_edit_profile_url();
return $this->redirect_to( $profile_url );
}
}
} else {
$user_query = new \WP_User_Query(
array(
'meta_key' => 'discourse_sso_user_id',
'meta_value' => $this->get_sso_response( 'external_id' ),
)
);
$user_query_results = $user_query->get_results();
if ( empty( $user_query_results ) && ! empty( $this->options['sso-client-sync-by-email'] ) ) {
$user = get_user_by( 'email', $this->get_sso_response( 'email' ) );
if ( $user ) {
return $user->ID;
}
}
if ( empty( $user_query_results ) && ! empty( $this->options['sso-client-disable-create-user'] ) ) {
return new \WP_Error( 'no_matching_user' );
}
if ( empty( $user_query_results ) ) {
$user_password = wp_generate_password( 12, true );
$user_id = wp_create_user(
$this->get_sso_response( 'username' ),
$user_password,
$this->get_sso_response( 'email' )
);
do_action( 'wpdc_sso_client_after_create_user', $user_id );
return $user_id;
}
return $user_query_results[0]->ID;
}// End if().
}
/**
* Update WP user with discourse user data
*
* @param int $user_id the user ID.
*
* @return int|\WP_Error integer if the update was successful, WP_Error otherwise.
*/
private function update_user( $user_id ) {
$query = $this->get_sso_response();
$nonce = Nonce::get_instance()->verify( $query['nonce'], '_discourse_sso' );
if ( ! $nonce ) {
return new \WP_Error( 'expired_nonce' );
}
$username = $query['username'];
$updated_user = array(
'ID' => $user_id,
'user_nicename' => $username,
);
if ( ! empty( $query['name'] ) ) {
$updated_user['first_name'] = explode( ' ', $query['name'] )[0];
$updated_user['name'] = $query['name'];
}
$updated_user = apply_filters( 'wpdc_sso_client_updated_user', $updated_user, $query );
$update = wp_update_user( $updated_user );
if ( ! is_wp_error( $update ) ) {
update_user_meta( $user_id, 'discourse_username', $username );
if ( ! get_user_meta( $user_id, 'discourse_sso_user_id', true ) ) {
update_user_meta( $user_id, 'discourse_sso_user_id', $query['external_id'] );
}
do_action( 'wpdc_after_sso_client_user_update', $user_id, $query );
}
return $update;
}
/**
* Set auth cookies
*
* @param int $user_id the user ID.
* @return null
*/
private function auth_user( $user_id ) {
$query = $this->get_sso_response();
wp_set_current_user( $user_id, $query['username'] );
wp_set_auth_cookie( $user_id );
$user = wp_get_current_user();
if ( ! $user->exists() ) {
$log_args = array( 'user_id' => $user_id );
$this->logger->error( 'auth_user.user_does_not_exist', $log_args );
return null;
}
do_action( 'wp_login', $query['username'], $user );
$result = wp_get_current_user();
$redirect_to = apply_filters( 'wpdc_sso_client_redirect_after_login', $query['return_sso_url'] );
if ( ! empty( $this->options['verbose-sso-logs'] ) ) {
$log_args = array( 'user_id' => $user_id );
$this->logger->info( 'auth_user.success', $log_args );
}
return $this->redirect_to( $redirect_to );
}
/**
* Handle Login errors
*
* @param \WP_Error $error WP_Error object.
* @param string $context error context.
*/
private function handle_errors( $error, $context ) {
$log_args = array(
'code' => $error->get_error_code(),
'message' => $error->get_error_message(),
);
$this->logger->error( $context, $log_args );
$redirect_to = apply_filters( 'wpdc_sso_client_redirect_after_failed_login', wp_login_url() );
$redirect_to = add_query_arg( 'discourse_sso_error', $log_args['code'], $redirect_to );
$this->redirect_to( $redirect_to );
}
/**
* Add errors on the login form.
*
* @param \WP_Error $errors the WP_Error object.
*
* @return \WP_Error updated errors.
*/
public function handle_login_errors( $errors ) {
if ( isset( $_GET['discourse_sso_error'] ) ) { // Input var okay.
$err = sanitize_text_field( wp_unslash( $_GET['discourse_sso_error'] ) ); // Input var okay.
switch ( $err ) {
case 'existing_user_email':
$message = __( "There is an exiting account with the email address you are attempting to login with. If you are trying to log in through Discourse, you need to first login through WordPress, visit your profile page, and click on the 'sync accounts' link.", 'wp-discourse' );
$errors->add( 'discourse_sso_existing_user', $message );
break;
case 'expired_nonce':
$message = __( 'Expired Nonce', 'wp-discourse' );
$errors->add( 'discourse_sso_expired_nonce', $message );
break;
case 'existing_user_login':
$message = __( 'There is already an account registered with the username supplied by Discourse. If this is you, login through WordPress and visit your profile page to sync your account with Discourse', 'wp-discourse' );
$errors->add( 'existing_user_login', $message );
break;
case 'no_matching_user':
$message = __( 'No WordPress user matches your Discourse user.', 'wp-discourse' );
$errors->add( 'discourse_sso_no_matching_user', $message );
break;
default:
$message = __( 'Unhandled Error', 'wp-discourse' );
$errors->add( 'discourse_sso_unhandled_error', $message );
break;
}
}
return $errors;
}
/**
* Gets the url to be redirected to
*
* @return string
*/
public function get_redirect_to_after_sso() {
return $this->get_sso_response( 'return_sso_url' );
}
/**
* Get SSO Signature
*/
private function get_sso_signature() {
$sig = isset( $_GET['sig'] ) ? sanitize_text_field( wp_unslash( $_GET['sig'] ) ) : ''; // Input var okay.
return sanitize_text_field( $sig );
}
/**
* Get SSO Secret from options
*/
private function get_sso_secret() {
return $this->options['sso-secret'];
}
/**
* Parse SSO Response
*
* @param string $return_key The key to return.
*
* @return string|array
*/
private function get_sso_response( $return_key = '' ) {
if ( empty( $_GET['sso'] ) ) { // Input var okay.
return null;
}
if ( 'raw' === $return_key ) {
return sanitize_text_field( wp_unslash( $_GET['sso'] ) ); // Input var okay.
}
$sso = base64_decode( sanitize_text_field( wp_unslash( $_GET['sso'] ) ), true ); // Input var okay.
if ( ! $sso ) {
return null;
}
$response = array();
parse_str( $sso, $response );
$response = array_map( 'rawurldecode', $response );
$response = array_map( 'sanitize_text_field', $response );
if ( empty( $response['external_id'] ) ) {
return null;
}
if ( ! empty( $return_key ) && isset( $response[ $return_key ] ) ) {
return $response[ $return_key ];
}
return $response;
}
/**
* Log the current user out of Discourse before logging them out of WordPress.
*
* This function hooks into the 'clear_auth_cookie' action. It is the last action hook before logout
* where it is possible to access the user_id.
*
* @return \WP_Error
*/
public function logout_from_discourse() {
// If sso-client is not enabled, don't make the request.
if ( empty( $this->options['sso-client-enabled'] ) || empty( $this->options['sso-client-sync-logout'] ) ) {
return null;
}
$user = wp_get_current_user();
$user_id = $user->ID;
$discourse_user_id = get_user_meta( $user_id, 'discourse_sso_user_id', true );
if ( empty( $discourse_user_id ) ) {
$discourse_user = $this->get_discourse_user( $user_id );
if ( empty( $discourse_user->id ) ) {
return new \WP_Error( 'wpdc_response_error', 'The Discourse user_id could not be returned when trying to logout the user.' );
}
$discourse_user_id = $discourse_user->id;
update_user_meta( $user_id, 'discourse_sso_user_id', $discourse_user_id );
}
$path = "/admin/users/$discourse_user_id/log_out";
$response = $this->discourse_request(
$path, array(
'method' => 'POST',
'raw' => true,
)
);
if ( ! $this->validate( $response ) ) {
return new \WP_Error( 'wpdc_response_error', 'There was an error in logging out the current user from Discourse.' );
} else {
return null;
}
}
/**
* Handle redirects
*
* @param string $url Url to redirect to.
*/
public function redirect_to( $url ) {
wp_safe_redirect( esc_url_raw( $url ) );
exit;
}
}