I am currently working on implementing user authentication and redirection logic based on the user's authentication status. For instance, if a logged-in user tries to access the login or signup page, they should be automatically redirected. To achieve this, I have set up middleware functions.
After logging in the user, the authenticateUser
action is triggered, creating the user and setting the necessary cookies and browser local storage data. However, despite verifying that these are correctly set, I encounter an issue where the redirection does not occur when visiting the login page post-login.
The first middleware, located in altauth.js, checks for user authentication as follows:
export default function (context) {
console.log(context.store.getters('profile/isAuthenticated'))
if (context.store.getters.isAuthenticated) {
context.redirect('/')
}
}
Additionally, token persistence is managed through another middleware, checkauth.js, which utilizes both Cookies and local storage to store the token:
export default function (context) {
if(context.hasOwnProperty('ssrContext')) {
context.store.dispatch('profile/initAuth', context.ssrContext.req);
} else {
context.store.dispatch('profile/initAuth', null);
}
}
Furthermore, below are the key store values pertaining to the implemented functionality:
import Cookie from 'js-cookie';
// State
export const state = () => ({
token: null,
})
// Mutations
export const mutations = {
setToken(state, token) {
state.token = token
},
clearToken(state) {
state.token = null
}
}
// Actions
export const actions = {
async authenticateUser(vuexContext, authData) {
// Authentication API endpoint URL selection based on operation type
let authUrl = 'https://look.herokuapp.com/signup/'
if (authData.isLogin) {
authUrl = 'https://look.herokuapp.com/login/'
}
return this.$axios
.$post(authUrl, authData.form)
.then(data => {
console.log(data);
// Saving received token
const token = data.token
vuexContext.commit('setToken', token)
localStorage.setItem("token", token)
Cookie.set('jwt', token);
})
.catch(e => console.log(e))
},
initAuth(vuexContext, req) {
// Initializing user authentication with stored token
let token
if (req) {
if (!req.headers.cookie) {
return;
}
// Retrieving JWT token from cookie header
const jwtCookie = req.headers.cookie
.split(';')
.find(c => c.trim().startsWith('jwt='));
if (!jwtCookie) {
return;
}
token = jwtCookie.split('=')[1];
} else {
// Fallback to local storage if no server request present
token = localStorage.getItem('token');
if (!token) {
return;
}
}
// Setting token in Vuex store
vuexContext.commit('setToken', token);
}
}
// Getters
export const getters = {
isAuthenticated(state) {
return state.token != null;
},
}
If anyone could provide insights into what might be causing the issue, I would greatly appreciate it.