From 4139f6fd5863ecf71afbaef3886a65c0f4931b12 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=98=99=E2=97=A6=20The=20Tablet=20=E2=9D=80=20GamerGirla?= =?UTF-8?q?ndCo=20=E2=97=A6=E2=9D=A7?= Date: Thu, 21 Mar 2024 18:34:46 -0400 Subject: [PATCH] refactor(api): remove auth cookie checks just get the authorization header --- server/api/auth/session.get.ts | 4 ++-- server/middleware/05.currentUser.ts | 29 ++++++++++++++++++----------- 2 files changed, 20 insertions(+), 13 deletions(-) diff --git a/server/api/auth/session.get.ts b/server/api/auth/session.get.ts index 7257b01..3ea59b3 100644 --- a/server/api/auth/session.get.ts +++ b/server/api/auth/session.get.ts @@ -1,6 +1,6 @@ export default eventHandler((event) => { - let ahead = (getHeaders(event).authorization || getCookie(event, "auth:token") || "")?.replace("Bearer ", ""); - if (event.context.currentUser) { + let ahead = (getHeaders(event).authorization || "")?.replace("Bearer ", ""); + if (event.context.currentUser && ahead) { return { token: ahead, user: event.context.currentUser, diff --git a/server/middleware/05.currentUser.ts b/server/middleware/05.currentUser.ts index a12619f..0e2e220 100644 --- a/server/middleware/05.currentUser.ts +++ b/server/middleware/05.currentUser.ts @@ -2,19 +2,26 @@ 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 || getCookie(event, "auth:token") || "")?.replace("Bearer ", ""); - // console.log("in here fucknuts", ahead); - // log.debug(`'${ahead}'`, { label: "idk" }); + let ahead = (getHeaders(event).authorization || "")?.replace("Bearer ", ""); if (ahead) { - let toktok = jwt.verify( - ahead, - // ahead.replace("Bearer ", ""), - useRuntimeConfig().jwt, - ) as jwt.JwtPayload; - let user = await User.findById(toktok.id as number).exec(); - if (user && toktok) event.context.currentUser = user; - // setCookie(event, "auth:token", 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; + } } });