67 lines
1.7 KiB
TypeScript
67 lines
1.7 KiB
TypeScript
import { defineStore } from 'pinia'
|
|
|
|
export type UserRole = 'user' | 'admin'
|
|
|
|
export interface User {
|
|
id: string
|
|
email: string
|
|
username: string
|
|
role: UserRole
|
|
email_verified: boolean
|
|
}
|
|
|
|
interface StoredAuth {
|
|
token: string
|
|
user: User
|
|
}
|
|
|
|
const STORAGE_KEY = 'imageforge_auth'
|
|
|
|
export const useAuthStore = defineStore('auth', {
|
|
state: () => ({
|
|
token: null as string | null,
|
|
user: null as User | null,
|
|
}),
|
|
getters: {
|
|
isLoggedIn: (state) => Boolean(state.token),
|
|
},
|
|
actions: {
|
|
initFromStorage() {
|
|
try {
|
|
const raw = localStorage.getItem(STORAGE_KEY)
|
|
if (!raw) return
|
|
const parsed = JSON.parse(raw) as StoredAuth
|
|
if (!parsed?.token || !parsed?.user) return
|
|
this.token = parsed.token
|
|
this.user = parsed.user
|
|
} catch {
|
|
localStorage.removeItem(STORAGE_KEY)
|
|
}
|
|
},
|
|
setAuth(token: string, user: User) {
|
|
this.token = token
|
|
this.user = user
|
|
const stored: StoredAuth = { token, user }
|
|
localStorage.setItem(STORAGE_KEY, JSON.stringify(stored))
|
|
},
|
|
updateUser(user: User) {
|
|
this.user = user
|
|
if (!this.token) return
|
|
const stored: StoredAuth = { token: this.token, user }
|
|
localStorage.setItem(STORAGE_KEY, JSON.stringify(stored))
|
|
},
|
|
logout() {
|
|
this.token = null
|
|
this.user = null
|
|
localStorage.removeItem(STORAGE_KEY)
|
|
},
|
|
markEmailVerified() {
|
|
if (!this.user || this.user.email_verified) return
|
|
this.user = { ...this.user, email_verified: true }
|
|
if (!this.token) return
|
|
const stored: StoredAuth = { token: this.token, user: this.user }
|
|
localStorage.setItem(STORAGE_KEY, JSON.stringify(stored))
|
|
},
|
|
},
|
|
})
|