From 170d24c11760b08ced76b7ebb2b5675f13b2adb1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lucas=20T=C3=A4kker?= Date: Fri, 5 Dec 2025 02:47:41 +0100 Subject: [PATCH] Implement authentication composable with signin, signup, and session management; add route middleware for auth checks --- app/composables/useAuth.ts | 56 +++++++++++++++++++++++++++++++++++ app/middleware/auth.global.ts | 6 ++++ app/utils/cfetch.ts | 2 ++ 3 files changed, 64 insertions(+) create mode 100644 app/composables/useAuth.ts create mode 100644 app/middleware/auth.global.ts diff --git a/app/composables/useAuth.ts b/app/composables/useAuth.ts new file mode 100644 index 0000000..038a6a6 --- /dev/null +++ b/app/composables/useAuth.ts @@ -0,0 +1,56 @@ +import axios, { AxiosError } from "axios" + +export const useAuth = () => { + const refreshToken = useCookie("refreshToken", { + sameSite: "lax", + }) + + const sessionToken = useCookie("sessionToken", { + sameSite: "lax", + }) + + const signin = async ( + email: string, + password: string, + remember: boolean = false + ) => { + console.log(email) + + try { + const res = await cfetch( + "/auth/signin", + { + method: "POST", + data: { + email, + password, + }, + }, + false + ) + + refreshToken.value = res.data.refreshToken + } catch (e) { + if (axios.isAxiosError(e) && e.response?.data?.message) { + throw new Error(e.response.data.message) + } + + throw new Error("Failed to sign in") + } + } + + const signup = async (name: string, email: string, password: string) => {} + + const signout = () => {} + + const refreshSessionToken = async () => {} + + return { + refreshToken, + sessionToken, + signin, + signup, + signout, + refreshSessionToken, + } +} diff --git a/app/middleware/auth.global.ts b/app/middleware/auth.global.ts new file mode 100644 index 0000000..05464e1 --- /dev/null +++ b/app/middleware/auth.global.ts @@ -0,0 +1,6 @@ +export default defineNuxtRouteMiddleware((to, from) => { + const auth = useAuth() + + if (!auth.refreshToken.value && !to.fullPath.includes("/auth")) + return navigateTo("/auth/signin") +}) diff --git a/app/utils/cfetch.ts b/app/utils/cfetch.ts index 9ae8c44..076a190 100644 --- a/app/utils/cfetch.ts +++ b/app/utils/cfetch.ts @@ -8,6 +8,8 @@ export const cfetch = async ( ): Promise => { const baseUrl = import.meta.env.VITE_PUBLIC_BACKEND + if (!baseUrl) throw new Error("BACKEND URL not set") + const defaults: AxiosRequestConfig = { baseURL: baseUrl, }