Add setCookie function for managing cookies in authentication flow

This commit is contained in:
lucast committed 2026-02-04 13:11:21 +01:00
1 parent b2a3bc458b
commit fd389c95e9
1 file changed
+38 -4
+38 -4
View File
@@ -3,6 +3,30 @@ import axios, { AxiosError } from "axios"
let refreshPromise: Promise<any> | null = null let refreshPromise: Promise<any> | null = null
let waitForPromise: boolean = false let waitForPromise: boolean = false
const setCookie = (
name: string,
value: string,
options: {
maxAge?: number
path?: string
sameSite?: "lax" | "strict" | "none"
secure?: boolean
} = {},
) => {
let cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`
if (options.maxAge !== undefined) {
cookie += `; Max-Age=${options.maxAge}`
}
cookie += `; Path=${options.path ?? "/"}`
cookie += `; SameSite=${options.sameSite ?? "Lax"}`
if (options.secure) cookie += "; Secure"
document.cookie = cookie
}
export const useAuth = () => { export const useAuth = () => {
const refreshToken = useCookie<string | null>("refreshToken", { const refreshToken = useCookie<string | null>("refreshToken", {
sameSite: "lax", sameSite: "lax",
@@ -10,12 +34,13 @@ export const useAuth = () => {
const sessionToken = useCookie<string | null>("sessionToken", { const sessionToken = useCookie<string | null>("sessionToken", {
sameSite: "lax", sameSite: "lax",
maxAge: 60 * 60, // 60 minutes
}) })
const signin = async ( const signin = async (
email: string, email: string,
password: string, password: string,
remember: boolean = false remember: boolean = false,
) => { ) => {
try { try {
const res = await cfetch( const res = await cfetch(
@@ -27,10 +52,19 @@ export const useAuth = () => {
password, password,
}, },
}, },
false false,
) )
refreshToken.value = res.data.refreshToken // NOTE: Quite hacky... this should be changed.
// TODO: Add httpOnly and update the backend to support that.
if (remember) {
setCookie("refreshToken", res.data.refreshToken, {
maxAge: 60 * 60 * 24 * 30, // 30 days
})
} else {
setCookie("refreshToken", res.data.refreshToken)
}
//refreshToken.value = res.data.refreshToken
await refreshSessionToken() await refreshSessionToken()
await navigateTo("/") await navigateTo("/")
@@ -74,7 +108,7 @@ export const useAuth = () => {
}, },
method: "POST", method: "POST",
}, },
false false,
) )
.then((res) => { .then((res) => {
const token = res.data.sessionToken const token = res.data.sessionToken