Files
crater/resources/scripts/stores/auth.js
Mohit Panjwani 082d5cacf2 v5.0.0 update
2021-11-30 18:58:19 +05:30

75 lines
1.9 KiB
JavaScript

import axios from 'axios'
import { defineStore } from 'pinia'
import { useNotificationStore } from './notification'
import { useResetStore } from './reset'
import router from '@/scripts/router'
import { handleError } from '@/scripts/helpers/error-handling'
export const useAuthStore = (useWindow = false) => {
const defineStoreFunc = useWindow ? window.pinia.defineStore : defineStore
const { global } = window.i18n
const resetStore = useResetStore()
return defineStoreFunc({
id: 'auth',
state: () => ({
status: '',
loginData: {
email: '',
password: '',
remember: '',
},
}),
actions: {
login(data) {
return new Promise((resolve, reject) => {
axios.get('/sanctum/csrf-cookie').then((response) => {
if (response) {
axios
.post('/login', data)
.then((response) => {
resolve(response)
setTimeout(() => {
this.loginData.email = ''
this.loginData.password = ''
}, 1000)
})
.catch((err) => {
handleError(err)
reject(err)
})
}
})
})
},
logout() {
return new Promise((resolve, reject) => {
axios
.get('/auth/logout')
.then((response) => {
const notificationStore = useNotificationStore()
notificationStore.showNotification({
type: 'success',
message: 'Logged out successfully.',
})
router.push('/login')
resetStore.clearPinia()
resolve(response)
})
.catch((err) => {
handleError(err)
router.push('/')
reject(err)
})
})
},
},
})()
}