user.js
2.95 KB
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import Cookie from 'js-cookie';
import {host} from '../env';
export const state = () => ({
me: null,
cookie: '',
});
export const mutations = {
loadMe(state, payload) {
const {user} = payload;
state.me = user;
},
login(state, payload) {
const {user} = payload;
state.me = user;
},
logout(state) {
state.me = null;
},
setToken(state, payload) {
const {cookie} = payload;
state.cookie = cookie;
},
};
export const actions = {
//mutation{commit} 호출
loadMe({commit}, payload) {
return new Promise(async (resolve, reject) => {
try {
const {cookie} = payload;
this.$axios.defaults.headers.common['Authorization'] = `Token ${cookie}`;
const res = await this.$axios.get(`http://${host}/api/auth/loadMe`, {
withCredentials: true
});
commit('loadMe', {user: res.data});
commit('setToken', {cookie});
return resolve();
} catch (e) {
console.error(e);
return reject(e);
}
})
},
/* signUp */
signUp({commit}, payload) {
return new Promise(async (resolve, reject) => {
try {
const {email, username, password} = payload;
const res = await this.$axios.post(`http://${host}/api/auth/signUp`, {
email, username, password
}, {
withCredentials: true
});
const {user, token} = res.data;
if (process.browser) {
localStorage.setItem('accessToken', token);
Cookie.set('accessToken', token);
console.log(localStorage);
}
commit('login', {user});
return resolve();
} catch (e) {
console.log(res.data);
console.error(e);
return reject(e);
}
})
},
/* login */
login({commit}, payload) {
return new Promise(async (resolve, reject) => {
try {
const {username, password} = payload;
const res = await this.$axios.post(`http://${host}/api/auth/login`, {
username, password
}, {
withCredentials: true
});
console.log(res);
const {user, token} = res.data;
console.log(user, token);
if (process.browser) {
localStorage.setItem('accessToken', token);
Cookie.set('accessToken', token);
console.log(localStorage);
}
commit('login', {user});
return resolve();
} catch (e) {
console.error(e);
return reject(e);
}
});
},
/* logout */
logout({commit}) {
return new Promise(async (resolve, reject) => {
try {
// await this.$axios.get('http://127.0.0.1:8000/user/logout', {
// withCredentials: true
// });
if (process.browser) {
localStorage.removeItem('accessToken');
Cookie.remove('accessToken');
}
commit('logout');
return resolve();
} catch (e) {
console.error(e);
return reject(e);
}
})
}
};