Revert use of cookies, go back to using a JWT

This commit is contained in:
Dane Everitt 2018-06-06 22:49:44 -07:00
parent 871147f2d9
commit 03c83c084a
No known key found for this signature in database
GPG key ID: EEA66103B3D71F53
8 changed files with 80 additions and 44 deletions

View file

@ -1,3 +1,5 @@
import User from './../models/user';
/**
* We'll load the axios HTTP library which allows us to easily issue requests
* to our Laravel back-end. This library automatically handles sending the
@ -7,6 +9,7 @@
let axios = require('axios');
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
axios.defaults.headers.common['Accept'] = 'application/json';
axios.defaults.headers.common['Authorization'] = `Bearer ${User.getToken()}`;
if (typeof phpdebugbar !== 'undefined') {
axios.interceptors.response.use(function (response) {

View file

@ -1,21 +1,37 @@
import axios from './../helpers/axios';
import isString from 'lodash/isString';
import jwtDecode from 'jwt-decode';
export default class User {
/**
* Get a new user model by hitting the Panel API using the authentication token
* provided. If no user can be retrieved null will be returned.
* Get a new user model from the JWT.
*
* @return {User|null}
* @return {User | null}
*/
static fromCookie() {
axios.get('/api/client/account')
.then(response => {
return new User(response.data.attributes);
})
.catch(err => {
console.error(err);
return null;
});
static fromToken(token) {
if (!isString(token)) {
token = localStorage.getItem('token');
}
if (!isString(token) || token.length < 1) {
return null;
}
const data = jwtDecode(token);
if (data.user) {
return new User(data.user);
}
return null;
}
/**
* Return the JWT for the authenticated user.
*
* @returns {string | null}
*/
static getToken()
{
return localStorage.getItem('token');
}
/**

View file

@ -4,7 +4,7 @@ const route = require('./../../../../../vendor/tightenco/ziggy/src/js/route').de
export default {
namespaced: true,
state: {
user: null,
user: User.fromToken(),
},
getters: {
/**
@ -32,7 +32,7 @@ export default {
}
if (response.data.complete) {
commit('login', {cookie: response.data.cookie, user: response.data.user});
commit('login', {jwt: response.data.jwt});
return resolve({
complete: true,
intended: response.data.intended,
@ -59,12 +59,9 @@ export default {
},
},
mutations: {
login: function (state, {cookie, user}) {
state.user = new User(user);
localStorage.setItem('token', JSON.stringify({
name: cookie.name,
value: cookie.value,
}));
login: function (state, {jwt}) {
localStorage.setItem('token', jwt);
state.user = User.fromToken(jwt);
},
logout: function (state) {
localStorage.removeItem('token');