-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathoauth.js
More file actions
46 lines (40 loc) · 1.34 KB
/
oauth.js
File metadata and controls
46 lines (40 loc) · 1.34 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
/**
* OAuth2 JWT Middleware
* Verifies JWT tokens from Discord OAuth2 sessions
*/
import jwt from 'jsonwebtoken';
import { error } from '../../logger.js';
import { getSessionToken } from '../routes/auth.js';
/**
* Creates middleware that verifies a JWT Bearer token from the Authorization header.
* Attaches the decoded user payload to req.user on success.
*
* @returns {import('express').RequestHandler} Express middleware function
*/
export function requireOAuth() {
return (req, res, next) => {
const authHeader = req.headers.authorization;
if (!authHeader?.startsWith('Bearer ')) {
return res.status(401).json({ error: 'No token provided' });
}
const token = authHeader.slice(7);
const sessionSecret = process.env.SESSION_SECRET;
if (!sessionSecret) {
error('SESSION_SECRET not configured — cannot verify OAuth token', {
ip: req.ip,
path: req.path,
});
return res.status(500).json({ error: 'Session not configured' });
}
try {
const decoded = jwt.verify(token, sessionSecret, { algorithms: ['HS256'] });
if (!getSessionToken(decoded.userId)) {
return res.status(401).json({ error: 'Session expired or revoked' });
}
req.user = decoded;
next();
} catch {
return res.status(401).json({ error: 'Invalid or expired token' });
}
};
}