DEV Community

Discussion on: Secure authentication in Nuxt SPA with Laravel as back-end

Collapse
stefant123 profile image
StefanT123 Author

I would just directly return the user from the login route in Laravel along wiith the token, that way I wouldn't need to send two requests, one for the token and another for the user.

My response would look something like this

return response([
    'user' => $user, // or even better wrap it in resource
    'token' => $token,
    'expiresIn' => $expiresIn,
    'message' => 'You have been logged in'
], 200);
Collapse
abronson07013635 profile image
ABronson

Awesome, thanks for the advice. I'm a bit of a noob with Vue/Nuxt, maybe there's a cleaner way to do it, but something like this seems to work (setting user on login, clearing user on logout).

Authcontroller.php
return response([
'user' => $user->name,
'token' => $resp->access_token,
'expiresIn' => $resp->expires_in,
'message' => 'You have been logged in',
], 200);

Added the user in store/index.js
export const state = () => ({
token: null,
user: null,
});

Added Vuex mutations:
SET_USER(state, user) {
state.user = user;
}
REMOVE_USER(state, user) {
state.user = null;
},

Added Vuex actions:
setUser({commit}, user) {
commit('SET_USER', user);
},
removeUser({commit}) {
commit('REMOVE_USER');
}

Changed logout method
logout: function() {
this.$axios.post('/api/logout')
.then(resp => {
this.$store.dispatch('removeUser');
this.$store.dispatch('logout');
this.$router.push('/login');
})
.catch(errors => {
console.log(errors);
});
}

Login.vue, login() method:
login() {
this.$axios.$post('/api/login', this.form)
.then(({token, expiresIn, user}) => {
this.$store.dispatch('setToken', {token, expiresIn});
this.$store.dispatch('setUser', user);
this.$router.push('/');
})
.catch(errors => {
console.log(errors);
})
}

  • A computed value for the current user in my NavBar.vue component, to display logged in users name currentUser() { return this.$store.state.user; },