homebox/frontend/stores/auth.ts

46 lines
1.1 KiB
TypeScript
Raw Normal View History

import { defineStore } from "pinia";
import { useLocalStorage } from "@vueuse/core";
2022-10-04 04:09:53 +00:00
import { UserClient } from "~~/lib/api/user";
import { UserOut } from "~~/lib/api/types/data-contracts";
2022-09-01 22:32:03 +00:00
export const useAuthStore = defineStore("auth", {
2022-09-01 22:32:03 +00:00
state: () => ({
token: useLocalStorage("pinia/auth/token", ""),
expires: useLocalStorage("pinia/auth/expires", ""),
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;
}
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-04 04:09:53 +00:00
async logout(api: UserClient) {
2022-10-04 05:36:51 +00:00
const result = await api.user.logout();
2022-09-01 22:32:03 +00:00
this.token = "";
this.expires = "";
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() {
this.token = "";
this.expires = "";
navigateTo("/");
2022-09-04 06:19:13 +00:00
},
2022-09-01 22:32:03 +00:00
},
});