From 2b233364a186261b7330aab981e448b5ab23bd9c 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, 28 Sep 2023 21:55:19 -0400 Subject: [PATCH] refactor(api): refactor app to use pure jwts instead of cookies cookies are no longer used --- composables/useApiFetch.ts | 27 +++++++++++------- server/api/auth/login.post.ts | 49 ++++++++++++++++++++++++++++++++ server/api/auth/register.post.ts | 3 ++ server/api/auth/session.get.ts | 10 +++++++ server/middleware/currentUser.ts | 31 ++++++++++++-------- 5 files changed, 97 insertions(+), 23 deletions(-) create mode 100644 server/api/auth/login.post.ts create mode 100644 server/api/auth/register.post.ts create mode 100644 server/api/auth/session.get.ts diff --git a/composables/useApiFetch.ts b/composables/useApiFetch.ts index c125c15..cad1806 100644 --- a/composables/useApiFetch.ts +++ b/composables/useApiFetch.ts @@ -1,11 +1,16 @@ -import { UseFetchOptions } from "nuxt/app"; - -const useApiFetch = async (url: string, options?: any) => { - const at = useCookie("rockfic_cookie", {default: undefined}) - return useFetch("/api" + url, { - method: "get", - ...options, - }) -} - -export default useApiFetch \ No newline at end of file +import { UseFetchOptions } from "nuxt/app"; + +const useApiFetch = async (url: string, options?: any) => { + const at = useCookie("rockfic_cookie", { default: undefined }); + const { token } = useAuth(); + return useFetch("/api" + url, { + method: "get", + headers: { + ...(options?.headers || {}), + Authorization: `Bearer ${token.value}`, + }, + ...options, + }); +}; + +export default useApiFetch; diff --git a/server/api/auth/login.post.ts b/server/api/auth/login.post.ts new file mode 100644 index 0000000..2aaa075 --- /dev/null +++ b/server/api/auth/login.post.ts @@ -0,0 +1,49 @@ +import mongoose from "mongoose"; +import jwt from "jsonwebtoken"; +import { IUser, User } from "~/models/user"; + +export default eventHandler(async (event) => { + const wrongMsg = "wrong credentials"; + let reqbody = await readBody(event); + let user = await User.findOne({ username: reqbody.username }).exec(); + console.log("USER -> ", user); + console.log("conn ->", mongoose.connection); + let cok = getHeader(event, "Authorization")?.replace("Bearer ", ""); + if (!cok) { + if (!user) { + throw createError({ statusCode: 401, message: wrongMsg }); + } + if (user.banned) { + throw createError({ + statusCode: 401, + message: "This account has been banned.", + }); + } + if (user.validPassword(reqbody.password)) { + if (!user.auth.emailVerified) { + throw createError({ + statusCode: 401, + message: + 'Account inactive!
Resend verification?', + }); + } + let tok = user.generateToken(useRuntimeConfig().jwt); + // setCookie(event, "rockfic_cookie", tok); + return { + user, + token: tok, + }; + } else { + throw createError({ statusCode: 401, message: wrongMsg }); + } + } else { + if (jwt.verify(cok, useRuntimeConfig().jwt)) { + throw createError({ + statusCode: 405, + message: "Already logged in.", + }); + } else { + throw createError({ statusCode: 401, message: wrongMsg }); + } + } +}); diff --git a/server/api/auth/register.post.ts b/server/api/auth/register.post.ts new file mode 100644 index 0000000..a4c2bf8 --- /dev/null +++ b/server/api/auth/register.post.ts @@ -0,0 +1,3 @@ +export default eventHandler((event) => { + +}) \ No newline at end of file diff --git a/server/api/auth/session.get.ts b/server/api/auth/session.get.ts new file mode 100644 index 0000000..f6f45ad --- /dev/null +++ b/server/api/auth/session.get.ts @@ -0,0 +1,10 @@ +export default eventHandler((event) => { + if (event.context.currentUser) { + return { + token: getHeader(event, "Authorization"), + user: event.context.currentUser, + }; + } else { + throw createError({ statusCode: 400, message: "unauthenticated" }); + } +}); diff --git a/server/middleware/currentUser.ts b/server/middleware/currentUser.ts index 212ac57..5d4393b 100644 --- a/server/middleware/currentUser.ts +++ b/server/middleware/currentUser.ts @@ -1,12 +1,19 @@ -import jwt from "jsonwebtoken" -import { User } from "~/models/user" - -export default defineEventHandler(async (event) => { - let ahead = getCookie(event, "rockfic_cookie") - if(ahead) { - let toktok = (jwt.verify(ahead.replace("Bearer ", ""), useRuntimeConfig().jwt) as jwt.JwtPayload) - console.log(toktok) - let user = await User.findById(toktok.id as number).exec() - event.context.currentUser = user - } -}) \ No newline at end of file +import jwt from "jsonwebtoken"; +import { User } from "~/models/user"; + +export default defineEventHandler(async (event) => { + let ahead = (getHeaders(event).authorization || "")?.replace("Bearer ", ""); + console.log(`=------------------------${event.path}`); + console.log("h", getHeaders(event)); + console.log(JSON.stringify(ahead)); + if (ahead) { + console.log("ahead", ahead); + let toktok = jwt.verify( + ahead, + // ahead.replace("Bearer ", ""), + useRuntimeConfig().jwt, + ) as jwt.JwtPayload; + let user = await User.findById(toktok.id as number).exec(); + event.context.currentUser = user; + } +});