From 5e89ad0836ca38b132d1748603be7d8593b9bcb2 Mon Sep 17 00:00:00 2001 From: Santo Cariotti Date: Sat, 12 Nov 2022 17:14:40 +0100 Subject: Add signup page --- app/src/store/modules/auth.ts | 80 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 app/src/store/modules/auth.ts (limited to 'app/src/store/modules/auth.ts') diff --git a/app/src/store/modules/auth.ts b/app/src/store/modules/auth.ts new file mode 100644 index 0000000..b511bff --- /dev/null +++ b/app/src/store/modules/auth.ts @@ -0,0 +1,80 @@ +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; -- cgit v1.2.3-18-g5258