auth.js
8.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
/**
* Auth Routes — 用户注册/登录/OAuth
*
* POST /api/auth/register 邮箱+密码注册
* POST /api/auth/login 邮箱+密码登录
* POST /api/auth/logout 退出
* GET /api/auth/me 当前用户
* GET /api/auth/github GitHub OAuth redirect
* GET /api/auth/github/callback
* GET /api/auth/google Google OAuth redirect
* GET /api/auth/google/callback
*/
const express = require('express');
const bcrypt = require('bcryptjs');
const router = express.Router();
const userDb = require('../services/user-db');
const { signAndSetCookie, clearCookie, requireAuth, optionalAuth } = require('../middleware/jwt-auth');
const SALT_ROUNDS = 10;
// ═══════════════════════════════════════
// Email + Password
// ═══════════════════════════════════════
/**
* POST /api/auth/register
*/
router.post('/register', async (req, res) => {
try {
const { email, password, displayName } = req.body;
if (!email || !password) {
return res.status(400).json({ error: 'email and password are required' });
}
if (password.length < 6) {
return res.status(400).json({ error: 'Password must be at least 6 characters' });
}
// Email format check
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
return res.status(400).json({ error: 'Invalid email format' });
}
// Check existing
const existing = userDb.findByEmail(email);
if (existing) {
return res.status(409).json({ error: 'Email already registered' });
}
const passwordHash = await bcrypt.hash(password, SALT_ROUNDS);
const user = userDb.createUser({
email,
passwordHash,
displayName: displayName || email.split('@')[0],
provider: 'local',
});
signAndSetCookie(res, user);
res.status(201).json({
message: 'Registration successful',
user: userDb.toPublicUser(user),
});
} catch (err) {
console.error('[Auth] Register error:', err);
res.status(500).json({ error: err.message });
}
});
/**
* POST /api/auth/login
*/
router.post('/login', async (req, res) => {
try {
const { email, password } = req.body;
if (!email || !password) {
return res.status(400).json({ error: 'email and password are required' });
}
const user = userDb.findByEmail(email);
if (!user) {
return res.status(401).json({ error: 'Invalid email or password' });
}
const valid = await bcrypt.compare(password, user.password_hash);
if (!valid) {
return res.status(401).json({ error: 'Invalid email or password' });
}
userDb.updateLastLogin(user.id);
signAndSetCookie(res, user);
res.json({
message: 'Login successful',
user: userDb.toPublicUser(user),
});
} catch (err) {
console.error('[Auth] Login error:', err);
res.status(500).json({ error: err.message });
}
});
/**
* POST /api/auth/logout
*/
router.post('/logout', (req, res) => {
clearCookie(res);
res.json({ message: 'Logged out' });
});
/**
* GET /api/auth/me
*/
router.get('/me', optionalAuth, (req, res) => {
res.json({ user: req.user || null });
});
// ═══════════════════════════════════════
// GitHub OAuth
// ═══════════════════════════════════════
const GITHUB_CLIENT_ID = process.env.GITHUB_CLIENT_ID;
const GITHUB_CLIENT_SECRET = process.env.GITHUB_CLIENT_SECRET;
router.get('/github', (req, res) => {
if (!GITHUB_CLIENT_ID) {
return res.status(503).json({ error: 'GitHub OAuth not configured' });
}
const redirectUri = `${getBaseUrl(req)}/api/auth/github/callback`;
const url = `https://github.com/login/oauth/authorize?client_id=${GITHUB_CLIENT_ID}&redirect_uri=${encodeURIComponent(redirectUri)}&scope=read:user,user:email`;
res.redirect(url);
});
router.get('/github/callback', async (req, res) => {
try {
const { code } = req.query;
if (!code) return res.status(400).send('Missing code');
// Exchange code for access token
const tokenRes = await fetch('https://github.com/login/oauth/access_token', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
client_id: GITHUB_CLIENT_ID,
client_secret: GITHUB_CLIENT_SECRET,
code,
}),
});
const tokenData = await tokenRes.json();
console.log('[Auth] GitHub token response:', JSON.stringify(tokenData));
if (!tokenData.access_token) {
console.error('[Auth] GitHub token exchange failed:', tokenData);
return res.redirect('/login?error=github_failed');
}
// Get user profile
const profileRes = await fetch('https://api.github.com/user', {
headers: { Authorization: `Bearer ${tokenData.access_token}` },
});
const profile = await profileRes.json();
console.log('[Auth] GitHub profile:', JSON.stringify(profile));
// Get email (may be private)
let email = profile.email;
if (!email) {
try {
const emailsRes = await fetch('https://api.github.com/user/emails', {
headers: { Authorization: `Bearer ${tokenData.access_token}` },
});
const emails = await emailsRes.json();
if (Array.isArray(emails)) {
const primary = emails.find(e => e.primary && e.verified);
email = primary?.email || emails[0]?.email;
} else {
console.warn('[Auth] GitHub /user/emails returned non-array:', emails);
}
} catch (emailErr) {
console.warn('[Auth] Failed to fetch GitHub emails:', emailErr.message);
}
}
const user = userDb.findOrCreateOAuthUser({
provider: 'github',
providerId: String(profile.id),
email,
displayName: profile.name || profile.login,
avatarUrl: profile.avatar_url,
githubLogin: profile.login,
});
signAndSetCookie(res, user);
res.redirect('/arena');
} catch (err) {
console.error('[Auth] GitHub callback error:', err);
res.redirect('/login?error=github_failed');
}
});
// ═══════════════════════════════════════
// Google OAuth
// ═══════════════════════════════════════
const GOOGLE_CLIENT_ID = process.env.GOOGLE_CLIENT_ID;
const GOOGLE_CLIENT_SECRET = process.env.GOOGLE_CLIENT_SECRET;
router.get('/google', (req, res) => {
if (!GOOGLE_CLIENT_ID) {
return res.status(503).json({ error: 'Google OAuth not configured' });
}
const redirectUri = `${getBaseUrl(req)}/api/auth/google/callback`;
const url = `https://accounts.google.com/o/oauth2/v2/auth?client_id=${GOOGLE_CLIENT_ID}&redirect_uri=${encodeURIComponent(redirectUri)}&response_type=code&scope=email%20profile&access_type=offline`;
res.redirect(url);
});
router.get('/google/callback', async (req, res) => {
try {
const { code } = req.query;
if (!code) return res.status(400).send('Missing code');
const redirectUri = `${getBaseUrl(req)}/api/auth/google/callback`;
// Exchange code for access token
const tokenRes = await fetch('https://oauth2.googleapis.com/token', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
client_id: GOOGLE_CLIENT_ID,
client_secret: GOOGLE_CLIENT_SECRET,
code,
grant_type: 'authorization_code',
redirect_uri: redirectUri,
}),
});
const tokenData = await tokenRes.json();
if (!tokenData.access_token) {
console.error('[Auth] Google token exchange failed:', tokenData);
return res.redirect('/login?error=google_failed');
}
// Get user profile
const profileRes = await fetch('https://www.googleapis.com/oauth2/v2/userinfo', {
headers: { Authorization: `Bearer ${tokenData.access_token}` },
});
const profile = await profileRes.json();
const user = userDb.findOrCreateOAuthUser({
provider: 'google',
providerId: String(profile.id),
email: profile.email,
displayName: profile.name,
avatarUrl: profile.picture,
});
signAndSetCookie(res, user);
res.redirect('/arena');
} catch (err) {
console.error('[Auth] Google callback error:', err);
res.redirect('/login?error=google_failed');
}
});
// ─── Helpers ───
function getBaseUrl(req) {
const proto = req.headers['x-forwarded-proto'] || req.protocol || 'http';
const host = req.headers['x-forwarded-host'] || req.get('host');
return `${proto}://${host}`;
}
module.exports = router;