wip migration
This commit is contained in:
81
stores/auth.ts
Normal file
81
stores/auth.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
// stores/auth.ts
|
||||
import { defineStore } from 'pinia'
|
||||
|
||||
export const useAuthStore = defineStore('auth', {
|
||||
state: () => ({
|
||||
access: null as string | null,
|
||||
refresh: null as string | null,
|
||||
id: null as number | null,
|
||||
name: null as string | null,
|
||||
email: null as string | null,
|
||||
role: 'ANON' as string,
|
||||
cookiesAreAccepted: false,
|
||||
}),
|
||||
getters: {
|
||||
isAuthenticated: (state) => !!state.access,
|
||||
isUser: (state) => state.role === 'SHOP_USER',
|
||||
isManager: (state) => state.role === 'COOP_MANAGER',
|
||||
isAdmin: (state) => state.role === 'SITE_ADMIN',
|
||||
getName: (state) => state.name,
|
||||
getId: (state) => state.id,
|
||||
cookiesAccepted: (state) => state.cookiesAreAccepted,
|
||||
},
|
||||
actions: {
|
||||
// Actions to handle authentication (action's migration)
|
||||
async login(email: string, password: string) {
|
||||
const config = useRuntimeConfig()
|
||||
const payload = await $fetch('/token/', {
|
||||
baseURL: config.public.baseURL,
|
||||
method: 'POST',
|
||||
body: { email, password }
|
||||
})
|
||||
this.setPayload(payload)
|
||||
},
|
||||
|
||||
async setUser() {
|
||||
const config = useRuntimeConfig()
|
||||
const data = await $fetch('/my_user/', {
|
||||
baseURL: config.public.baseURL,
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.access}`
|
||||
}
|
||||
})
|
||||
this.setUserData(data)
|
||||
},
|
||||
|
||||
async refresh() {
|
||||
const config = useRuntimeConfig()
|
||||
if (!this.refresh) return
|
||||
const data = await $fetch('/token/refresh/', {
|
||||
baseURL: config.public.baseURL,
|
||||
method: 'POST',
|
||||
body: { refresh: this.refresh }
|
||||
})
|
||||
this.setPayload(data)
|
||||
},
|
||||
|
||||
// Mutations migration
|
||||
logout() {
|
||||
this.$reset() // Reset the store state
|
||||
},
|
||||
|
||||
acceptCookies() {
|
||||
this.cookiesAreAccepted = true
|
||||
},
|
||||
|
||||
setUserData(payload: any) {
|
||||
this.id = payload.id
|
||||
this.name = payload.full_name
|
||||
this.email = payload.email
|
||||
this.role = payload.role
|
||||
},
|
||||
|
||||
setPayload(payload: any) {
|
||||
this.access = payload.access
|
||||
if (payload.refresh) {
|
||||
this.refresh = payload.refresh
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user