summaryrefslogtreecommitdiff
path: root/app/src/store/modules
diff options
context:
space:
mode:
authorSanto Cariotti <santo@dcariotti.me>2022-11-12 17:14:40 +0100
committerSanto Cariotti <santo@dcariotti.me>2022-11-12 17:14:40 +0100
commit5e89ad0836ca38b132d1748603be7d8593b9bcb2 (patch)
tree25ec2a2f62b95616b5587754f1bded6e34f890ec /app/src/store/modules
parente4e6653f754b6d2857bcf03a89d26c3e24083271 (diff)
Add signup page
Diffstat (limited to 'app/src/store/modules')
-rw-r--r--app/src/store/modules/auth.ts80
1 files changed, 80 insertions, 0 deletions
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<AuthState, RootState>;
+
+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;