| 1 |
<?php |
| 2 |
|
| 3 |
namespace Give\DonorDashboards\Routes; |
| 4 |
|
| 5 |
use Give\API\RestRoute; |
| 6 |
use WP_REST_Request; |
| 7 |
use WP_REST_Response; |
| 8 |
|
| 9 |
/** |
| 10 |
* @since 2.10.0 |
| 11 |
*/ |
| 12 |
class LoginRoute implements RestRoute |
| 13 |
{ |
| 14 |
|
| 15 |
/** @var string */ |
| 16 |
protected $endpoint = 'donor-dashboard/login'; |
| 17 |
|
| 18 |
/** |
| 19 |
* @inheritDoc |
| 20 |
*/ |
| 21 |
public function registerRoute() |
| 22 |
{ |
| 23 |
register_rest_route( |
| 24 |
'give-api/v2', |
| 25 |
$this->endpoint, |
| 26 |
[ |
| 27 |
[ |
| 28 |
'methods' => 'POST', |
| 29 |
'callback' => [$this, 'handleRequest'], |
| 30 |
'permission_callback' => '__return_true', |
| 31 |
], |
| 32 |
'args' => [ |
| 33 |
'login' => [ |
| 34 |
'type' => 'string', |
| 35 |
'required' => true, |
| 36 |
'sanitize_callback' => 'sanitize_text_field', |
| 37 |
], |
| 38 |
'password' => [ |
| 39 |
'type' => 'string', |
| 40 |
'required' => true, |
| 41 |
'sanitize_callback' => 'sanitize_text_field', |
| 42 |
], |
| 43 |
], |
| 44 |
] |
| 45 |
); |
| 46 |
} |
| 47 |
|
| 48 |
/** |
| 49 |
* Handles login request |
| 50 |
* |
| 51 |
* @since 2.10.0 |
| 52 |
* |
| 53 |
* @param WP_REST_Request $request |
| 54 |
* |
| 55 |
* @return array |
| 56 |
* |
| 57 |
*/ |
| 58 |
public function handleRequest(WP_REST_Request $request) |
| 59 |
{ |
| 60 |
$login = $request->get_param('login'); |
| 61 |
$password = $request->get_param('password'); |
| 62 |
|
| 63 |
$user = get_user_by('login', $login); |
| 64 |
|
| 65 |
if ( ! $user) { |
| 66 |
$user = get_user_by('email', $login); |
| 67 |
} |
| 68 |
|
| 69 |
if ($user) { |
| 70 |
if (wp_check_password($password, $user->user_pass, $user->ID)) { |
| 71 |
give_log_user_in($user->ID, $login, $password); |
| 72 |
|
| 73 |
return new WP_REST_Response( |
| 74 |
[ |
| 75 |
'status' => 200, |
| 76 |
'response' => 'login_successful', |
| 77 |
'body_response' => [ |
| 78 |
'login' => $user->login, |
| 79 |
'id' => $user->ID, |
| 80 |
], |
| 81 |
] |
| 82 |
); |
| 83 |
} else { |
| 84 |
return new WP_REST_Response( |
| 85 |
[ |
| 86 |
'status' => 400, |
| 87 |
'response' => 'incorrect_password', |
| 88 |
'body_response' => [ |
| 89 |
'message' => __('The provided password was incorrect.', 'give'), |
| 90 |
], |
| 91 |
] |
| 92 |
); |
| 93 |
} |
| 94 |
} else { |
| 95 |
return new WP_REST_Response( |
| 96 |
[ |
| 97 |
'status' => 400, |
| 98 |
'response' => 'unidentified_login', |
| 99 |
'body_response' => [ |
| 100 |
'message' => sprintf( |
| 101 |
__('A record for the provided login (%s) could not be found.', 'give'), |
| 102 |
$login |
| 103 |
), |
| 104 |
], |
| 105 |
] |
| 106 |
); |
| 107 |
} |
| 108 |
} |
| 109 |
} |
| 110 |
|