2023-10-10 21:56:25 -04:00
|
|
|
import jwt from "jsonwebtoken";
|
2023-12-20 17:23:31 -05:00
|
|
|
import { User } from "@models/user";
|
2023-12-29 20:11:07 -05:00
|
|
|
import { messages } from "@server/constants";
|
|
|
|
import { AccessToken } from "@models/oauth";
|
2023-10-10 21:56:25 -04:00
|
|
|
|
|
|
|
export default defineEventHandler(async (event) => {
|
2023-12-29 20:11:07 -05:00
|
|
|
let ahead = (getHeaders(event).authorization || getCookie(event, "auth:token") || "")?.replace("Bearer ", "");
|
2023-10-10 21:56:25 -04:00
|
|
|
if (ahead) {
|
2023-12-29 20:11:07 -05:00
|
|
|
let toktok: jwt.JwtPayload;
|
|
|
|
try {
|
|
|
|
toktok = jwt.verify(ahead, useRuntimeConfig().jwt) as jwt.JwtPayload;
|
|
|
|
let user = await User.findById(toktok.id as number).exec();
|
|
|
|
if (user && toktok) event.context.currentUser = user;
|
|
|
|
} catch (e) {
|
|
|
|
const t = await AccessToken.findOne({ token: ahead });
|
|
|
|
if (!t)
|
|
|
|
throw createError({
|
|
|
|
statusCode: 401,
|
|
|
|
message: messages[401],
|
|
|
|
});
|
|
|
|
let user = await User.findById(t.userID);
|
|
|
|
if (user) event.context.currentUser = user;
|
|
|
|
// else throw createError({statusCode: 401, message: messages[401]})
|
|
|
|
}
|
2023-10-10 21:56:25 -04:00
|
|
|
}
|
|
|
|
});
|