25 lines
750 B
TypeScript
25 lines
750 B
TypeScript
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 };
|
|
};
|