next/server/middleware/05.currentUser.ts
2024-03-21 18:34:46 -04:00

28 lines
884 B
TypeScript

import jwt from "jsonwebtoken";
import { log } from "@server/logger";
import { messages } from "@server/constants";
import { User } from "@models/user";
import { AccessToken } from "@models/oauth";
import { IJwt } from "@server/types/authstuff";
export default defineEventHandler(async (event) => {
let ahead = (getHeaders(event).authorization || "")?.replace("Bearer ", "");
if (ahead) {
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;
}
}
});