| 1 |
<?php |
| 2 |
|
| 3 |
namespace Give\DonationForms\Actions; |
| 4 |
|
| 5 |
/** |
| 6 |
* Signs the donor in for a donate or validate request from a signed auth |
| 7 |
* token instead of the login cookie. |
| 8 |
* |
| 9 |
* A donation form embedded on another website cannot rely on cookies: the |
| 10 |
* browser drops WordPress auth cookies set from a cross-site iframe response. |
| 11 |
* The authentication route therefore also returns a token built with the same |
| 12 |
* core functions as the auth cookie, which WordPress signs, expires, and backs |
| 13 |
* with a session token, under a plugin-specific scheme. The form sends it back |
| 14 |
* with the donation and the route validates it the same way core validates |
| 15 |
* the cookie. |
| 16 |
* |
| 17 |
* This runs from the two form routes rather than on determine_current_user so |
| 18 |
* it works even when another plugin resolves the current user before this |
| 19 |
* plugin has loaded, and so the token is never accepted anywhere else. |
| 20 |
* |
| 21 |
* @since 4.17.0 |
| 22 |
*/ |
| 23 |
class AuthenticateFormRequestWithToken |
| 24 |
{ |
| 25 |
/** |
| 26 |
* The request key the form sends the token under. The authentication |
| 27 |
* route returns it under the same key. |
| 28 |
* |
| 29 |
* @since 4.17.0 |
| 30 |
*/ |
| 31 |
public const TOKEN_KEY = 'authToken'; |
| 32 |
|
| 33 |
/** |
| 34 |
* A plugin-specific salt scheme. WordPress derives the salt from the scheme |
| 35 |
* name, so the token verifies only here and is never a valid login cookie |
| 36 |
* if it leaks. |
| 37 |
* |
| 38 |
* @since 4.17.0 |
| 39 |
*/ |
| 40 |
public const SCHEME = 'givewp_embedded_form'; |
| 41 |
|
| 42 |
/** |
| 43 |
* @since 4.17.0 |
| 44 |
*/ |
| 45 |
public function __invoke(array $request): void |
| 46 |
{ |
| 47 |
if (is_user_logged_in()) { |
| 48 |
return; |
| 49 |
} |
| 50 |
|
| 51 |
$token = $request[self::TOKEN_KEY] ?? ''; |
| 52 |
|
| 53 |
if (!is_string($token) || $token === '') { |
| 54 |
return; |
| 55 |
} |
| 56 |
|
| 57 |
/* |
| 58 |
* Core extends the expiry by an hour for POST requests, which is meant |
| 59 |
* for a form that sat open in a browser. This token is a short-lived |
| 60 |
* credential, so its own expiry is the limit. |
| 61 |
*/ |
| 62 |
$parts = wp_parse_auth_cookie($token); |
| 63 |
|
| 64 |
if (!$parts || (int)$parts['expiration'] < time()) { |
| 65 |
return; |
| 66 |
} |
| 67 |
|
| 68 |
$userId = wp_validate_auth_cookie($token, self::SCHEME); |
| 69 |
|
| 70 |
if ($userId) { |
| 71 |
wp_set_current_user($userId); |
| 72 |
} |
| 73 |
} |
| 74 |
} |
| 75 |
|