-
Notifications
You must be signed in to change notification settings - Fork 6
/
personalize-login.php
567 lines (470 loc) · 17.1 KB
/
personalize-login.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
<?php
/**
* Plugin Name: Personalize Login
* Description: A plugin that replaces the WordPress login flow with a custom page.
* Version: 1.0.0
* Author: Jarkko Laine
* License: GPL-2.0+
* Text Domain: personalize-login
*/
class Personalize_Login_Plugin {
/**
* Initializes the plugin.
*
* To keep the initialization fast, only add filter and action
* hooks in the constructor.
*/
public function __construct() {
add_action( 'login_form_login', array( $this, 'redirect_to_custom_login' ) );
add_action( 'login_form_register', array( $this, 'redirect_to_custom_register' ) );
add_action( 'login_form_register', array( $this, 'do_register_user' ) );
add_action( 'wp_print_footer_scripts', array( $this, 'add_captcha_js_to_footer' ) );
add_action( 'wp_logout', array( $this, 'redirect_after_logout' ) );
add_filter( 'authenticate', array( $this, 'maybe_redirect_at_authenticate' ), 101, 3 );
add_filter( 'login_redirect', array( $this, 'redirect_after_login' ), 10, 3 );
add_filter( 'admin_init' , array( $this, 'register_settings_fields' ) );
add_shortcode( 'custom-login-form', array( $this, 'render_login_form' ) );
add_shortcode( 'custom-register-form', array( $this, 'render_register_form' ) );
}
/**
* Plugin activation hook.
*
* Creates all WordPress pages needed by the plugin.
*/
public static function plugin_activated() {
// Information needed for creating the plugin's pages
$page_definitions = array(
'member-login' => array(
'title' => __( 'Sign In', 'personalize-login' ),
'content' => '[custom-login-form]'
),
'member-account' => array(
'title' => __( 'Your Account', 'personalize-login' ),
'content' => '[account-info]'
),
'member-register' => array(
'title' => __( 'Register', 'personalize-login' ),
'content' => '[custom-register-form]'
)
);
foreach ( $page_definitions as $slug => $page ) {
// Check that the page doesn't exist already
$query = new WP_Query( 'pagename=' . $slug );
if ( ! $query->have_posts() ) {
// Add the page using the data from the array above
wp_insert_post(
array(
'post_content' => $page['content'],
'post_name' => $slug,
'post_title' => $page['title'],
'post_status' => 'publish',
'post_type' => 'page',
'ping_status' => 'closed',
'comment_status' => 'closed',
)
);
}
}
}
//
// REDIRECT FUNCTIONS
//
/**
* Redirect the user to the custom login page instead of wp-login.php.
*/
public function redirect_to_custom_login() {
$redirect_to = isset( $_REQUEST['redirect_to'] ) ? $_REQUEST['redirect_to'] : null;
if ( $_SERVER['REQUEST_METHOD'] == 'GET' ) {
if ( is_user_logged_in() ) {
$this->redirect_logged_in_user( $redirect_to );
exit;
}
// The rest are redirected to the login page
$login_url = home_url( 'member-login' );
if ( ! empty( $redirect_to ) ) {
$login_url = add_query_arg( 'redirect_to', $redirect_to, $login_url );
}
wp_redirect( $login_url );
exit;
}
}
/**
* Redirects the user to the custom registration page instead
* of wp-login.php?action=register.
*/
public function redirect_to_custom_register() {
if ( 'GET' == $_SERVER['REQUEST_METHOD'] ) {
if ( is_user_logged_in() ) {
$this->redirect_logged_in_user();
} else {
wp_redirect( home_url( 'member-register' ) );
}
exit;
}
}
/**
* Returns the URL to which the user should be redirected after the (successful) login.
*
* @param string $redirect_to The redirect destination URL.
* @param string $requested_redirect_to The requested redirect destination URL passed as a parameter.
* @param WP_User|WP_Error $user WP_User object if login was successful, WP_Error object otherwise.
*
* @return string Redirect URL
*/
public function redirect_after_login( $redirect_to, $requested_redirect_to, $user ) {
$redirect_url = home_url();
if ( ! isset( $user->ID ) ) {
return $redirect_url;
}
if ( user_can( $user, 'manage_options' ) ) {
// Use the redirect_to parameter if one is set, otherwise redirect to admin dashboard.
if ( $requested_redirect_to == '' ) {
$redirect_url = admin_url();
} else {
$redirect_url = $redirect_to;
}
} else {
// Non-admin users always go to their account page after login
$redirect_url = home_url( 'member-account' );
}
return wp_validate_redirect( $redirect_url, home_url() );
}
/**
* Redirect to custom login page after the user has been logged out.
*/
public function redirect_after_logout() {
$redirect_url = home_url( 'member-login?logged_out=true' );
wp_redirect( $redirect_url );
exit;
}
/**
* Redirect the user after authentication if there were any errors.
*
* @param Wp_User|Wp_Error $user The signed in user, or the errors that have occurred during login.
* @param string $username The user name used to log in.
* @param string $password The password used to log in.
*
* @return Wp_User|Wp_Error The logged in user, or error information if there were errors.
*/
public function maybe_redirect_at_authenticate( $user, $username, $password ) {
// Check if the earlier authenticate filter (most likely,
// the default WordPress authentication) functions have found errors
if ( $_SERVER['REQUEST_METHOD'] === 'POST' ) {
if ( is_wp_error( $user ) ) {
$error_codes = join( ',', $user->get_error_codes() );
$login_url = home_url( 'member-login' );
$login_url = add_query_arg( 'login', $error_codes, $login_url );
wp_redirect( $login_url );
exit;
}
}
return $user;
}
//
// FORM RENDERING SHORTCODES
//
/**
* A shortcode for rendering the login form.
*
* @param array $attributes Shortcode attributes.
* @param string $content The text content for shortcode. Not used.
*
* @return string The shortcode output
*/
public function render_login_form( $attributes, $content = null ) {
// Parse shortcode attributes
$default_attributes = array( 'show_title' => false );
$attributes = shortcode_atts( $default_attributes, $attributes );
if ( is_user_logged_in() ) {
return __( 'You are already signed in.', 'personalize-login' );
}
// Pass the redirect parameter to the WordPress login functionality: by default,
// don't specify a redirect, but if a valid redirect URL has been passed as
// request parameter, use it.
$attributes['redirect'] = '';
if ( isset( $_REQUEST['redirect_to'] ) ) {
$attributes['redirect'] = wp_validate_redirect( $_REQUEST['redirect_to'], $attributes['redirect'] );
}
// Error messages
$errors = array();
if ( isset( $_REQUEST['login'] ) ) {
$error_codes = explode( ',', $_REQUEST['login'] );
foreach ( $error_codes as $code ) {
$errors []= $this->get_error_message( $code );
}
}
$attributes['errors'] = $errors;
// Check if user just logged out
$attributes['logged_out'] = isset( $_REQUEST['logged_out'] ) && $_REQUEST['logged_out'] == true;
// Check if the user just registered
$attributes['registered'] = isset( $_REQUEST['registered'] );
// Render the login form using an external template
return $this->get_template_html( 'login_form', $attributes );
}
/**
* A shortcode for rendering the new user registration form.
*
* @param array $attributes Shortcode attributes.
* @param string $content The text content for shortcode. Not used.
*
* @return string The shortcode output
*/
public function render_register_form( $attributes, $content = null ) {
// Parse shortcode attributes
$default_attributes = array( 'show_title' => false );
$attributes = shortcode_atts( $default_attributes, $attributes );
if ( is_user_logged_in() ) {
return __( 'You are already signed in.', 'personalize-login' );
} elseif ( ! get_option( 'users_can_register' ) ) {
return __( 'Registering new users is currently not allowed.', 'personalize-login' );
} else {
// Retrieve possible errors from request parameters
$attributes['errors'] = array();
if ( isset( $_REQUEST['register-errors'] ) ) {
$error_codes = explode( ',', $_REQUEST['register-errors'] );
foreach ( $error_codes as $error_code ) {
$attributes['errors'] []= $this->get_error_message( $error_code );
}
}
// Retrieve recaptcha key
$attributes['recaptcha_site_key'] = get_option( 'personalize-login-recaptcha-site-key', null );
return $this->get_template_html( 'register_form', $attributes );
}
}
/**
* Renders the contents of the given template to a string and returns it.
*
* @param string $template_name The name of the template to render (without .php)
* @param array $attributes The PHP variables for the template
*
* @return string The contents of the template.
*/
private function get_template_html( $template_name, $attributes = null ) {
if ( ! $attributes ) {
$attributes = array();
}
ob_start();
do_action( 'personalize_login_before_' . $template_name );
require( 'templates/' . $template_name . '.php');
do_action( 'personalize_login_after_' . $template_name );
$html = ob_get_contents();
ob_end_clean();
return $html;
}
/**
* An action function used to include the reCAPTCHA JavaScript file
* at the end of the page.
*/
public function add_captcha_js_to_footer() {
echo "<script src='https://www.google.com/recaptcha/api.js?hl=en'></script>";
}
//
// ACTION HANDLERS
//
/**
* Handles the registration of a new user.
*
* Used through the action hook "login_form_register" activated on wp-login.php
* when accessed through the registration action.
*/
public function do_register_user() {
if ( 'POST' == $_SERVER['REQUEST_METHOD'] ) {
$redirect_url = home_url( 'member-register' );
if ( ! get_option( 'users_can_register' ) ) {
// Registration closed, display error
$redirect_url = add_query_arg( 'register-errors', 'closed', $redirect_url );
} elseif ( ! $this->verify_recaptcha() ) {
// Recaptcha check failed, display error
$redirect_url = add_query_arg( 'register-errors', 'captcha', $redirect_url );
} else {
$email = $_POST['email'];
$first_name = sanitize_text_field( $_POST['first_name'] );
$last_name = sanitize_text_field( $_POST['last_name'] );
$result = $this->register_user( $email, $first_name, $last_name );
if ( is_wp_error( $result ) ) {
// Parse errors into a string and append as parameter to redirect
$errors = join( ',', $result->get_error_codes() );
$redirect_url = add_query_arg( 'register-errors', $errors, $redirect_url );
} else {
// Success, redirect to login page.
$redirect_url = home_url( 'member-login' );
$redirect_url = add_query_arg( 'registered', $email, $redirect_url );
}
}
wp_redirect( $redirect_url );
exit;
}
}
//
// HELPER FUNCTIONS
//
/**
* Validates and then completes the new user signup process if all went well.
*
* @param string $email The new user's email address
* @param string $first_name The new user's first name
* @param string $last_name The new user's last name
*
* @return int|WP_Error The id of the user that was created, or error if failed.
*/
private function register_user( $email, $first_name, $last_name ) {
$errors = new WP_Error();
// Email address is used as both username and email. It is also the only
// parameter we need to validate
if ( ! is_email( $email ) ) {
$errors->add( 'email', $this->get_error_message( 'email' ) );
return $errors;
}
if ( username_exists( $email ) || email_exists( $email ) ) {
$errors->add( 'email_exists', $this->get_error_message( 'email_exists') );
return $errors;
}
// Generate the password so that the subscriber will have to check email...
$password = wp_generate_password( 12, false );
$user_data = array(
'user_login' => $email,
'user_email' => $email,
'user_pass' => $password,
'first_name' => $first_name,
'last_name' => $last_name,
'nickname' => $first_name,
);
$user_id = wp_insert_user( $user_data );
wp_new_user_notification( $user_id, $password );
return $user_id;
}
/**
* Checks that the reCAPTCHA parameter sent with the registration
* request is valid.
*
* @return bool True if the CAPTCHA is OK, otherwise false.
*/
private function verify_recaptcha() {
// This field is set by the recaptcha widget if check is successful
if ( isset ( $_POST['g-recaptcha-response'] ) ) {
$captcha_response = $_POST['g-recaptcha-response'];
} else {
return false;
}
// Verify the captcha response from Google
$response = wp_remote_post(
'https://www.google.com/recaptcha/api/siteverify',
array(
'body' => array(
'secret' => get_option( 'personalize-login-recaptcha-secret-key' ),
'response' => $captcha_response
)
)
);
$success = false;
if ( $response && is_array( $response ) ) {
$decoded_response = json_decode( $response['body'] );
$success = $decoded_response->success;
}
return $success;
}
/**
* Redirects the user to the correct page depending on whether he / she
* is an admin or not.
*
* @param string $redirect_to An optional redirect_to URL for admin users
*/
private function redirect_logged_in_user( $redirect_to = null ) {
$user = wp_get_current_user();
if ( user_can( $user, 'manage_options' ) ) {
if ( $redirect_to ) {
wp_safe_redirect( $redirect_to );
} else {
wp_redirect( admin_url() );
}
} else {
wp_redirect( home_url( 'member-account' ) );
}
}
/**
* Finds and returns a matching error message for the given error code.
*
* @param string $error_code The error code to look up.
*
* @return string An error message.
*/
private function get_error_message( $error_code ) {
switch ( $error_code ) {
// Login errors
case 'empty_username':
return __( 'You do have an email address, right?', 'personalize-login' );
case 'empty_password':
return __( 'You need to enter a password to login.', 'personalize-login' );
case 'invalid_username':
return __(
"We don't have any users with that email address. Maybe you used a different one when signing up?",
'personalize-login'
);
case 'incorrect_password':
$err = __(
"The password you entered wasn't quite right. <a href='%s'>Did you forget your password</a>?",
'personalize-login'
);
return sprintf( $err, wp_lostpassword_url() );
// Registration errors
case 'email':
return __( 'The email address you entered is not valid.', 'personalize-login' );
case 'email_exists':
return __( 'An account exists with this email address.', 'personalize-login' );
case 'closed':
return __( 'Registering new users is currently not allowed.', 'personalize-login' );
case 'captcha':
return __( 'The Google reCAPTCHA check failed. Are you a robot?', 'personalize-login' );
// Lost password
case 'empty_username':
return __( 'You need to enter your email address to continue.', 'personalize-login' );
case 'invalid_email':
case 'invalidcombo':
return __( 'There are no users registered with this email address.', 'personalize-login' );
// Reset password
case 'expiredkey':
case 'invalidkey':
return __( 'The password reset link you used is not valid anymore.', 'personalize-login' );
case 'password_reset_mismatch':
return __( "The two passwords you entered don't match.", 'personalize-login' );
default:
break;
}
return __( 'An unknown error occurred. Please try again later.', 'personalize-login' );
}
//
// SETTINGS FIELDS
//
/**
* Registers the settings fields needed by the plugin.
*/
public function register_settings_fields() {
// Create settings fields for the two keys used by reCAPTCHA
register_setting( 'general', 'personalize-login-recaptcha-site-key' );
register_setting( 'general', 'personalize-login-recaptcha-secret-key' );
add_settings_field(
'personalize-login-recaptcha-site-key',
'<label for="personalize-login-recaptcha-site-key">' . __( 'reCAPTCHA site key' , 'personalize-login' ) . '</label>',
array( $this, 'render_recaptcha_site_key_field' ),
'general'
);
add_settings_field(
'personalize-login-recaptcha-secret-key',
'<label for="personalize-login-recaptcha-secret-key">' . __( 'reCAPTCHA secret key' , 'personalize-login' ) . '</label>',
array( $this, 'render_recaptcha_secret_key_field' ),
'general'
);
}
public function render_recaptcha_site_key_field() {
$value = get_option( 'personalize-login-recaptcha-site-key', '' );
echo '<input type="text" id="personalize-login-recaptcha-site-key" name="personalize-login-recaptcha-site-key" value="' . esc_attr( $value ) . '" />';
}
public function render_recaptcha_secret_key_field() {
$value = get_option( 'personalize-login-recaptcha-secret-key', '' );
echo '<input type="text" id="personalize-login-recaptcha-secret-key" name="personalize-login-recaptcha-secret-key" value="' . esc_attr( $value ) . '" />';
}
}
// Initialize the plugin
$personalize_login_pages_plugin = new Personalize_Login_Plugin();
// Create the custom pages at plugin activation
register_activation_hook( __FILE__, array( 'Personalize_Login_Plugin', 'plugin_activated' ) );