81 lines
1.8 KiB
TypeScript
81 lines
1.8 KiB
TypeScript
import { defineStore } from 'pinia'
|
|
import { ref, computed } from 'vue'
|
|
import type { User } from '@/types'
|
|
import {
|
|
getCurrentUser,
|
|
logout as authLogout,
|
|
sendOtp,
|
|
verifyOtp,
|
|
updateProfile as authUpdateProfile,
|
|
} from '@/services/authService'
|
|
|
|
export const useAuthStore = defineStore('auth', () => {
|
|
const user = ref<User | null>(getCurrentUser())
|
|
const loading = ref(false)
|
|
const error = ref<string | null>(null)
|
|
|
|
const isAuthenticated = computed(() => !!user.value)
|
|
const fullName = computed(() =>
|
|
user.value ? `${user.value.firstName} ${user.value.lastName}` : '',
|
|
)
|
|
|
|
function clearError() {
|
|
error.value = null
|
|
}
|
|
|
|
async function requestOtp(
|
|
phone: string,
|
|
options: { firstName?: string; lastName?: string; isRegister: boolean },
|
|
) {
|
|
loading.value = true
|
|
error.value = null
|
|
const result = await sendOtp(phone, options)
|
|
loading.value = false
|
|
if (!result.success) error.value = result.message
|
|
return result
|
|
}
|
|
|
|
async function confirmOtp(phone: string, code: string) {
|
|
loading.value = true
|
|
error.value = null
|
|
const result = await verifyOtp(phone, code)
|
|
loading.value = false
|
|
if (result.success && result.user) {
|
|
user.value = result.user
|
|
} else {
|
|
error.value = result.message
|
|
}
|
|
return result
|
|
}
|
|
|
|
function logout() {
|
|
authLogout()
|
|
user.value = null
|
|
}
|
|
|
|
function updateProfile(data: Partial<Pick<User, 'firstName' | 'lastName' | 'nationalId'>>) {
|
|
if (!user.value) return null
|
|
const updated = authUpdateProfile(user.value.id, data)
|
|
if (updated) user.value = updated
|
|
return updated
|
|
}
|
|
|
|
function hydrate() {
|
|
user.value = getCurrentUser()
|
|
}
|
|
|
|
return {
|
|
user,
|
|
loading,
|
|
error,
|
|
isAuthenticated,
|
|
fullName,
|
|
clearError,
|
|
requestOtp,
|
|
confirmOtp,
|
|
logout,
|
|
updateProfile,
|
|
hydrate,
|
|
}
|
|
})
|