Created
April 19, 2023 19:23
-
-
Save mbmaciel/a83895aaa6eb745d67373bf3de909698 to your computer and use it in GitHub Desktop.
Authentication.php
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 | |
header('Access-Control-Allow-Origin: *'); | |
header('Access-Control-Allow-Methods: GET, POST'); | |
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Cache-Control, Pragma, Authorization, Accept, Accept-Encoding"); | |
require_once('wp-load.php'); | |
function generateRandomString($length = 10) { | |
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; | |
$charactersLength = strlen($characters); | |
$randomString = ''; | |
for ($i = 0; $i < $length; $i++) { | |
$randomString .= $characters[rand(0, $charactersLength - 1)]; | |
} | |
return $randomString; | |
} | |
$response = array( | |
'data' => array(), | |
'msg' => 'Invalid email or password', | |
'status' => false | |
); | |
/* Sanitize all received posts */ | |
foreach($_POST as $k => $value){ | |
$_POST[$k] = sanitize_text_field($value); | |
} | |
/** | |
* Login Method | |
* | |
*/ | |
if( isset( $_POST['type'] ) && $_POST['type'] == 'login' ){ | |
/* Get user data */ | |
$user = get_user_by( 'email', $_POST['email'] ); | |
if ( $user ){ | |
$password_check = wp_check_password( $_POST['password'], $user->user_pass, $user->ID ); | |
if ( $password_check ){ | |
/* Generate a unique auth token */ | |
$token = generateRandomString( 30 ); | |
/* Store / Update auth token in the database */ | |
if( update_user_meta( $user->ID, 'auth_token', $token ) ){ | |
/* Return generated token and user ID*/ | |
$response['status'] = true; | |
$response['data'] = array( | |
'auth_token' => $token, | |
'user_id' => $user->ID, | |
'user_login' => $user->user_login, | |
'first_name' => $user->first_name, | |
'last_name' => $user->last_name, | |
'nickname' => $user->nickname | |
); | |
$response['msg'] = 'Successfully Authenticated'; | |
print_r(json_encode($response['data'])); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment