Files
Sdf1_login/api/gh_oauth.php
T

144 lines
6.3 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
/**
* 15m44l 工单第二批 / 15m44m:GitHub issue 双向同步 —— OAuth 授权端点(玩家逐次授权)
*
* 两个用途:
* 1) 发起授权(GET, 无 code):302 到 GitHub OAuth App 的 authorize 页,state=玩家名(CSRF)。
* 玩家名解析优先级:?token=(validateTokenSilent 反解)→ ?player=(兜底)→ 'anon'。
* 前端只需带自己的 TOKEN 即可,不用知道玩家名。
* 2) 回调(GET, 带 code+state):code+client_secret 换 access_token,state=玩家名,
* 写 web_tickets.gh_access_token(按玩家名),回跳 player.php?gh_ok=1&gh_user=xxx。
*
* 凭据全在 img.json(repo.Client ID / Client secrets + repo.webhook_secret),本文件不含敏感值。
* gh_enabled=false(模式.type≠GitHub)时直接报错,避免误跳。
*
* 给用户配的 2 条 URL 之一:
* OAuth 回调(Redirect URI): https://caoyuan.ypshidifu.cn/plugin/api/gh_oauth.php
*/
while (ob_get_level() > 0) { @ob_end_clean(); }
ob_start();
header('X-Content-Type-Options: nosniff');
error_reporting(E_ALL);
ini_set('display_errors', '0');
if (function_exists('opcache_invalidate')) { @opcache_invalidate(__FILE__); }
require_once __DIR__ . '/../core.php';
require_once __DIR__ . '/../lsky.php';
$cfg = loadImgJson();
if (!$cfg['gh_enabled']) {
header('Content-Type: text/html; charset=utf-8');
echo '<meta charset="utf-8"><title>GitHub 工单同步未启用</title>'
. '<p>GitHub issue 工单同步未启用(img.json 的 模式.type 需填 GitHub)。</p>'
. '<p><a href="javascript:history.back()">返回</a></p>';
exit;
}
$clientId = $cfg['gh_client_id'];
$clientSec = $cfg['gh_client_secret'];
$baseSite = rtrim('https://caoyuan.ypshidifu.cn/plugin', '/');
$oauthUrl = $baseSite . '/api/gh_oauth.php';
$ghAuthorize = 'https://github.com/login/oauth/authorize';
$ghToken = 'https://github.com/login/oauth/access_token';
$code = isset($_GET['code']) ? trim((string)$_GET['code']) : '';
if ($code !== '') {
// ===== 回调:换 token =====
$player = isset($_GET['state']) ? trim((string)$_GET['state']) : '';
$scope = 'repo'; // issue 读+写需要 repo 权限
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $ghToken);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
'client_id' => $clientId,
'client_secret' => $clientSec,
'code' => $code,
'scope' => $scope,
]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
$body = curl_exec($ch);
$errno = curl_errno($ch);
curl_close($ch);
if ($errno) {
header('Content-Type: text/html; charset=utf-8');
echo '<meta charset="utf-8"><p>获取 GitHub token 失败(cURL ' . htmlspecialchars((string)$errno) . ')。</p>';
exit;
}
parse_str((string)$body, $tok);
$accessToken = isset($tok['access_token']) ? (string)$tok['access_token'] : '';
$ghUser = isset($tok['user_login']) ? (string)$tok['user_login'] : '';
if ($accessToken === '') {
$err = isset($tok['error']) ? (string)$tok['error'] : 'unknown';
header('Content-Type: text/html; charset=utf-8');
echo '<meta charset="utf-8"><p>GitHub 授权失败: ' . htmlspecialchars($err) . '。</p>'
. '<p><a href="javascript:history.back()">返回</a></p>';
exit;
}
// 写库:独立表 gh_auth_tokens(玩家名→GitHub access_token),不污染 web_tickets。
// 工单表只留 gh_issue_number 一列(记录已同步的 issue 号),授权 token 单独存。
$db = getDB();
try { $db->exec("ALTER TABLE web_tickets ADD COLUMN gh_issue_number TEXT DEFAULT ''"); } catch (\Throwable $e) {}
try {
$db->exec("CREATE TABLE IF NOT EXISTS gh_auth_tokens (
player_name TEXT PRIMARY KEY,
gh_login TEXT DEFAULT '',
access_token TEXT NOT NULL,
updated_at INTEGER NOT NULL
)");
$up = $db->prepare("INSERT INTO gh_auth_tokens (player_name, gh_login, access_token, updated_at)
VALUES (:p, :l, :t, :now)
ON CONFLICT(player_name) DO UPDATE SET
gh_login = :l2, access_token = :t2, updated_at = :now2");
$up->bindValue(':p', $player, SQLITE3_TEXT);
$up->bindValue(':l', $ghUser, SQLITE3_TEXT);
$up->bindValue(':t', $accessToken, SQLITE3_TEXT);
$up->bindValue(':now', time(), SQLITE3_INTEGER);
$up->bindValue(':l2', $ghUser, SQLITE3_TEXT);
$up->bindValue(':t2', $accessToken, SQLITE3_TEXT);
$up->bindValue(':now2', time(), SQLITE3_INTEGER);
$up->execute();
} catch (\Throwable $e) {
// 老库若不支持 ON CONFLICT,退化:先删后插
try {
$db->exec("DELETE FROM gh_auth_tokens WHERE player_name = '" . str_replace("'", "''", $player) . "'");
$db->exec("INSERT INTO gh_auth_tokens (player_name, gh_login, access_token, updated_at)
VALUES ('" . str_replace("'", "''", $player) . "', '" . str_replace("'", "''", $ghUser) . "',
'" . str_replace("'", "''", $accessToken) . "', " . time() . ")");
} catch (\Throwable $e2) { /* 忽略,回跳仍成功 */ }
}
// 回跳前端工单页,带成功标记
header('Location: ' . $baseSite . '/player.php?gh_ok=1&gh_user=' . urlencode($ghUser));
exit;
}
// ===== 发起授权:解析玩家名(token 优先,player 兜底)=====
$playerName = '';
$tk = isset($_GET['token']) ? trim((string)$_GET['token']) : '';
if ($tk !== '') {
$info = validateTokenSilent($tk);
if ($info && !empty($info['player'])) $playerName = $info['player'];
}
if ($playerName === '' && isset($_GET['player'])) $playerName = trim((string)$_GET['player']);
if ($playerName === '') $playerName = 'anon';
$state = $playerName;
$authUrl = $ghAuthorize . '?' . http_build_query([
'client_id' => $clientId,
'redirect_uri' => $oauthUrl,
'scope' => 'repo',
'state' => $state,
]);
header('Location: ' . $authUrl);
exit;