2023-10-10 21:56:25 -04:00
|
|
|
import jwt from "jsonwebtoken";
|
2023-12-30 17:36:22 -05:00
|
|
|
import { log } from "@server/logger";
|
2023-12-31 14:23:02 -05:00
|
|
|
import { messages } from "@server/constants";
|
2023-12-20 17:23:31 -05:00
|
|
|
import { User } from "@models/user";
|
2024-03-21 18:34:46 -04:00
|
|
|
import { AccessToken } from "@models/oauth";
|
|
|
|
import { IJwt } from "@server/types/authstuff";
|
2023-10-10 21:56:25 -04:00
|
|
|
|
|
|
|
export default defineEventHandler(async (event) => {
|
2024-03-21 18:34:46 -04:00
|
|
|
let ahead = (getHeaders(event).authorization || "")?.replace("Bearer ", "");
|
2023-10-10 21:56:25 -04:00
|
|
|
if (ahead) {
|
2024-03-21 18:34:46 -04:00
|
|
|
let toktok: jwt.JwtPayload;
|
|
|
|
try {
|
|
|
|
toktok = jwt.verify(ahead, useRuntimeConfig().jwt) as IJwt;
|
|
|
|
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;
|
|
|
|
}
|
2023-10-10 21:56:25 -04:00
|
|
|
}
|
|
|
|
});
|