Library/frontend/src/auth/index.js

91 lines
2.1 KiB
JavaScript
Raw Normal View History

2017-11-09 11:19:53 +00:00
import {HTTP} from '../http-common'
2017-11-10 10:49:02 +00:00
import router from '../router'
2017-11-09 11:19:53 +00:00
// const API_URL = 'http://localhost:8082/api/v1/'
// const LOGIN_URL = 'http://localhost:8082/login'
export default {
user: {
2017-11-20 14:42:36 +00:00
authenticated: false,
infos: {}
2017-11-09 11:19:53 +00:00
},
2017-11-09 13:24:59 +00:00
login (context, creds, redirect) {
2017-11-09 11:19:53 +00:00
HTTP.post('login', {
username: creds.username,
password: creds.password
})
.then(response => {
// Save the token to local storage for later use
localStorage.setItem('token', response.data.token)
// Tell others the user is autheticated
this.user.authenticated = true
2017-11-20 15:14:44 +00:00
this.getUserInfos()
2017-11-09 13:24:59 +00:00
// Hide the loader
context.loading = false
// Redirect if nessecary
if (redirect) {
2017-11-17 13:07:41 +00:00
router.push({ name: redirect })
2017-11-09 13:24:59 +00:00
}
2017-11-09 11:19:53 +00:00
})
.catch(e => {
2017-11-09 13:24:59 +00:00
// Hide the loader
context.loading = false
if (e.response) {
context.error = e.response.data.message
2017-11-22 13:17:29 +00:00
if (e.response.status === 401) {
context.error = context.translate('login').wrong
}
2017-11-09 13:24:59 +00:00
}
2017-11-09 11:19:53 +00:00
})
},
logout () {
localStorage.removeItem('token')
2017-11-20 14:44:03 +00:00
router.push({ name: 'login' })
2017-11-09 11:19:53 +00:00
this.user.authenticated = false
},
checkAuth () {
let jwt = localStorage.getItem('token')
2017-11-20 15:14:44 +00:00
this.getUserInfos()
this.user.authenticated = false
2017-11-09 11:19:53 +00:00
if (jwt) {
2017-11-20 15:14:44 +00:00
let infos = this.user.infos
let ts = Math.round((new Date()).getTime() / 1000)
2017-11-20 14:42:36 +00:00
if (infos.exp >= ts) {
this.user.authenticated = true
}
2017-11-09 11:19:53 +00:00
}
},
2017-11-20 14:42:36 +00:00
getUserInfos () {
let jwt = localStorage.getItem('token')
if (jwt) {
2017-11-20 15:14:44 +00:00
this.user.infos = this.parseJwt(localStorage.getItem('token'))
2017-11-20 14:42:36 +00:00
return this.parseJwt(localStorage.getItem('token'))
} else {
return {}
}
},
parseJwt (token) {
let base64Url = token.split('.')[1]
let base64 = base64Url.replace('-', '+').replace('_', '/')
return JSON.parse(window.atob(base64))
},
2017-11-09 11:19:53 +00:00
getAuthHeader () {
return {
'Authorization': 'Bearer ' + localStorage.getItem('token')
}
},
getToken () {
return localStorage.getItem('token')
2017-11-09 11:19:53 +00:00
}
}