Created
May 6, 2017 04:07
-
-
Save itzikbenh/9841bf301d0b66205c0b14bdc9a198ae to your computer and use it in GitHub Desktop.
Nopriv?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function api_register_user( WP_REST_Request $request ) { | |
$username = sanitize_text_field( trim( $request['username'] ) ); | |
$email = sanitize_email( trim( $request['email'] ) ); | |
$password = sanitize_text_field( trim( $request['password'] ) ); | |
$confirm_password = sanitize_text_field( trim( $request['confirm_password'] ) ); | |
$captcha = $request['captcha']; | |
$errors = []; | |
if( ! $captcha ) { | |
$error = "The reCAPTCHA field is required."; | |
return new WP_Error( 'captcha_error', $error, ['status' => 422] ); | |
} | |
if( username_exists( $username ) ) { | |
$errors["username"] = "Username exists already"; | |
} | |
if( strlen( $username ) < 3 ) { | |
$errors["username"] = "Username must be at least 3 characters"; | |
} | |
if( email_exists( $email ) ) { | |
$errors["email"] = "Email exists already"; | |
} | |
if ( empty( $email ) || ! is_email( $email ) ) { | |
$errors["email"] = "Valid Email is required"; | |
} | |
if( $password !== $confirm_password ) { | |
$errors["confirm_password"] = "Password confirmation don't match"; | |
} | |
if( strlen( $password ) < 6 ) { | |
$errors["password"] = "Password must be at least 6 characters"; | |
} | |
if( count( $errors ) > 0 ) { | |
return new WP_Error( 'registration_errors', $errors, ['status' => 422] ); | |
} | |
$secret = "dkjbdhbhjdbhjdbchjdbcjhdbchjdbchjdbchjbddhdbjbc"; | |
$response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$captcha."&remoteip=".$_SERVER["REMOTE_ADDR"]), true); | |
if ( $response['success'] == false ) { | |
$error = "Something went wrong with reCAPTCHA validation, please try again."; | |
return new WP_Error( 'captcha_error', $error, ['status' => 422] ); | |
} | |
$user_data = [ | |
'user_login' => $username, | |
'user_email' => $email, | |
'user_pass' => $password | |
]; | |
$user_id = wp_insert_user( $user_data ); | |
if( is_wp_error( $user_id ) ) { | |
$error = "Sorry, registration failed due to an unxpected error. We are working on fixing it as soon as possible."; | |
return new WP_Error( 'server_error', $error, ['status' => 500] ); | |
} | |
$creds = [ | |
'user_login' => $username, | |
'user_password' => $password, | |
'remember' => false | |
]; | |
$user = wp_signon( $creds, false ); | |
$username = $user->get( 'user_login' ); | |
$_SESSION["success"] = "Welcome $username, you have registered successfully"; | |
return "success"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment