1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
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;
|