|
| 1 | +/** |
| 2 | + * Shared OAuth JWT middleware helpers |
| 3 | + */ |
| 4 | + |
| 5 | +import { error } from '../../logger.js'; |
| 6 | +import { verifyJwtToken } from './verifyJwt.js'; |
| 7 | + |
| 8 | +/** |
| 9 | + * Extract Bearer token from Authorization header. |
| 10 | + * |
| 11 | + * @param {string|undefined} authHeader - Raw Authorization header value |
| 12 | + * @returns {string|null} JWT token if present, otherwise null |
| 13 | + */ |
| 14 | +export function getBearerToken(authHeader) { |
| 15 | + if (!authHeader?.startsWith('Bearer ')) { |
| 16 | + return null; |
| 17 | + } |
| 18 | + return authHeader.slice(7); |
| 19 | +} |
| 20 | + |
| 21 | +/** |
| 22 | + * Authenticate request using OAuth JWT Bearer token. |
| 23 | + * |
| 24 | + * @param {import('express').Request} req - Express request |
| 25 | + * @param {import('express').Response} res - Express response |
| 26 | + * @param {import('express').NextFunction} next - Express next callback |
| 27 | + * @param {{ missingTokenError?: string }} [options] - Behavior options |
| 28 | + * @returns {boolean} True if middleware chain has been handled, false if no Bearer token was provided and no missing-token error was requested |
| 29 | + */ |
| 30 | +export function handleOAuthJwt(req, res, next, options = {}) { |
| 31 | + const token = getBearerToken(req.headers.authorization); |
| 32 | + if (!token) { |
| 33 | + if (options.missingTokenError) { |
| 34 | + res.status(401).json({ error: options.missingTokenError }); |
| 35 | + return true; |
| 36 | + } |
| 37 | + return false; |
| 38 | + } |
| 39 | + |
| 40 | + const result = verifyJwtToken(token); |
| 41 | + if (result.error) { |
| 42 | + if (result.status === 500) { |
| 43 | + error('SESSION_SECRET not configured — cannot verify OAuth token', { |
| 44 | + ip: req.ip, |
| 45 | + path: req.path, |
| 46 | + }); |
| 47 | + } |
| 48 | + res.status(result.status).json({ error: result.error }); |
| 49 | + return true; |
| 50 | + } |
| 51 | + |
| 52 | + req.authMethod = 'oauth'; |
| 53 | + req.user = result.user; |
| 54 | + next(); |
| 55 | + return true; |
| 56 | +} |
0 commit comments