Newer
Older
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
import Vue from 'vue'
import config from '@/config'
import logger from '@/logging'
import cache from '@/cache'
import router from '@/router'
// import favoriteTracks from '@/favorites/tracks'
const LOGIN_URL = config.API_URL + 'token/'
const USER_PROFILE_URL = config.API_URL + 'users/users/me/'
export default {
namespaced: true,
state: {
authenticated: false,
username: '',
availablePermissions: {},
profile: null,
token: ''
},
getters: {
header: state => {
return 'JWT ' + state.token
}
},
mutations: {
profile: (state, value) => {
state.profile = value
},
authenticated: (state, value) => {
state.authenticated = value
},
username: (state, value) => {
state.username = value
},
token: (state, value) => {
state.token = value
}
},
actions: {
// Send a request to the login URL and save the returned JWT
login ({commit, dispatch, state}, {next, credentials, onError}) {
let resource = Vue.resource(LOGIN_URL)
return resource.save({}, credentials).then(response => {
logger.default.info('Successfully logged in as', credentials.username)
commit('token', response.data.token)
cache.set('token', response.data.token)
commit('username', credentials.username)
cache.set('username', credentials.username)
commit('authenticated', true)
dispatch('fetchProfile')
// Redirect to a specified route
router.push(next)
}, response => {
logger.default.error('Error while logging in', response.data)
onError(response)
})
},
logout ({commit}) {
cache.clear()
commit('authenticated', false)
commit('profile', null)
logger.default.info('Log out, goodbye!')
router.push({name: 'index'})
},
check ({commit, dispatch, state}) {
logger.default.info('Checking authentication...')
var jwt = cache.get('token')
var username = cache.get('username')
if (jwt) {
commit('authenticated', true)
commit('username', username)
commit('token', jwt)
logger.default.info('Logged back in as ' + username)
dispatch('fetchProfile')
} else {
logger.default.info('Anonymous user')
commit('authenticated', false)
}
},
fetchProfile ({commit, state}) {
let resource = Vue.resource(USER_PROFILE_URL)
return resource.get({}).then((response) => {
logger.default.info('Successfully fetched user profile')
let data = response.data
commit('profile', data)
// favoriteTracks.fetch()
console.log('AFTER')
Object.keys(data.permissions).forEach(function (key) {
// this makes it easier to check for permissions in templates
state.availablePermissions[key] = data.permissions[String(key)].status
})
return response.data
}, (response) => {
logger.default.info('Error while fetching user profile')
})
}
}
}