Files
onboard/resources/js/Stores/auth.js

75 lines
2.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import axios from 'axios'
import {usePage} from "@inertiajs/vue3";
export const useAuthStore = defineStore('authStore', () => {
const user = usePage().props.user
const token = user?.token
const permissions = user?.permissions
const availableDepartments = ref([])
// Инициализация axios с токеном
if (token?.value) {
axios.defaults.headers.common['Authorization'] = `Bearer ${token.value}`
}
// Вычисляемые свойства
const isAuthenticated = computed(() => !!user.value && !!token.value)
const isAdmin = computed(() => user.role === 'admin')
const isDoctor = computed(() => user.role === 'doctor')
const isNurse = computed(() => user.role === 'nurse')
const isHeadOfDepartment = computed(() => user.role === 'head_of_department')
const isStatistician = computed(() => user.role === 'statistician')
const userDepartment = computed(() => user.department || '')
const clearAuthData = () => {
user.value = null
token.value = null
permissions.value = {}
availableDepartments.value = []
localStorage.removeItem('token')
localStorage.removeItem('user')
delete axios.defaults.headers.common['Authorization']
}
const logout = async () => {
try {
await axios.post('/api/auth/logout')
} catch (error) {
console.error('Ошибка при выходе:', error)
} finally {
clearAuthData()
}
}
// Проверка прав
const hasPermission = (permission) => {
return permissions.value[permission] === true
}
const canAccessDepartment = (department) => {
if (isAdmin.value || isHeadOfDepartment.value) return true
return availableDepartments.value.includes(department)
}
return {
user,
token,
permissions,
availableDepartments,
isAuthenticated,
isAdmin,
isDoctor,
isNurse,
isHeadOfDepartment,
isStatistician,
userDepartment,
clearAuthData,
hasPermission,
canAccessDepartment
}
})