perf:优化代码
This commit is contained in:
24
src/routes-simple/middleware/auth.ts
Normal file
24
src/routes-simple/middleware/auth.ts
Normal 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 };
|
||||
};
|
||||
Reference in New Issue
Block a user