-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathauth.js
65 lines (59 loc) · 1.64 KB
/
auth.js
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
/* eslint-disable promise/param-names */
import { AUTH_REQUEST, AUTH_ERROR, AUTH_SUCCESS, AUTH_LOGOUT } from '../actions/auth'
import axios from 'axios'
var config = {};
const state = { token: localStorage.getItem('auth-user-token') || '', status: '', hasLoadedOnce: false }
const getters = {
isAuthenticated: state => !!state.token,
authStatus: state => state.status
}
const actions = {
[AUTH_REQUEST]: ({commit, dispatch}, user) => {
return new Promise((resolve, reject) => {
commit(AUTH_REQUEST)
//axios.post('http://localhost:3001/api/authenticate', user, config)
axios.post('/api/authenticate', user, config)
.then(resp => {
localStorage.setItem('auth-user-token', resp.data.data.token)
axios.defaults.headers.common['bearer'] = localStorage.getItem('auth-user-token')
commit(AUTH_SUCCESS, resp.data.data)
resolve(resp.data.data)
})
.catch(err => {
commit(AUTH_ERROR, err)
localStorage.removeItem('auth-user-token')
reject(err)
})
})
},
[AUTH_LOGOUT]: ({commit, dispatch}) => {
return new Promise((resolve, reject) => {
commit(AUTH_LOGOUT)
localStorage.removeItem('auth-user-token')
resolve()
})
}
}
const mutations = {
[AUTH_REQUEST]: (state) => {
state.status = 'loading'
},
[AUTH_SUCCESS]: (state, resp) => {
state.status = 'success'
state.token = resp.token
state.hasLoadedOnce = true
},
[AUTH_ERROR]: (state) => {
state.status = 'error'
state.hasLoadedOnce = true
},
[AUTH_LOGOUT]: (state) => {
state.token = ''
}
}
export default {
state,
getters,
actions,
mutations
}