2022-09-09 22:46:53 +00:00
|
|
|
import { defineStore } from "pinia";
|
|
|
|
import { useLocalStorage } from "@vueuse/core";
|
2022-10-07 02:54:09 +00:00
|
|
|
import { UserClient } from "~~/lib/api/user";
|
2022-09-25 22:33:13 +00:00
|
|
|
import { UserOut } from "~~/lib/api/types/data-contracts";
|
2022-09-01 22:32:03 +00:00
|
|
|
|
2022-09-09 22:46:53 +00:00
|
|
|
export const useAuthStore = defineStore("auth", {
|
2022-09-01 22:32:03 +00:00
|
|
|
state: () => ({
|
2022-09-09 22:46:53 +00:00
|
|
|
token: useLocalStorage("pinia/auth/token", ""),
|
|
|
|
expires: useLocalStorage("pinia/auth/expires", ""),
|
2022-09-25 22:33:13 +00:00
|
|
|
self: null as UserOut | null,
|
2022-09-01 22:32:03 +00:00
|
|
|
}),
|
|
|
|
getters: {
|
2022-09-03 09:17:57 +00:00
|
|
|
isTokenExpired: state => {
|
2022-09-01 22:32:03 +00:00
|
|
|
if (!state.expires) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2022-09-09 22:46:53 +00:00
|
|
|
if (typeof state.expires === "string") {
|
2022-09-01 22:32:03 +00:00
|
|
|
return new Date(state.expires) < new Date();
|
|
|
|
}
|
|
|
|
|
|
|
|
return state.expires < new Date();
|
|
|
|
},
|
|
|
|
},
|
|
|
|
actions: {
|
2022-10-07 02:54:09 +00:00
|
|
|
async logout(api: UserClient) {
|
|
|
|
const result = await api.user.logout();
|
2022-09-01 22:32:03 +00:00
|
|
|
|
2022-09-09 22:46:53 +00:00
|
|
|
this.token = "";
|
|
|
|
this.expires = "";
|
2022-09-25 22:33:13 +00:00
|
|
|
this.self = null;
|
2022-09-01 22:32:03 +00:00
|
|
|
|
|
|
|
return result;
|
|
|
|
},
|
2022-09-04 06:19:13 +00:00
|
|
|
/**
|
|
|
|
* clearSession is used when the user cannot be logged out via the API and
|
|
|
|
* must clear it's local session, usually when a 401 is received.
|
|
|
|
*/
|
|
|
|
clearSession() {
|
2022-09-09 22:46:53 +00:00
|
|
|
this.token = "";
|
|
|
|
this.expires = "";
|
|
|
|
navigateTo("/");
|
2022-09-04 06:19:13 +00:00
|
|
|
},
|
2022-09-01 22:32:03 +00:00
|
|
|
},
|
|
|
|
});
|