| 1 |
<?php |
| 2 |
|
| 3 |
namespace Leadin\auth; |
| 4 |
|
| 5 |
use Leadin\data\User; |
| 6 |
use Leadin\data\Portal_Options; |
| 7 |
use Leadin\auth\OAuthCrypto; |
| 8 |
use Leadin\admin\Routing; |
| 9 |
use Leadin\admin\MenuConstants; |
| 10 |
|
| 11 |
/** |
| 12 |
* Class managing OAuth2 authorization |
| 13 |
*/ |
| 14 |
class OAuth { |
| 15 |
|
| 16 |
/** |
| 17 |
* Authorizes the plugin with given oauth credentials by storing them in the options DB. |
| 18 |
* |
| 19 |
* @param string $refresh_token OAuth refresh token to store. |
| 20 |
*/ |
| 21 |
public static function authorize( $refresh_token ) { |
| 22 |
$encrypted_refresh_token = OAuthCrypto::encrypt( $refresh_token ); |
| 23 |
Portal_Options::set_refresh_token( $encrypted_refresh_token ); |
| 24 |
|
| 25 |
Portal_Options::set_last_authorize_time(); |
| 26 |
} |
| 27 |
|
| 28 |
/** |
| 29 |
* Deauthorizes the plugin by deleting OAuth credentials from the options DB. |
| 30 |
*/ |
| 31 |
public static function deauthorize() { |
| 32 |
Portal_Options::delete_refresh_token(); |
| 33 |
|
| 34 |
Portal_Options::set_last_deauthorize_time(); |
| 35 |
} |
| 36 |
|
| 37 |
/** |
| 38 |
* Attempts to get and decrypt the refresh token. |
| 39 |
* Records an error if decryption fails or if the token is invalid. |
| 40 |
* |
| 41 |
* Note: WordPress sites that are missing keys and salts will have the refresh token stored in plaintext. |
| 42 |
* The decrypt function will return the plaintext token in this case. |
| 43 |
* |
| 44 |
* @return string The result of decrypt function, or an empty string on failure. |
| 45 |
*/ |
| 46 |
public static function get_refresh_token() { |
| 47 |
$encrypted_refresh_token = Portal_Options::get_refresh_token(); |
| 48 |
|
| 49 |
if ( ! self::is_valid_value( $encrypted_refresh_token ) ) { |
| 50 |
return ''; |
| 51 |
} |
| 52 |
|
| 53 |
$refresh_token = OAuthCrypto::decrypt( $encrypted_refresh_token ); |
| 54 |
|
| 55 |
if ( ! self::is_valid_value( $refresh_token ) ) { |
| 56 |
return false; |
| 57 |
} |
| 58 |
|
| 59 |
return $refresh_token; |
| 60 |
} |
| 61 |
|
| 62 |
/** |
| 63 |
* Checks if the provided value is valid (not false, null, or empty). |
| 64 |
* |
| 65 |
* @param mixed $value The value to check. |
| 66 |
* @return bool Whether the value is valid. |
| 67 |
*/ |
| 68 |
private static function is_valid_value( $value ) { |
| 69 |
return false !== $value && null !== $value && '' !== $value; |
| 70 |
} |
| 71 |
} |
| 72 |
|