perf:优化代码

This commit is contained in:
2024-11-21 02:09:05 +08:00
parent 801e05b23e
commit aa3e8f2bb6
4 changed files with 29 additions and 2 deletions

View File

@@ -0,0 +1,24 @@
import { User } from '@/models/user.ts';
import http from 'http';
export const error = (msg: string, code = 500) => {
return JSON.stringify({ code, message: msg });
};
export const checkAuth = async (req: http.IncomingMessage, res: http.ServerResponse) => {
const authroization = req.headers?.['authorization'] as string;
if (!authroization) {
res.statusCode = 401;
res.end(error('Invalid authorization'));
return { tokenUser: null, token: null };
}
const token = authroization.split(' ')[1];
let tokenUser;
try {
tokenUser = await User.verifyToken(token);
} catch (e) {
res.statusCode = 401;
res.end(error('Invalid token'));
return { tokenUser: null, token: null };
}
return { tokenUser, token };
};