385 lines
15 KiB
PHP
385 lines
15 KiB
PHP
<?php
|
|
/**
|
|
* @package AKSRT
|
|
*/
|
|
|
|
namespace AKSRT\Auth;
|
|
|
|
defined('ABSPATH') || exit;
|
|
|
|
final class OAuth {
|
|
|
|
private static $instance = null;
|
|
private OAuthProviderBroker $broker;
|
|
|
|
private function __construct() {
|
|
$this->broker = new OAuthProviderBroker();
|
|
}
|
|
|
|
public static function get_instance(): self {
|
|
if (null === self::$instance) {
|
|
self::$instance = new self();
|
|
}
|
|
return self::$instance;
|
|
}
|
|
|
|
public function init(): void {
|
|
add_action('init', [$this, 'add_rewrite_rules']);
|
|
add_action('init', [$this, 'maybe_flush_rewrite_rules'], 20);
|
|
add_action('init', static function (): void {
|
|
if (wp_rand(1, 100) === 1) {
|
|
OAuthTransactionStore::cleanup();
|
|
}
|
|
}, 30);
|
|
add_action('template_redirect', [$this, 'handle_routes'], 8);
|
|
add_action('wp_ajax_aksrt_oauth_unbind', [$this, 'ajax_unbind']);
|
|
}
|
|
|
|
public function add_rewrite_rules(): void {
|
|
add_rewrite_rule('^oauth/start/([a-z0-9_-]+)/?$', 'index.php?aksrt_oauth=start&aksrt_oauth_provider=$matches[1]', 'top');
|
|
add_rewrite_rule('^oauth/callback/?$', 'index.php?aksrt_oauth=callback', 'top');
|
|
add_rewrite_rule('^oauth/clogin/?$', 'index.php?aksrt_oauth=clogin', 'top');
|
|
add_rewrite_rule('^oauth/clogin/callback/?$', 'index.php?aksrt_oauth=clogin_callback', 'top');
|
|
add_filter('query_vars', static function (array $vars): array {
|
|
$vars[] = 'aksrt_oauth';
|
|
$vars[] = 'aksrt_oauth_provider';
|
|
return $vars;
|
|
});
|
|
}
|
|
|
|
public function maybe_flush_rewrite_rules(): void {
|
|
$version = defined('AKSRT_VERSION') ? AKSRT_VERSION . ':oauth-v2' : 'oauth-v2';
|
|
if (get_option('aksrt_oauth_routes_flushed') !== $version) {
|
|
flush_rewrite_rules(false);
|
|
update_option('aksrt_oauth_routes_flushed', $version, false);
|
|
}
|
|
}
|
|
|
|
public function handle_routes(): void {
|
|
$route = sanitize_key((string) get_query_var('aksrt_oauth'));
|
|
if ($route === '') {
|
|
return;
|
|
}
|
|
switch ($route) {
|
|
case 'start':
|
|
$this->handle_start();
|
|
break;
|
|
case 'callback':
|
|
$this->handle_callback();
|
|
break;
|
|
case 'clogin':
|
|
$this->handle_clogin_start();
|
|
break;
|
|
case 'clogin_callback':
|
|
$this->handle_clogin_callback();
|
|
break;
|
|
}
|
|
}
|
|
|
|
public function get_auth_url(string $provider, string $action = 'login'): string {
|
|
$provider = sanitize_key($provider);
|
|
$action = $action === 'bind' ? 'bind' : 'login';
|
|
if (!in_array($provider, OAuthProviderCatalog::enabled_login_keys(), true)) {
|
|
return '';
|
|
}
|
|
$redirect = isset($_GET['redirect_to'])
|
|
? OAuthUrlPolicy::validated_redirect((string) wp_unslash($_GET['redirect_to']), home_url('/'))
|
|
: '';
|
|
if ($provider === 'weixingzh') {
|
|
$url = function_exists('aksrt_get_sign_page_url') ? aksrt_get_sign_page_url('oauth') : home_url('/sign/?tab=oauth');
|
|
$url = add_query_arg('oauth_intent', $action, $url);
|
|
return $redirect !== '' ? add_query_arg('redirect_to', $redirect, $url) : $url;
|
|
}
|
|
if (str_starts_with($provider, 'clogin_')) {
|
|
$url = add_query_arg([
|
|
'type' => substr($provider, 7),
|
|
'action' => $action,
|
|
], home_url('/oauth/clogin/'));
|
|
return $redirect !== '' ? add_query_arg('redirect_to', $redirect, $url) : $url;
|
|
}
|
|
$url = add_query_arg('action', $action, home_url('/oauth/start/' . $provider . '/'));
|
|
return $redirect !== '' ? add_query_arg('redirect_to', $redirect, $url) : $url;
|
|
}
|
|
|
|
public function get_auth_providers_data(): array {
|
|
$result = [];
|
|
foreach (OAuthProviderCatalog::enabled_login_keys() as $provider) {
|
|
$url = $this->get_auth_url($provider);
|
|
if ($url === '') {
|
|
continue;
|
|
}
|
|
$result[] = [
|
|
'name' => $provider,
|
|
'label' => OAuthProviderCatalog::label($provider),
|
|
'icon' => function_exists('aksrt_brand_icon') ? aksrt_brand_icon(OAuthProviderCatalog::icon_key($provider)) : '',
|
|
'url' => esc_url($url),
|
|
];
|
|
}
|
|
return $result;
|
|
}
|
|
|
|
public function render_social_buttons(string $title = ''): string {
|
|
$items = $this->get_auth_providers_data();
|
|
if ($items === []) {
|
|
return '';
|
|
}
|
|
ob_start();
|
|
?>
|
|
<div class="social-login-divider">
|
|
<span><?php echo esc_html($title) ?: esc_html__('or', 'aksrt'); ?></span>
|
|
</div>
|
|
<div class="oauth-row">
|
|
<?php foreach ($items as $item) : ?>
|
|
<a href="<?php echo esc_url((string) $item['url']); ?>"
|
|
class="oauth-btn oauth-btn--<?php echo esc_attr((string) $item['name']); ?>"
|
|
data-provider="<?php echo esc_attr((string) $item['name']); ?>"
|
|
aria-label="<?php echo esc_attr((string) $item['label']); ?>"
|
|
title="<?php echo esc_attr((string) $item['label']); ?>">
|
|
<?php echo $item['icon']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
|
|
</a>
|
|
<?php endforeach; ?>
|
|
</div>
|
|
<?php
|
|
return (string) ob_get_clean();
|
|
}
|
|
|
|
public function get_frontend_bindings_data(int $user_id): array {
|
|
$bound = OAuthAccountService::bindings($user_id);
|
|
$bindings = [];
|
|
foreach ($bound as $provider) {
|
|
$bindings[] = $this->binding_row($provider, true);
|
|
}
|
|
$available = [];
|
|
foreach (OAuthProviderCatalog::enabled_login_keys() as $provider) {
|
|
if (in_array($provider, $bound, true)) {
|
|
continue;
|
|
}
|
|
$url = $this->get_auth_url($provider, 'bind');
|
|
if ($url !== '') {
|
|
$row = $this->binding_row($provider, false);
|
|
$row['url'] = $url;
|
|
$available[] = $row;
|
|
}
|
|
}
|
|
return ['bindings' => $bindings, 'available' => $available];
|
|
}
|
|
|
|
public function ajax_unbind(): void {
|
|
check_ajax_referer('aksrt_oauth_unbind', 'nonce');
|
|
$provider = sanitize_key((string) ($_POST['provider'] ?? ''));
|
|
$user_id = isset($_POST['userId']) ? (int) $_POST['userId'] : 0;
|
|
$current_id = get_current_user_id();
|
|
if ($current_id <= 0 || $current_id !== $user_id || !current_user_can('read')) {
|
|
wp_send_json_error(['message' => __('无权执行此操作', 'aksrt')], 403);
|
|
}
|
|
$result = OAuthAccountService::unbind($current_id, $provider);
|
|
if (is_wp_error($result)) {
|
|
$status = $result->get_error_code() === 'oauth_last_login_method' ? 409 : 400;
|
|
wp_send_json_error(['message' => $result->get_error_message()], $status);
|
|
}
|
|
wp_send_json_success(['unbound' => true, 'message' => __('解除绑定成功', 'aksrt')]);
|
|
}
|
|
|
|
private function handle_start(): void {
|
|
$provider = sanitize_key((string) get_query_var('aksrt_oauth_provider'));
|
|
$action = isset($_GET['action']) && sanitize_key((string) $_GET['action']) === 'bind' ? 'bind' : 'login';
|
|
if (!OAuthProviderCatalog::master_enabled() || !in_array($provider, OAuthProviderCatalog::enabled_login_keys(), true)) {
|
|
$this->redirect_error('provider_disabled', $provider, $action);
|
|
}
|
|
if (OAuthProviderCatalog::proxy_mode() === 'client') {
|
|
$url = OAuthProxyClient::get_instance()->get_proxy_auth_url($provider, $action);
|
|
if ($url === '') {
|
|
$this->redirect_error('proxy_config', $provider, $action);
|
|
}
|
|
wp_redirect($url); // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect
|
|
exit;
|
|
}
|
|
$user_id = get_current_user_id();
|
|
if ($action === 'bind' && $user_id <= 0) {
|
|
wp_safe_redirect(function_exists('aksrt_get_login_url') ? aksrt_get_login_url() : wp_login_url());
|
|
exit;
|
|
}
|
|
$redirect = isset($_GET['redirect_to']) ? OAuthUrlPolicy::validated_redirect((string) $_GET['redirect_to'], home_url('/')) : home_url('/');
|
|
$redirect_uri = home_url('/oauth/callback/');
|
|
try {
|
|
$state = OAuthTransactionStore::issue('direct', [
|
|
'provider' => $provider,
|
|
'action' => $action,
|
|
'user_id' => $user_id,
|
|
'redirect_to' => $redirect,
|
|
'redirect_uri' => $redirect_uri,
|
|
], 10 * MINUTE_IN_SECONDS);
|
|
wp_redirect($this->broker->auth_url($provider, $redirect_uri, $state)); // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect
|
|
exit;
|
|
} catch (\Throwable $e) {
|
|
$this->redirect_error('provider_unavailable', $provider, $action);
|
|
}
|
|
}
|
|
|
|
private function handle_callback(): void {
|
|
$state = sanitize_text_field((string) ($_GET['state'] ?? ''));
|
|
$row = $state !== '' ? OAuthTransactionStore::claim($state, 'direct') : null;
|
|
$payload = is_array($row['payload'] ?? null) ? $row['payload'] : [];
|
|
$provider = sanitize_key((string) ($payload['provider'] ?? ''));
|
|
$action = (string) ($payload['action'] ?? 'login');
|
|
if (!$row || !OAuthProviderCatalog::is_direct($provider)) {
|
|
$this->redirect_error('state_invalid', $provider, $action);
|
|
}
|
|
if ($action === 'bind' && (int) ($payload['user_id'] ?? 0) !== get_current_user_id()) {
|
|
$this->redirect_error('state_user_mismatch', $provider, $action);
|
|
}
|
|
if (!empty($_GET['error'])) {
|
|
$this->redirect_error('provider_cancelled', $provider, $action);
|
|
}
|
|
$code = sanitize_text_field((string) ($_GET['code'] ?? ''));
|
|
if ($code === '') {
|
|
$this->redirect_error('code_missing', $provider, $action);
|
|
}
|
|
try {
|
|
$identity = $this->broker->identity($provider, $code, (string) $payload['redirect_uri'], $state);
|
|
if (empty($identity['provider_id'])) {
|
|
throw new \RuntimeException('missing_provider_id');
|
|
}
|
|
if ($action === 'bind') {
|
|
$result = OAuthAccountService::bind(get_current_user_id(), $provider, $identity);
|
|
if (is_wp_error($result)) {
|
|
throw new \RuntimeException($result->get_error_code());
|
|
}
|
|
$this->redirect_success('bind', $provider, function_exists('aksrt_get_user_center_url') ? aksrt_get_user_center_url('settings') : home_url('/'));
|
|
}
|
|
$this->complete_identity_login($provider, $identity, (string) ($payload['redirect_to'] ?? home_url('/')));
|
|
} catch (\Throwable $e) {
|
|
$this->redirect_error($e->getMessage() === 'oauth_binding_conflict' ? 'binding_conflict' : 'callback_failed', $provider, $action);
|
|
}
|
|
}
|
|
|
|
private function handle_clogin_start(): void {
|
|
$config = OAuthProviderCatalog::clogin_settings();
|
|
$type = sanitize_key((string) ($_GET['type'] ?? ''));
|
|
$action = sanitize_key((string) ($_GET['action'] ?? '')) === 'bind' ? 'bind' : 'login';
|
|
if (!$config['enabled'] || !in_array($type, $config['types'], true)) {
|
|
$this->redirect_error('provider_disabled', 'clogin_' . $type, $action);
|
|
}
|
|
if ($action === 'bind' && !is_user_logged_in()) {
|
|
wp_safe_redirect(function_exists('aksrt_get_login_url') ? aksrt_get_login_url() : wp_login_url());
|
|
exit;
|
|
}
|
|
$redirect = isset($_GET['redirect_to']) ? OAuthUrlPolicy::validated_redirect((string) $_GET['redirect_to'], home_url('/')) : home_url('/');
|
|
try {
|
|
$state = OAuthTransactionStore::issue('clogin', [
|
|
'type' => $type,
|
|
'action' => $action,
|
|
'user_id' => get_current_user_id(),
|
|
'redirect_to' => $redirect,
|
|
], 10 * MINUTE_IN_SECONDS);
|
|
$client = new CLoginClient([
|
|
'apiurl' => $config['url'],
|
|
'appid' => $config['id'],
|
|
'appkey' => $config['key'],
|
|
'callback' => home_url('/oauth/clogin/callback/'),
|
|
]);
|
|
$response = $client->login($type, $state);
|
|
if (!empty($response['code']) || empty($response['url'])) {
|
|
throw new \RuntimeException('clogin_unavailable');
|
|
}
|
|
wp_redirect((string) $response['url']); // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect
|
|
exit;
|
|
} catch (\Throwable $e) {
|
|
$this->redirect_error('provider_unavailable', 'clogin_' . $type, $action);
|
|
}
|
|
}
|
|
|
|
private function handle_clogin_callback(): void {
|
|
$state = sanitize_text_field((string) ($_GET['state'] ?? ''));
|
|
$row = $state !== '' ? OAuthTransactionStore::claim($state, 'clogin') : null;
|
|
$payload = is_array($row['payload'] ?? null) ? $row['payload'] : [];
|
|
$type = sanitize_key((string) ($payload['type'] ?? ''));
|
|
$provider = 'clogin_' . $type;
|
|
$action = (string) ($payload['action'] ?? 'login');
|
|
if (!$row || !in_array($type, OAuthProviderCatalog::clogin_settings()['types'], true)) {
|
|
$this->redirect_error('state_invalid', $provider, $action);
|
|
}
|
|
if ($action === 'bind' && (int) ($payload['user_id'] ?? 0) !== get_current_user_id()) {
|
|
$this->redirect_error('state_user_mismatch', $provider, $action);
|
|
}
|
|
$code = sanitize_text_field((string) ($_GET['code'] ?? ''));
|
|
if ($code === '') {
|
|
$this->redirect_error('code_missing', $provider, $action);
|
|
}
|
|
$config = OAuthProviderCatalog::clogin_settings();
|
|
$client = new CLoginClient(['apiurl' => $config['url'], 'appid' => $config['id'], 'appkey' => $config['key']]);
|
|
$info = $client->callback($code);
|
|
$returned_type = $client->from_api_type((string) ($info['type'] ?? ''));
|
|
if ((isset($info['code']) && (int) $info['code'] !== 0) || $returned_type !== $type || empty($info['social_uid'])) {
|
|
$this->redirect_error('callback_failed', $provider, $action);
|
|
}
|
|
$identity = [
|
|
'provider' => $provider,
|
|
'provider_id' => (string) $info['social_uid'],
|
|
'username' => sanitize_text_field((string) ($info['nickname'] ?? '')),
|
|
'name' => sanitize_text_field((string) ($info['nickname'] ?? '')),
|
|
'email' => '',
|
|
'email_verified' => false,
|
|
'avatar_url' => esc_url_raw((string) ($info['faceimg'] ?? '')),
|
|
];
|
|
if ($action === 'bind') {
|
|
$result = OAuthAccountService::bind(get_current_user_id(), $provider, $identity);
|
|
if (is_wp_error($result)) {
|
|
$this->redirect_error('binding_conflict', $provider, $action);
|
|
}
|
|
$this->redirect_success('bind', $provider, function_exists('aksrt_get_user_center_url') ? aksrt_get_user_center_url('settings') : home_url('/'));
|
|
}
|
|
$this->complete_identity_login($provider, $identity, (string) ($payload['redirect_to'] ?? home_url('/')));
|
|
}
|
|
|
|
private function complete_identity_login(string $provider, array $identity, string $redirect): void {
|
|
$user = OAuthAccountService::resolve($provider, $identity);
|
|
if (is_wp_error($user) && $user->get_error_code() === 'oauth_no_match') {
|
|
$obk = OAuthTransactionStore::issue('obk', [
|
|
'provider' => $provider,
|
|
'provider_id' => (string) ($identity['provider_id'] ?? ''),
|
|
'user_data' => $identity,
|
|
'redirect_to' => OAuthUrlPolicy::validated_redirect($redirect, home_url('/')),
|
|
], 15 * MINUTE_IN_SECONDS);
|
|
$url = function_exists('aksrt_get_bind_url') ? aksrt_get_bind_url($obk) : home_url('/sign/?tab=bind&obk=' . rawurlencode($obk));
|
|
wp_safe_redirect($url);
|
|
exit;
|
|
}
|
|
if (!$user instanceof \WP_User) {
|
|
$this->redirect_error('account_match_failed', $provider, 'login');
|
|
}
|
|
OAuthAccountService::complete_login($user, true);
|
|
$this->redirect_success('login', $provider, OAuthUrlPolicy::validated_redirect($redirect, home_url('/')));
|
|
}
|
|
|
|
private function binding_row(string $provider, bool $bound): array {
|
|
return [
|
|
'key' => $provider,
|
|
'name' => OAuthProviderCatalog::label($provider),
|
|
'icon' => function_exists('aksrt_brand_icon') ? aksrt_brand_icon(OAuthProviderCatalog::icon_key($provider)) : '',
|
|
'is_bound' => $bound,
|
|
'url' => '',
|
|
];
|
|
}
|
|
|
|
private function redirect_success(string $action, string $provider, string $target): void {
|
|
wp_safe_redirect(add_query_arg([
|
|
'oauth_action' => $action,
|
|
'oauth_provider' => $provider,
|
|
], $target));
|
|
exit;
|
|
}
|
|
|
|
private function redirect_error(string $code, string $provider = '', string $action = 'login'): void {
|
|
$target = $action === 'bind' && is_user_logged_in() && function_exists('aksrt_get_user_center_url')
|
|
? aksrt_get_user_center_url('settings')
|
|
: (function_exists('aksrt_get_login_url') ? aksrt_get_login_url() : wp_login_url());
|
|
wp_safe_redirect(add_query_arg([
|
|
'oauth_action' => 'error',
|
|
'oauth_provider' => sanitize_key($provider),
|
|
'oauth_error' => sanitize_key($code),
|
|
], $target));
|
|
exit;
|
|
}
|
|
}
|