75 lines
1.7 KiB
JavaScript
75 lines
1.7 KiB
JavaScript
import {HTTP} from '../http-common'
|
|
import router from '../router'
|
|
// const API_URL = 'http://localhost:8082/api/v1/'
|
|
// const LOGIN_URL = 'http://localhost:8082/login'
|
|
|
|
export default {
|
|
|
|
user: {
|
|
authenticated: false
|
|
},
|
|
|
|
login (context, creds, redirect) {
|
|
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
|
|
|
|
// Hide the loader
|
|
context.loading = false
|
|
|
|
// Redirect if nessecary
|
|
if (redirect) {
|
|
router.push({ name: redirect })
|
|
}
|
|
})
|
|
.catch(e => {
|
|
// Hide the loader
|
|
context.loading = false
|
|
if (e.response) {
|
|
context.error = e.response.data.Message
|
|
}
|
|
})
|
|
},
|
|
|
|
logout () {
|
|
localStorage.removeItem('token')
|
|
router.push({ name: 'home' })
|
|
this.user.authenticated = false
|
|
},
|
|
|
|
checkAuth () {
|
|
let jwt = localStorage.getItem('token')
|
|
this.user.authenticated = false
|
|
if (jwt) {
|
|
let jwtinfos = this.parseJwt(jwt)
|
|
let ts = Math.round((new Date()).getTime() / 1000)
|
|
if (jwtinfos.exp >= ts) {
|
|
this.user.authenticated = true
|
|
}
|
|
}
|
|
},
|
|
|
|
parseJwt (token) {
|
|
let base64Url = token.split('.')[1]
|
|
let base64 = base64Url.replace('-', '+').replace('_', '/')
|
|
return JSON.parse(window.atob(base64))
|
|
},
|
|
|
|
getAuthHeader () {
|
|
return {
|
|
'Authorization': 'Bearer ' + localStorage.getItem('token')
|
|
}
|
|
},
|
|
|
|
getToken () {
|
|
return localStorage.getItem('token')
|
|
}
|
|
}
|