52 lines
1.6 KiB
TypeScript
52 lines
1.6 KiB
TypeScript
import {defineStore} from 'pinia'
|
|
|
|
interface UserClaims {
|
|
user_id: string
|
|
username: string
|
|
is_admin: boolean // On s'assure que le backend l'envoie ou on le déduit
|
|
exp: number
|
|
}
|
|
|
|
export const useAuthStore = defineStore('auth', {
|
|
state: () => ({
|
|
token: localStorage.getItem('token') || null as string | null,
|
|
user: JSON.parse(localStorage.getItem('user') || 'null') as UserClaims | null,
|
|
}),
|
|
getters: {
|
|
isAuthenticated: (state) => !!state.token,
|
|
isAdmin: (state) => state.user?.is_admin || false,
|
|
},
|
|
actions: {
|
|
setToken(token: string) {
|
|
this.token = token
|
|
localStorage.setItem('token', token)
|
|
|
|
try {
|
|
// Décoder le payload du JWT (2ème partie du string)
|
|
const base64Url = token.split('.')[1]
|
|
const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/')
|
|
const jsonPayload = decodeURIComponent(atob(base64).split('').map(function (c) {
|
|
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
|
|
}).join(''))
|
|
|
|
const decoded = JSON.parse(jsonPayload)
|
|
this.user = {
|
|
user_id: decoded.user_id,
|
|
username: decoded.username,
|
|
is_admin: decoded.is_superuser || false, // Vérifiez le nom du champ dans votre Claims Rust
|
|
exp: decoded.expire_at
|
|
}
|
|
localStorage.setItem('user', JSON.stringify(this.user))
|
|
} catch (e) {
|
|
console.error("Failed to decode token", e)
|
|
this.logout()
|
|
}
|
|
},
|
|
logout() {
|
|
this.token = null
|
|
this.user = null
|
|
localStorage.removeItem('token')
|
|
localStorage.removeItem('user')
|
|
}
|
|
}
|
|
}) |