felicity-lims/frontend/vite/src/stores/auth.ts

72 lines
1.8 KiB
TypeScript
Raw Normal View History

2022-04-01 04:29:09 +08:00
import { defineStore } from 'pinia'
import { ref, watch } from 'vue'
import { IUser } from "../models/auth";
import { STORAGE_AUTH_KEY, USER_GROUP_OVERRIDE } from "../conf";
import { useNotifyToast } from "../composables";
const { toastInfo } = useNotifyToast();
2022-04-01 04:29:09 +08:00
interface IAuth {
token?: string,
tokenType?: string,
user?: IUser,
isAuthenticated: boolean
}
export const useAuthStore = defineStore('auth', () => {
const initialState: IAuth = {
user: undefined,
token: "",
tokenType: "",
isAuthenticated: false
}
const auth = ref({ ...initialState })
const resetState = () => auth.value = { ...initialState }
2022-04-04 02:54:31 +08:00
const reset = () => {
2022-04-01 04:29:09 +08:00
localStorage.removeItem(STORAGE_AUTH_KEY)
resetState()
2022-04-04 02:54:31 +08:00
}
const logout = () => {
toastInfo("Good bye " + auth.value.user?.firstName)
2022-04-04 02:54:31 +08:00
localStorage.removeItem(STORAGE_AUTH_KEY)
reset()
2022-04-01 04:29:09 +08:00
}
const upsertPermission = () => {
if(USER_GROUP_OVERRIDE.length > 0) {
auth.value.user?.groups?.forEach(group => ({ ...group, name: USER_GROUP_OVERRIDE }))
}
}
if(localStorage.getItem(STORAGE_AUTH_KEY)){
const data = JSON.parse(localStorage.getItem(STORAGE_AUTH_KEY)!)
auth.value = { ...auth.value, ...data, isAuthenticated: true }
upsertPermission()
} else {
2022-04-04 02:54:31 +08:00
// logout()
2022-04-01 04:29:09 +08:00
}
watch(auth, (authValue) => {
if(authValue && authValue.user && authValue.token){
localStorage.setItem(STORAGE_AUTH_KEY, JSON.stringify(authValue))
upsertPermission()
}
})
2022-04-04 02:54:31 +08:00
const persistAuth = async (data): Promise<boolean> => {
auth.value = data
2022-04-15 16:32:24 +08:00
auth.value.isAuthenticated = true;
2022-04-04 02:54:31 +08:00
return true
}
2022-04-01 04:29:09 +08:00
return {
auth,
2022-04-04 02:54:31 +08:00
reset,
2022-04-01 04:29:09 +08:00
persistAuth,
logout
}
})