优化了一些问题

This commit is contained in:
2026-08-29 22:03:48 +08:00
parent 1d904e6532
commit 780e1eba21
46 changed files with 4074 additions and 3143 deletions
+374 -414
View File
@@ -7,418 +7,378 @@ namespace AKSRT\Auth;
defined('ABSPATH') || exit;
class OAuth {
use OAuthPart1;
use OAuthPart2;
private static $instance = null;
private function __construct() {}
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('template_redirect', [$this, 'handle_callback']);
add_action('template_redirect', [$this, 'handle_clogin_routes'], 9);
add_action('show_user_profile', [$this, 'profile_bindings'], 10, 1);
add_action('wp_ajax_aksrt_oauth_unbind', [$this, 'ajax_unbind']);
}
public function add_rewrite_rules(): void {
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', function($vars) {
$vars[] = 'aksrt_oauth';
return $vars;
});
}
/**
* 生成OAuth授权URL
*/
public function get_auth_url(string $provider, string $action = 'login'): string {
$provider = sanitize_key($provider);
if (str_starts_with($provider, 'clogin_') || str_starts_with($provider, 'clogin-')) {
$type = str_replace(['clogin_', 'clogin-'], '', $provider);
return $this->get_clogin_login_url($type, $action);
}
if ($provider === 'clogin') {
return $this->get_clogin_login_url('qq', $action);
}
if (class_exists('\AKSRT\Settings\Settings') && \AKSRT\Settings\Settings::oauth_proxy_mode() === 'client') {
if (class_exists('AKSRT\\Auth\\OAuthProxyClient')) {
return OAuthProxyClient::get_instance()->get_proxy_auth_url($provider, $action);
}
return '';
}
$config = $this->get_provider_config($provider);
if (!$config) return '';
$uid = get_current_user_id();
$nonce = wp_create_nonce('aksrt_oauth_' . $provider . '_' . $uid);
$state = ($action === 'bind' && $uid)
? 'bind_' . $provider . '_' . $nonce
: $provider . '_' . $nonce;
$redirect_uri = !empty($config['redirect_uri']) ? $config['redirect_uri'] : home_url('/oauth/callback/');
try {
switch ($provider) {
case 'github':
$oauth = new \Yurun\OAuthLogin\Github\OAuth2(
$config['client_id'],
$config['client_secret'],
$redirect_uri
);
return $oauth->getAuthUrl($redirect_uri, $state);
case 'gitee':
$oauth = new \Yurun\OAuthLogin\Gitee\OAuth2(
$config['client_id'],
$config['client_secret'],
$redirect_uri
);
return $oauth->getAuthUrl($redirect_uri, $state);
case 'qq':
$oauth = new \Yurun\OAuthLogin\QQ\OAuth2(
$config['client_id'],
$config['client_secret'],
$redirect_uri
);
return $oauth->getAuthUrl($redirect_uri, $state);
case 'weibo':
$oauth = new \Yurun\OAuthLogin\Weibo\OAuth2(
$config['client_id'],
$config['client_secret'],
$redirect_uri
);
return $oauth->getAuthUrl($redirect_uri, $state);
case 'weixin':
$oauth = new \Yurun\OAuthLogin\Weixin\OAuth2(
$config['client_id'],
$config['client_secret'],
$redirect_uri
);
return $oauth->getAuthUrl($redirect_uri, $state);
case 'baidu':
$oauth = new \Yurun\OAuthLogin\Baidu\OAuth2(
$config['client_id'],
$config['client_secret'],
$redirect_uri
);
return $oauth->getAuthUrl($redirect_uri, $state);
case 'alipay':
$oauth = new \Yurun\OAuthLogin\Alipay\OAuth2(
$config['client_id'],
$config['client_secret'],
$redirect_uri
);
return $oauth->getAuthUrl($redirect_uri, $state);
case 'google':
return $this->get_google_auth_url($config, $redirect_uri, $state);
case 'weixingzh':
return $this->get_weixingzh_auth_url($config, $redirect_uri, $state);
default:
return '';
}
} catch (\Exception $e) {
return '';
}
}
/**
* 处理OAuth回调 — 路由分发
*/
public function handle_callback(): void {
$provider = $this->resolve_callback_provider();
if ($provider === '' || !in_array($provider, $this->get_enabled_providers())) return;
$error = $_GET['error'] ?? '';
if ($error) {
wp_die(__('登录失败:', 'aksrt') . esc_html($error));
}
$code = $_GET['code'] ?? '';
$state = $_GET['state'] ?? '';
if (empty($code)) {
wp_die(__('OAuth回调缺少授权码', 'aksrt'));
}
$is_bind = strpos($state, 'bind_') === 0;
$rest = $is_bind ? substr($state, 5) : $state;
$sep = strpos($rest, '_');
if ($sep === false || $sep >= strlen($rest) - 1) {
wp_die(__('无效的OAuth状态参数', 'aksrt'));
}
$parsed_provider = sanitize_key(substr($rest, 0, $sep));
if (!in_array($parsed_provider, $this->get_enabled_providers())) {
wp_die(__('未知的OAuth提供商', 'aksrt'));
}
$nonce_state = substr($rest, $sep + 1);
if ($is_bind) {
$this->handle_bind_callback($parsed_provider, $code, $nonce_state);
} else {
$this->handle_login_callback($parsed_provider, $code, $nonce_state);
}
}
private function handle_login_callback(string $provider, string $code, string $nonce): void {
try {
if (!wp_verify_nonce($nonce, "aksrt_oauth_{$provider}_0")) {
throw new \Exception(__('安全验证失败,请重试', 'aksrt'));
}
$user_data = $this->get_user_data($provider, $code);
if (!$user_data || empty($user_data['provider_id'])) {
throw new \Exception(__('无法获取用户信息', 'aksrt'));
}
$user = $this->find_or_create_user($provider, $user_data);
if (is_wp_error($user) && $user->get_error_code() === 'oauth_no_match') {
$error_data = $user->get_error_data();
$obk = 'aksrt_ob_' . wp_generate_password(24, false);
set_transient($obk, [
'provider' => $error_data['provider'],
'provider_id' => $error_data['user_data']['provider_id'] ?? '',
'user_data' => $error_data['user_data'],
], 15 * MINUTE_IN_SECONDS);
$bind_url = aksrt_get_bind_url();
wp_safe_redirect(add_query_arg('obk', $obk, $bind_url));
exit;
}
if (is_wp_error($user)) {
throw new \Exception($user->get_error_message());
}
wp_set_auth_cookie($user->ID, true);
$redirect_url = home_url('/');
if (function_exists('aksrt_get_user_center_url')) {
$redirect_url = aksrt_get_user_center_url();
}
wp_safe_redirect(add_query_arg(['oauth_action' => 'login', 'oauth_bound' => $provider], $redirect_url));
exit;
} catch (\Exception $e) {
wp_die(__('登录失败:', 'aksrt') . '<br>' . esc_html($e->getMessage()));
}
}
private function handle_bind_callback(string $provider, string $code, string $nonce): void {
$current_uid = get_current_user_id();
if (!$current_uid) {
wp_safe_redirect(aksrt_get_login_url());
exit;
}
try {
$expected = wp_create_nonce("aksrt_oauth_{$provider}_{$current_uid}");
if (!hash_equals($expected, $nonce)) {
throw new \Exception(__('安全验证失败,请重试', 'aksrt'));
}
$existing_binding = get_user_meta($current_uid, "aksrt_{$provider}_id", true);
if (!empty($existing_binding)) {
wp_safe_redirect(add_query_arg(['tab' => 'settings', 'oauth_action' => 'bind', 'oauth_bound' => $provider], $this->get_profile_url()));
exit;
}
$user_data = $this->get_user_data($provider, $code);
if (!$user_data || empty($user_data['provider_id'])) {
throw new \Exception(__('无法获取用户信息', 'aksrt'));
}
$existing = $this->find_user_by_provider($provider, $user_data['provider_id'] ?? '');
if ($existing && $existing->ID !== $current_uid) {
throw new \Exception(__('该第三方账号已被其他用户绑定', 'aksrt'));
}
$this->bind_provider_to_user($current_uid, $provider, $user_data);
wp_safe_redirect(add_query_arg(['tab' => 'settings', 'oauth_action' => 'bind', 'oauth_bound' => $provider], $this->get_profile_url()));
exit;
} catch (\Exception $e) {
wp_die(__('绑定失败:', 'aksrt') . '<br>' . esc_html($e->getMessage()));
}
}
/**
* 通过授权码获取用户数据(统一输出格式)
*/
private function get_user_data(string $provider, string $code): array {
$config = $this->get_provider_config($provider);
$redirect_uri = !empty($config['redirect_uri']) ? $config['redirect_uri'] : home_url('/oauth/callback/');
switch ($provider) {
case 'github':
return $this->get_github_user_data($config, $code, $redirect_uri);
case 'gitee':
return $this->get_gitee_user_data($config, $code, $redirect_uri);
case 'qq':
return $this->get_qq_user_data($config, $code, $redirect_uri);
case 'weibo':
return $this->get_weibo_user_data($config, $code, $redirect_uri);
case 'weixin':
return $this->get_weixin_user_data($config, $code, $redirect_uri);
case 'baidu':
return $this->get_baidu_user_data($config, $code, $redirect_uri);
case 'alipay':
return $this->get_alipay_user_data($config, $code, $redirect_uri);
case 'google':
return $this->get_google_user_data($config, $code, $redirect_uri);
case 'weixingzh':
return $this->get_weixingzh_user_data($config, $code, $redirect_uri);
default:
throw new \Exception(__('不支持的OAuth平台:', 'aksrt') . $provider);
}
}
private function get_github_user_data(array $config, string $code, string $redirect_uri): array {
$oauth = new \Yurun\OAuthLogin\Github\OAuth2(
$config['client_id'],
$config['client_secret'],
$redirect_uri
);
$oauth->getAccessToken($_GET['state'] ?? '', $code, $_GET['state'] ?? null);
$userInfo = $oauth->getUserInfo();
// 获取邮箱
$email = $userInfo['email'] ?? '';
if (empty($email)) {
$emails_json = $oauth->http->header('Authorization', ' token ' . $oauth->accessToken)
->get('https://api.github.com/user/emails')
->body();
$emails = json_decode($emails_json, true) ?: [];
foreach ($emails as $em) {
if (!empty($em['primary']) && !empty($em['email'])) {
$email = $em['email'];
break;
}
}
}
return [
'provider' => 'github',
'provider_id' => (string) ($userInfo['id'] ?? ''),
'username' => $userInfo['login'] ?? '',
'name' => $userInfo['name'] ?? '',
'email' => $email,
'avatar_url' => $userInfo['avatar_url'] ?? '',
'url' => $userInfo['html_url'] ?? '',
'bio' => $userInfo['bio'] ?? '',
];
}
private function get_gitee_user_data(array $config, string $code, string $redirect_uri): array {
$oauth = new \Yurun\OAuthLogin\Gitee\OAuth2(
$config['client_id'],
$config['client_secret'],
$redirect_uri
);
$oauth->getAccessToken($_GET['state'] ?? '', $code, $_GET['state'] ?? null);
$userInfo = $oauth->getUserInfo();
return [
'provider' => 'gitee',
'provider_id' => (string) ($userInfo['id'] ?? ''),
'username' => $userInfo['login'] ?? '',
'name' => $userInfo['name'] ?? '',
'email' => $userInfo['email'] ?? '',
'avatar_url' => $userInfo['avatar_url'] ?? '',
'url' => $userInfo['html_url'] ?? '',
'bio' => $userInfo['bio'] ?? '',
];
}
private function get_qq_user_data(array $config, string $code, string $redirect_uri): array {
$oauth = new \Yurun\OAuthLogin\QQ\OAuth2(
$config['client_id'],
$config['client_secret'],
$redirect_uri
);
$oauth->getAccessToken($_GET['state'] ?? '', $code, $_GET['state'] ?? null);
$openid = $oauth->getOpenID();
$userInfo = $oauth->getUserInfo();
return [
'provider' => 'qq',
'provider_id' => $openid,
'username' => $userInfo['nickname'] ?? '',
'name' => $userInfo['nickname'] ?? '',
'email' => '',
'avatar_url' => $userInfo['figureurl_qq_2'] ?? $userInfo['figureurl_2'] ?? $userInfo['figureurl'] ?? '',
'gender' => $userInfo['gender'] ?? '',
];
}
private function get_weibo_user_data(array $config, string $code, string $redirect_uri): array {
$oauth = new \Yurun\OAuthLogin\Weibo\OAuth2(
$config['client_id'],
$config['client_secret'],
$redirect_uri
);
$oauth->getAccessToken($_GET['state'] ?? '', $code, $_GET['state'] ?? null);
$userInfo = $oauth->getUserInfo();
return [
'provider' => 'weibo',
'provider_id' => (string) ($userInfo['id'] ?? ''),
'username' => $userInfo['screen_name'] ?? '',
'name' => $userInfo['name'] ?? '',
'email' => '',
'avatar_url' => $userInfo['avatar_large'] ?? $userInfo['profile_image_url'] ?? '',
'gender' => ($userInfo['gender'] ?? '') === 'm' ? 'male' : (($userInfo['gender'] ?? '') === 'f' ? 'female' : ''),
];
}
private function get_weixin_user_data(array $config, string $code, string $redirect_uri): array {
$oauth = new \Yurun\OAuthLogin\Weixin\OAuth2(
$config['client_id'],
$config['client_secret'],
$redirect_uri
);
$oauth->getAccessToken($_GET['state'] ?? '', $code, $_GET['state'] ?? null);
$userInfo = $oauth->getUserInfo();
return [
'provider' => 'weixin',
'provider_id' => (string) ($userInfo['openid'] ?? ''),
'username' => $userInfo['nickname'] ?? '',
'name' => $userInfo['nickname'] ?? '',
'email' => '',
'avatar_url' => $userInfo['headimgurl'] ?? '',
'gender' => ($userInfo['sex'] ?? 0) == 1 ? 'male' : (($userInfo['sex'] ?? 0) == 2 ? 'female' : ''),
];
}
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;
}
}