Files
List_ultimate/app/stores/auth.ts
2026-02-26 21:29:34 +01:00

247 lines
6.7 KiB
TypeScript

import { defineStore } from 'pinia'
import UserRepository from '~/repositories/user.repository'
import type { User, LoginResponse, ConfirmResult } from '~/types/auth'
export const useAuthStore = defineStore('auth', {
state: () => ({
// On lie l'état directement au cookie
token: useCookie<string | null>('auth_token', {
// secure: false,
// sameSite: 'lax',
path: '/',
maxAge: 60 * 60 * 24 * 7
}), // Expire après 7 jours
user: useCookie<User | null>('auth_user', {
// secure: false,
// sameSite: 'lax',
path: '/',
maxAge: 60 * 60 * 24 * 7
}),
loading: false,
error: null as string | null,
}),
getters: {
// Le "!!" transforme la valeur en vrai BOULÉEN (true/false)
isLoggedIn: (state) => !!state.token,
// plus tard on pourras ajouter un getter pour récupérer le prénom
//userName: (state) => state.user?.name || 'Invité'
},
actions: {
setTokenCookie(newToken: string | null) {
const cookie = useCookie('auth_token')
cookie.value = newToken // On force l'écriture
this.token = newToken // On met à jour le state Pinia
},
setUserCookie(newUser: User | null) {
// 1. On récupère le cookie sans typage strict ou typé en 'any' pour l'écriture
const userCookie = useCookie<any>('auth_user', {
path: '/',
maxAge: 60 * 60 * 24 * 7,
})
// 2. On assigne l'objet (Nuxt va faire le JSON.stringify en interne)
userCookie.value = newUser
// 3. On met à jour le state Pinia
this.user = newUser
},
async register(email: string, password:string, locale:string ){
const { $api } = useNuxtApp();
const listsStore = useListStore()
const config = useRuntimeConfig()
this.loading = true
this.error = null
try {
const data = await $api.user.register(email, password, locale)
// En cas de réussite, le nouveau user est connecté.
// On assigne les valeurs : useCookie met à jour le state ET le navigateur
this.setTokenCookie(data.token)
this.setUserCookie(data.user)
listsStore.saveLists(data.lists)
return true
} catch (err: any) {
// En cas d'erreur, on nettoie les cookies
this.token = null
this.user = null
this.error = err.data?.message || "Erreur de connexion"
return false
} finally {
this.loading = false
}
},
async confirmUser(token: string) {
const { $api } = useNuxtApp();
//console.log(token)
this.error = null
try {
const res: ConfirmResult = await $api.user.confirm(token)
return res
} catch (err: any) {
return false
}
},
async login(login: string, password: string) {
const listsStore = useListStore()
const config = useRuntimeConfig()
this.loading = true
this.error = null
try {
const data = await $fetch<LoginResponse>(`${config.public.apiBase}/auth/login`, {
method: 'POST',
body: { login, password }
})
// On assigne les valeurs : useCookie met à jour le state ET le navigateur
this.setTokenCookie(data.token)
this.setUserCookie(data.user)
listsStore.saveLists(data.lists)
return true
} catch (err: any) {
// En cas d'erreur, on nettoie les cookies
this.token = null
this.user = null
this.error = err.data?.message || "Erreur de connexion"
return false
} finally {
this.loading = false
}
},
logout() {
this.setTokenCookie(null)
this.setUserCookie(null)
const listsStore = useListStore()
listsStore.resetLists()
return navigateTo('/')
},
async pwdResetResquest( email: string, locale: string) {
const config = useRuntimeConfig()
this.error = null
try {
const data = await $fetch<boolean>(`${config.public.apiBase}/user/pwdReset`, {
method: 'POST',
body: { email, locale }
})
return data
} catch (err: any) {
this.error = err.data?.message || "Erreur de connexion"
return false
} finally {
this.loading = false
}
},
async pwdReset( password: string, token: any) {
const config = useRuntimeConfig()
this.error = null
try {
const data = await $fetch<boolean>(`${config.public.apiBase}/user/pwdReset`, {
method: 'PUT',
body: { password, token }
})
return data
} catch (err: any) {
this.error = err.data?.message || "Erreur de connexion"
return false
} finally {
this.loading = false
}
},
async emailChange( newEmail:string, locale:string){
const { $api } = useNuxtApp();
// const config = useRuntimeConfig()
this.error = null;
if ( !this.user?.email ){
return false;
}
try {
const data = await $api.user.emailChange(newEmail, locale)
return data
} catch (err: any) {
this.error = err.data?.message || "Erreur de connexion"
return false
} finally {
this.loading = false
}
},
async updateDisplayName(newDisplayName:string){
const { $api } = useNuxtApp();
// const config = useRuntimeConfig()
this.error = null;
if ( !this.user?.email ){
return false;
}
try {
const data = await $api.user.updateDisplayName(newDisplayName)
this.user.display_name = newDisplayName
return data
} catch (err: any) {
this.error = err.data?.message || "Erreur de connexion"
return false
} finally {
this.loading = false
}
},
async deleteRequest(locale:string){
const { $api } = useNuxtApp();
this.error = null
if ( !this.user?.email ){
return false;
}
try {
const data = await $api.user.deleteRequest(locale)
return data
} catch (err: any) {
this.error = err.data?.message || "Erreur de connexion"
return false
}
},
async pwdChallenge(pwd:string){
const { $api } = useNuxtApp();
try {
const data = await $api.user.pwdChallenge(pwd)
console.log(data)
if (this.user){
this.user.sudo_token = data.sudo_token
}
} catch (err: any) {
if (err.response?.status === 403) {
console.warn("Mauvais mot de passe, mais on garde la session active.");
return false; // On renvoie false pour afficher une erreur dans l'UI
}
}
},
}
})