liuzhao521 commited on
Commit
15bfd5e
·
1 Parent(s): 8f3a455

Add OAuth login support for Hugging Face Spaces

Browse files
Files changed (2) hide show
  1. src/oauth/routes.js +209 -0
  2. src/server/index.js +4 -0
src/oauth/routes.js ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Router } from 'express';
2
+ import https from 'https';
3
+ import crypto from 'crypto';
4
+ import fs from 'fs';
5
+ import path from 'path';
6
+ import logger from '../utils/logger.js';
7
+
8
+ const router = Router();
9
+
10
+ const CLIENT_ID = '1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com';
11
+ const CLIENT_SECRET = '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';
12
+ const ACCOUNTS_FILE = path.join(process.cwd(), 'data', 'accounts.json');
13
+
14
+ const SCOPES = [
15
+ 'https://www.googleapis.com/auth/cloud-platform',
16
+ 'https://www.googleapis.com/auth/userinfo.email',
17
+ 'https://www.googleapis.com/auth/userinfo.profile',
18
+ 'https://www.googleapis.com/auth/cclog',
19
+ 'https://www.googleapis.com/auth/experimentsandconfigs'
20
+ ];
21
+
22
+ // 存储 state 用于验证
23
+ const pendingStates = new Map();
24
+
25
+ // 获取回调基础 URL
26
+ function getBaseUrl(req) {
27
+ // 优先使用环境变量
28
+ if (process.env.OAUTH_CALLBACK_URL) {
29
+ return process.env.OAUTH_CALLBACK_URL;
30
+ }
31
+ // 从请求中推断
32
+ const protocol = req.headers['x-forwarded-proto'] || req.protocol || 'http';
33
+ const host = req.headers['x-forwarded-host'] || req.headers.host;
34
+ return `${protocol}://${host}`;
35
+ }
36
+
37
+ // 生成授权 URL
38
+ router.get('/login', (req, res) => {
39
+ const state = crypto.randomUUID();
40
+ const baseUrl = getBaseUrl(req);
41
+ const redirectUri = `${baseUrl}/oauth-callback`;
42
+
43
+ // 保存 state,5分钟过期
44
+ pendingStates.set(state, { redirectUri, timestamp: Date.now() });
45
+ setTimeout(() => pendingStates.delete(state), 5 * 60 * 1000);
46
+
47
+ const params = new URLSearchParams({
48
+ access_type: 'offline',
49
+ client_id: CLIENT_ID,
50
+ prompt: 'consent',
51
+ redirect_uri: redirectUri,
52
+ response_type: 'code',
53
+ scope: SCOPES.join(' '),
54
+ state: state
55
+ });
56
+
57
+ const authUrl = `https://accounts.google.com/o/oauth2/v2/auth?${params.toString()}`;
58
+
59
+ // 返回 HTML 页面,用户点击后跳转
60
+ res.send(`
61
+ <!DOCTYPE html>
62
+ <html>
63
+ <head>
64
+ <meta charset="utf-8">
65
+ <title>Google 账号登录</title>
66
+ <style>
67
+ body { font-family: system-ui; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background: #f5f5f5; }
68
+ .container { text-align: center; background: white; padding: 40px; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
69
+ h1 { color: #333; margin-bottom: 20px; }
70
+ p { color: #666; margin-bottom: 30px; }
71
+ a { display: inline-block; background: #4285f4; color: white; padding: 12px 32px; border-radius: 6px; text-decoration: none; font-weight: 500; }
72
+ a:hover { background: #3367d6; }
73
+ .info { font-size: 12px; color: #999; margin-top: 20px; }
74
+ </style>
75
+ </head>
76
+ <body>
77
+ <div class="container">
78
+ <h1>🚀 添加 Google 账号</h1>
79
+ <p>点击下方按钮使用 Google 账号授权</p>
80
+ <a href="${authUrl}">使用 Google 登录</a>
81
+ <p class="info">回调地址: ${redirectUri}</p>
82
+ </div>
83
+ </body>
84
+ </html>
85
+ `);
86
+ });
87
+
88
+ // OAuth 回调处理
89
+ router.get('/oauth-callback', async (req, res) => {
90
+ const { code, state, error } = req.query;
91
+
92
+ if (error) {
93
+ logger.error('OAuth 授权失败:', error);
94
+ return res.send('<h1>授权失败</h1><p>' + error + '</p>');
95
+ }
96
+
97
+ if (!code) {
98
+ return res.send('<h1>授权失败</h1><p>未收到授权码</p>');
99
+ }
100
+
101
+ // 验证 state
102
+ const stateData = pendingStates.get(state);
103
+ if (!stateData) {
104
+ logger.warn('无效的 state 参数,可能是过期或重复使用');
105
+ // 尝试从当前请求推断 redirect_uri
106
+ }
107
+
108
+ const redirectUri = stateData?.redirectUri || `${getBaseUrl(req)}/oauth-callback`;
109
+ pendingStates.delete(state);
110
+
111
+ try {
112
+ logger.info('收到授权码,正在交换 Token...');
113
+ const tokenData = await exchangeCodeForToken(code, redirectUri);
114
+
115
+ const account = {
116
+ access_token: tokenData.access_token,
117
+ refresh_token: tokenData.refresh_token,
118
+ expires_in: tokenData.expires_in,
119
+ timestamp: Date.now()
120
+ };
121
+
122
+ // 保存到 accounts.json
123
+ let accounts = [];
124
+ try {
125
+ if (fs.existsSync(ACCOUNTS_FILE)) {
126
+ accounts = JSON.parse(fs.readFileSync(ACCOUNTS_FILE, 'utf-8'));
127
+ }
128
+ } catch (err) {
129
+ logger.warn('读取 accounts.json 失败,将创建新文件');
130
+ }
131
+
132
+ accounts.push(account);
133
+
134
+ const dir = path.dirname(ACCOUNTS_FILE);
135
+ if (!fs.existsSync(dir)) {
136
+ fs.mkdirSync(dir, { recursive: true });
137
+ }
138
+
139
+ fs.writeFileSync(ACCOUNTS_FILE, JSON.stringify(accounts, null, 2));
140
+ logger.info(`Token 已保存,当前共 ${accounts.length} 个账号`);
141
+
142
+ res.send(`
143
+ <!DOCTYPE html>
144
+ <html>
145
+ <head>
146
+ <meta charset="utf-8">
147
+ <title>授权成功</title>
148
+ <style>
149
+ body { font-family: system-ui; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background: #f5f5f5; }
150
+ .container { text-align: center; background: white; padding: 40px; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
151
+ h1 { color: #4caf50; }
152
+ p { color: #666; }
153
+ </style>
154
+ </head>
155
+ <body>
156
+ <div class="container">
157
+ <h1>✅ 授权成功!</h1>
158
+ <p>账号已添加,当前共 ${accounts.length} 个账号</p>
159
+ <p><a href="/">返回首页</a></p>
160
+ </div>
161
+ </body>
162
+ </html>
163
+ `);
164
+ } catch (err) {
165
+ logger.error('Token 交换失败:', err.message);
166
+ res.send(`<h1>Token 获取失败</h1><p>${err.message}</p>`);
167
+ }
168
+ });
169
+
170
+ // 交换授权码获取 Token
171
+ function exchangeCodeForToken(code, redirectUri) {
172
+ return new Promise((resolve, reject) => {
173
+ const postData = new URLSearchParams({
174
+ code: code,
175
+ client_id: CLIENT_ID,
176
+ client_secret: CLIENT_SECRET,
177
+ redirect_uri: redirectUri,
178
+ grant_type: 'authorization_code'
179
+ }).toString();
180
+
181
+ const options = {
182
+ hostname: 'oauth2.googleapis.com',
183
+ path: '/token',
184
+ method: 'POST',
185
+ headers: {
186
+ 'Content-Type': 'application/x-www-form-urlencoded',
187
+ 'Content-Length': Buffer.byteLength(postData)
188
+ }
189
+ };
190
+
191
+ const req = https.request(options, (res) => {
192
+ let body = '';
193
+ res.on('data', chunk => body += chunk);
194
+ res.on('end', () => {
195
+ if (res.statusCode === 200) {
196
+ resolve(JSON.parse(body));
197
+ } else {
198
+ reject(new Error(`HTTP ${res.statusCode}: ${body}`));
199
+ }
200
+ });
201
+ });
202
+
203
+ req.on('error', reject);
204
+ req.write(postData);
205
+ req.end();
206
+ });
207
+ }
208
+
209
+ export default router;
src/server/index.js CHANGED
@@ -9,6 +9,7 @@ import config from '../config/config.js';
9
  import adminRoutes, { incrementRequestCount, addLog } from '../admin/routes.js';
10
  import { validateKey, checkRateLimit } from '../admin/key_manager.js';
11
  import idleManager from '../utils/idle_manager.js';
 
12
 
13
  const __filename = fileURLToPath(import.meta.url);
14
  const __dirname = path.dirname(__filename);
@@ -119,6 +120,9 @@ app.use(async (req, res, next) => {
119
  // 管理路由
120
  app.use('/admin', adminRoutes);
121
 
 
 
 
122
  app.get('/v1/models', async (req, res) => {
123
  try {
124
  const models = await getAvailableModels();
 
9
  import adminRoutes, { incrementRequestCount, addLog } from '../admin/routes.js';
10
  import { validateKey, checkRateLimit } from '../admin/key_manager.js';
11
  import idleManager from '../utils/idle_manager.js';
12
+ import oauthRoutes from '../oauth/routes.js';
13
 
14
  const __filename = fileURLToPath(import.meta.url);
15
  const __dirname = path.dirname(__filename);
 
120
  // 管理路由
121
  app.use('/admin', adminRoutes);
122
 
123
+ // OAuth 路由 (登录和回调)
124
+ app.use('/', oauthRoutes);
125
+
126
  app.get('/v1/models', async (req, res) => {
127
  try {
128
  const models = await getAvailableModels();