refactor: migrate entire project to TypeScript
This commit is contained in:
53
middleware/auth.ts
Normal file
53
middleware/auth.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import jwt from 'jsonwebtoken';
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import db from '../utils/database';
|
||||
import { AuthUser } from '../types';
|
||||
|
||||
declare global {
|
||||
namespace Express {
|
||||
interface Request {
|
||||
user?: AuthUser;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const authenticateToken = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
|
||||
const authHeader = req.headers['authorization'];
|
||||
const token = authHeader && authHeader.split(' ')[1];
|
||||
|
||||
if (!token) {
|
||||
res.status(401).json({ error: '访问令牌缺失' });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const decoded = jwt.verify(token, process.env.JWT_SECRET!) as { userId: number; username: string; role: string };
|
||||
|
||||
const user = await db.get(
|
||||
'SELECT id, username, name, role FROM users WHERE id = ?',
|
||||
[decoded.userId]
|
||||
) as AuthUser | undefined;
|
||||
|
||||
if (!user) {
|
||||
res.status(401).json({ error: '用户不存在' });
|
||||
return;
|
||||
}
|
||||
|
||||
req.user = user;
|
||||
next();
|
||||
} catch (error: any) {
|
||||
if (error.name === 'TokenExpiredError') {
|
||||
res.status(401).json({ error: '令牌已过期' });
|
||||
return;
|
||||
}
|
||||
res.status(403).json({ error: '无效的令牌' });
|
||||
}
|
||||
};
|
||||
|
||||
export const requireAdmin = (req: Request, res: Response, next: NextFunction): void => {
|
||||
if (req.user?.role !== 'admin') {
|
||||
res.status(403).json({ error: '需要管理员权限' });
|
||||
return;
|
||||
}
|
||||
next();
|
||||
};
|
||||
Reference in New Issue
Block a user