import { ActionContext } from "vuex"; import { RootState } from "@/store/state"; export interface AuthState { user: string | null; token: string | null; } type AuthContext = ActionContext; const auth = { namespaced: true, state: { user: null, token: localStorage.getItem("access_token") || null, }, getters: { accessToken: (state: AuthState): string | null => { return state.token; }, isLogged: (state: AuthState): boolean => { return state.token != null; }, me: (state: AuthState): any => { return state.user; }, }, mutations: { saveAccessToken: (state: AuthState, token: string) => { localStorage.setItem("access_token", token); state.token = token; }, deleteAccessToken: (state: AuthState) => { localStorage.removeItem("access_token"); state.token = null; localStorage.removeItem("login"); state.user = null; }, saveUserInfo: (state: AuthState, data: any) => { state.user = data; }, }, actions: { // Make the login using `credentials`. // It returns the response in JSON format async login(context: AuthContext, credentials: any) { const api = context.rootState.api; const res = { status: -1, data: null }; console.log(credentials); await fetch(`${api}/auth/login`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(credentials), }) .then(async (response) => { const data = await response.json(); res.data = data; res.status = response.status; if (res.status != 200) { context.commit("deleteAccessToken"); } else { context.commit("saveAccessToken", data.access_token); } }) .catch((e) => { res.status = e.status; }); return res; }, logout(context: AuthContext) { context.commit("deleteAccessToken"); }, }, }; export default auth;