feat: Implement bearer token validation in auth middleware (#186)

This commit is contained in:
samanhappy
2025-06-19 12:11:35 +08:00
committed by GitHub
parent 1e308ec4c5
commit d119be0f82
15 changed files with 248 additions and 56 deletions

View File

@@ -1,11 +1,45 @@
import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';
import { loadSettings } from '../config/index.js';
// Default secret key - in production, use an environment variable
const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key-change-this';
const validateBearerAuth = (req: Request, routingConfig: any): boolean => {
if (!routingConfig.enableBearerAuth) {
return false;
}
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return false;
}
return authHeader.substring(7) === routingConfig.bearerAuthKey;
};
// Middleware to authenticate JWT token
export const auth = (req: Request, res: Response, next: NextFunction): void => {
// Check if authentication is disabled globally
const routingConfig = loadSettings().systemConfig?.routing || {
enableGlobalRoute: true,
enableGroupNameRoute: true,
enableBearerAuth: false,
bearerAuthKey: '',
skipAuth: false,
};
if (routingConfig.skipAuth) {
next();
return;
}
// Check if bearer auth is enabled and validate it
if (validateBearerAuth(req, routingConfig)) {
next();
return;
}
// Get token from header or query parameter
const headerToken = req.header('x-auth-token');
const queryToken = req.query.token as string;
@@ -20,11 +54,11 @@ export const auth = (req: Request, res: Response, next: NextFunction): void => {
// Verify token
try {
const decoded = jwt.verify(token, JWT_SECRET);
// Add user from payload to request
(req as any).user = (decoded as any).user;
next();
} catch (error) {
res.status(401).json({ success: false, message: 'Token is not valid' });
}
};
};