| 1 |
<?php |
| 2 |
|
| 3 |
namespace Give\DonationForms\Routes; |
| 4 |
|
| 5 |
use Give\DonationForms\Actions\AuthenticateFormRequestWithToken; |
| 6 |
use Give\DonationForms\DataTransferObjects\AuthenticationData; |
| 7 |
use Give\DonationForms\DataTransferObjects\DonateRouteData; |
| 8 |
use Give\DonationForms\DataTransferObjects\UserData; |
| 9 |
use Give\Framework\PaymentGateways\Traits\HandleHttpResponses; |
| 10 |
use WP_User; |
| 11 |
|
| 12 |
/** |
| 13 |
* @since 3.0.0 |
| 14 |
*/ |
| 15 |
class AuthenticationRoute |
| 16 |
{ |
| 17 |
use HandleHttpResponses; |
| 18 |
|
| 19 |
/** |
| 20 |
* @since 4.17.0 Return an auth token so embedded forms can authenticate without cookies. |
| 21 |
* @since 3.0.0 |
| 22 |
* |
| 23 |
* @return void |
| 24 |
*/ |
| 25 |
public function __invoke(array $request) |
| 26 |
{ |
| 27 |
$routeData = DonateRouteData::fromRequest(give_clean($_GET)); |
| 28 |
|
| 29 |
$routeData->validateSignature(); |
| 30 |
|
| 31 |
$user = $this->authenticate(AuthenticationData::fromRequest($request)); |
| 32 |
|
| 33 |
wp_send_json_success( |
| 34 |
get_object_vars(UserData::fromUser($user)) + [ |
| 35 |
AuthenticateFormRequestWithToken::TOKEN_KEY => $this->generateAuthToken($user), |
| 36 |
] |
| 37 |
); |
| 38 |
|
| 39 |
exit; |
| 40 |
} |
| 41 |
|
| 42 |
/** |
| 43 |
* The token is built like an auth cookie: signed by core, session backed, |
| 44 |
* and revoked with the session. It carries the login where the cookie |
| 45 |
* cannot, which is inside a cross-site iframe. Its own salt scheme means |
| 46 |
* it is not usable as a login cookie. |
| 47 |
* |
| 48 |
* @since 4.17.0 |
| 49 |
*/ |
| 50 |
protected function generateAuthToken(WP_User $user): string |
| 51 |
{ |
| 52 |
return wp_generate_auth_cookie($user->ID, time() + HOUR_IN_SECONDS, AuthenticateFormRequestWithToken::SCHEME); |
| 53 |
} |
| 54 |
|
| 55 |
/** |
| 56 |
* @since 3.0.0 |
| 57 |
*/ |
| 58 |
protected function authenticate(AuthenticationData $auth): WP_User |
| 59 |
{ |
| 60 |
$userOrError = wp_signon([ |
| 61 |
'user_login' => $auth->login, |
| 62 |
'user_password' => $auth->password, |
| 63 |
]); |
| 64 |
|
| 65 |
if (is_wp_error($userOrError)) { |
| 66 |
wp_send_json_error([ |
| 67 |
'type' => 'authentication_error', |
| 68 |
'message' => __('The login/password does not match or is incorrect.', 'give'), |
| 69 |
], 401); |
| 70 |
exit; |
| 71 |
} |
| 72 |
|
| 73 |
return $userOrError; |
| 74 |
} |
| 75 |
} |
| 76 |
|