| [92e7c7a] | 1 | import { computed, ref } from 'vue'
|
|---|
| 2 | import { defineStore } from 'pinia'
|
|---|
| 3 | import type { LoginRequest, SignupRequest } from '../api/auth'
|
|---|
| 4 | import { login as apiLogin, signup as apiSignup } from '../api/auth'
|
|---|
| 5 |
|
|---|
| 6 | const STORAGE_KEY = 'petify.auth.user'
|
|---|
| 7 |
|
|---|
| 8 | interface User {
|
|---|
| 9 | userId: number
|
|---|
| 10 | username: string
|
|---|
| 11 | email: string
|
|---|
| 12 | firstName: string
|
|---|
| 13 | lastName: string
|
|---|
| 14 | userType: string
|
|---|
| 15 | verified: boolean
|
|---|
| 16 | }
|
|---|
| 17 |
|
|---|
| 18 | export const useAuthStore = defineStore('auth', () => {
|
|---|
| 19 | const user = ref<User | null>(null)
|
|---|
| 20 |
|
|---|
| 21 | // Load user from localStorage on store initialization
|
|---|
| 22 | const storedUser = localStorage.getItem(STORAGE_KEY)
|
|---|
| 23 | if (storedUser) {
|
|---|
| 24 | try {
|
|---|
| 25 | user.value = JSON.parse(storedUser)
|
|---|
| 26 | } catch (e) {
|
|---|
| 27 | localStorage.removeItem(STORAGE_KEY)
|
|---|
| 28 | }
|
|---|
| 29 | }
|
|---|
| 30 |
|
|---|
| 31 | const isAuthenticated = computed(() => !!user.value)
|
|---|
| 32 | const token = computed(() => user.value ? `user_${user.value.userId}` : '')
|
|---|
| 33 |
|
|---|
| 34 | function setUser(userData: User | null) {
|
|---|
| 35 | user.value = userData
|
|---|
| 36 | if (userData) {
|
|---|
| 37 | localStorage.setItem(STORAGE_KEY, JSON.stringify(userData))
|
|---|
| 38 | } else {
|
|---|
| 39 | localStorage.removeItem(STORAGE_KEY)
|
|---|
| 40 | }
|
|---|
| 41 | }
|
|---|
| 42 |
|
|---|
| 43 | async function login(payload: LoginRequest) {
|
|---|
| 44 | const result = await apiLogin(payload)
|
|---|
| 45 | if (result.user) {
|
|---|
| 46 | setUser(result.user)
|
|---|
| 47 | } else {
|
|---|
| 48 | throw new Error('Login failed: No user data received')
|
|---|
| 49 | }
|
|---|
| 50 | }
|
|---|
| 51 |
|
|---|
| 52 | async function signup(payload: SignupRequest): Promise<{ tokenReturned: boolean }> {
|
|---|
| 53 | const result = await apiSignup(payload)
|
|---|
| 54 | if (result.user) {
|
|---|
| 55 | setUser(result.user)
|
|---|
| 56 | return { tokenReturned: true }
|
|---|
| 57 | }
|
|---|
| 58 | // Registration successful but need to login
|
|---|
| 59 | return { tokenReturned: false }
|
|---|
| 60 | }
|
|---|
| 61 |
|
|---|
| 62 | function logout() {
|
|---|
| 63 | setUser(null)
|
|---|
| 64 | }
|
|---|
| 65 |
|
|---|
| 66 | return {
|
|---|
| 67 | user,
|
|---|
| 68 | token,
|
|---|
| 69 | isAuthenticated,
|
|---|
| 70 | login,
|
|---|
| 71 | signup,
|
|---|
| 72 | logout,
|
|---|
| 73 | }
|
|---|
| 74 | })
|
|---|