Implement authentication composable with signin, signup, and session management; add route middleware for auth checks
This commit is contained in:
1 parent
e1716c3e61
commit
170d24c117
3 files changed
+64
No files matched your search
@@ -0,0 +1,56 @@
|
|||||||
|
import axios, { AxiosError } from "axios"
|
||||||
|
|
||||||
|
export const useAuth = () => {
|
||||||
|
const refreshToken = useCookie<string | null>("refreshToken", {
|
||||||
|
sameSite: "lax",
|
||||||
|
})
|
||||||
|
|
||||||
|
const sessionToken = useCookie<string | null>("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,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
export default defineNuxtRouteMiddleware((to, from) => {
|
||||||
|
const auth = useAuth()
|
||||||
|
|
||||||
|
if (!auth.refreshToken.value && !to.fullPath.includes("/auth"))
|
||||||
|
return navigateTo("/auth/signin")
|
||||||
|
})
|
||||||
@@ -8,6 +8,8 @@ export const cfetch = async (
|
|||||||
): Promise<AxiosResponse> => {
|
): Promise<AxiosResponse> => {
|
||||||
const baseUrl = import.meta.env.VITE_PUBLIC_BACKEND
|
const baseUrl = import.meta.env.VITE_PUBLIC_BACKEND
|
||||||
|
|
||||||
|
if (!baseUrl) throw new Error("BACKEND URL not set")
|
||||||
|
|
||||||
const defaults: AxiosRequestConfig = {
|
const defaults: AxiosRequestConfig = {
|
||||||
baseURL: baseUrl,
|
baseURL: baseUrl,
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user