Auth not accessible in vuex-module after page reload or direct access - vue.js

I have an authentication on my nuxt web-app, using the nuxt/auth module. I also use modular vuex stores to handle different states. After I login, everything is fine and I can navigate through the app normally. But when I try to reload the page or access it directly through a URL, the user is not accessible, thus, the whole web-app becomes unusable. I try to access the user object with this.context.rootState.auth.user, which is null after page-reload or direct access. Strangely enough, this only happens in production.
I already tried to add an if-guard, but sadly the getter is not reactive. Probably because it´s a nested object. This is my current getter:
get someGetter() {
if (!this.context.rootState.auth.user) {
return []
}
const userId = this.context.rootState.auth.user.id as string
const arr = []
for (const item of this.items) {
// Using userId to add something to arr
}
return arr
}
Is there a way to force nuxt to finish the authentication before initialising the vuex-modules, or to make this getter reactive, so it will trigger again, when the user object is accessible?
This is what my auth-config looks like in nuxt.config.ts:
auth: {
strategies: {
local: {
_scheme: '#/auth/local-scheme',
endpoints: {
login: {
url: '/api/authenticate',
method: 'post',
propertyName: false
},
logout: { url: '/api/logout', method: 'post' },
user: { url: '/api/users/profile', propertyName: false }
}
},
// This dummy setting is required so we can extend the default local scheme
dummy: {
_scheme: 'local'
}
},
redirect: {
logout: '/login'
}
}
EDIT
I resolved this by following Raihan Kabir´s answer. Using vuex-persistedstate in an auth-plugin, which is triggered every time the server renders the page. The plugin saves the userId in a cookie, so the store can use it as a fallback, if the auth-module isn´t ready.

The thing is, the vuex clears data on reload/refresh to keep credentials secure. That's what vuex is. If you want to store data for long time without being interrupted after reloading, you should use localstorage for that. But localstorage is not recommended for storing credentials.
If you need only user_id to keep in the vuex, use Cookie instead. And try something like this in your store's index.js file -
export const actions = {
// This one runs on the beginning of reload/refresh
nuxtServerInit ({ commit }, { req }) {
if (req.headers.cookie) {
const parsed = cookieparser.parse(req.headers.cookie)
try {
// get user id that you would set on auth as Cookie
user_id = parsed.uid
} catch (err) {
// error here...
}
}
// perform login and store info on vuex store
commit('authUserOnReload', user_id)
},
}
// Define Mutations
export const mutations = {
authUserOnReload (state, user_id) {
// perform login here and store user
}
}

Related

Insert localstorage with vuex

My script I'm using axios and vuex but it was necessary to make a change from formData to Json in the script and with that it's returning from the POST/loginB2B 200 api, but it doesn't insert in the localstorage so it doesn't direct to the dashboard page.
**Auth.js**
import axios from "axios";
const state = {
user: null,
};
const getters = {
isAuthenticated: (state) => !!state.user,
StateUser: (state) => state.user,
};
async LogIn({commit}, user) {
await axios.post("loginB2B", user);
await commit("setUser", user.get("email"));
},
async LogOut({ commit }) {
let user = null;
commit("logout", user);
},
};
**Login.vue**
methods: {
...mapActions(["LogIn"]),
async submit() {
/*const User = new FormData();
User.append("email", this.form.username)
User.append("password", this.form.password)*/
try {
await this.LogIn({
"email": this.form.username,
"password": this.form.password
})
this.$router.push("/dashboard")
this.showError = false
} catch (error) {
this.showError = true
}
},
},
app.vue
name: "App",
created() {
const currentPath = this.$router.history.current.path;
if (window.localStorage.getItem("authenticated") === "false") {
this.$router.push("/login");
}
if (currentPath === "/") {
this.$router.push("/dashboard");
}
},
};
The api /loginB2B returns 200 but it doesn't create the storage to redirect to the dashboard.
I use this example, but I need to pass json instead of formData:
https://www.smashingmagazine.com/2020/10/authentication-in-vue-js/
There are a couple of problems here:
You do a window.localStorage.getItem call, but you never do a window.localStorage.setItem call anywhere that we can see, so that item is probably always empty. There also does not seem to be a good reason to use localStorage here, because you can just access your vuex store. I noticed in the link you provided that they use the vuex-persistedstate package. This does store stuff in localStorage by default under the vuex key, but you should not manually query that.
You are using the created lifecycle hook in App.vue, which usually is the main component that is mounted when you start the application. This also means that the code in this lifecycle hook is executed before you log in, or really do anything in the application. Instead use Route Navigation Guards from vue-router (https://router.vuejs.org/guide/advanced/navigation-guards.html).
Unrelated, but you are not checking the response from your axios post call, which means you are relying on this call always returning a status code that is not between 200 and 299, and that nothing and no-one will ever change the range of status codes that result in an error and which codes result in a response. It's not uncommon to widen the range of "successful" status codes and perform their own global code based on that. It's also not uncommon for these kind of endpoints to return a 200 OK status code with a response body that indicates that no login took place, to make it easier on the frontend to display something useful to the user. That may result in people logging in with invalid credentials.
Unrelated, but vuex mutations are always synchronous. You never should await them.
There's no easy way to solve your problem, so I would suggest making it robust from the get-go.
To properly solve your issue I would suggest using a global navigation guard in router.js, mark with the meta key which routes require authentication and which do not, and let the global navigation guard decide if it lets you load a new route or not. It looks like the article you linked goes a similar route. For completeness sake I will post it here as well for anyone visiting.
First of all, modify your router file under router/index.js to contain meta information about the routes you include. Load the store by importing it from the file where you define your store. We will then use the Global Navigation Guard beforeEach to check if the user may continue to that route.
We define the requiresAuth meta key for each route to check if we need to redirect someone if they are not logged in.
router/index.js
import Vue from 'vue';
import VueRouter from 'vue-router';
import store from '../store';
Vue.use(VueRouter);
const routes = [
{
path: '/',
name: 'Dashboard',
component: Dashboard,
meta: {
requiresAuth: true
}
},
{
path: '/login',
name: 'Login',
component: Login,
meta: {
requiresAuth: false
}
}
];
// Create a router with the routes we just defined
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
// This navigation guard is called everytime you go to a new route,
// including the first route you try to load
router.beforeEach((to, from, next) => {
// to is the route object that we want to go to
const requiresAuthentication = to.meta.requiresAuth;
// Figure out if we are logged in
const userIsLoggedIn = store.getters['isAuthenticated']; // (maybe auth/isAuthenticated if you are using modules)
if (
(!requiresAuthentication) ||
(requiresAuthentication && userIsLoggedIn)
) {
// We meet the requirements to go to our intended destination, so we call
// the function next without any arguments to go where we intended to go
next();
// Then we return so we do not run any other code
return;
}
// Oh dear, we did try to access a route while we did not have the required
// permissions. Let's redirect the user to the login page by calling next
// with an object like you would do with `this.$router.push(..)`.
next({ name: 'Login' });
});
export default router;
Now you can remove the created hook from App.vue. Now when you manually change the url in the address bar, or use this.$router.push(..) or this.$router.replace(..) it will check this function, and redirect you to the login page if you are not allowed to access it.

Nuxt: Fetching data only on server side

I am using Github's API to fetch the list of my pinned repositories, and I put the call in the AsyncData method so that I have the list on the first render. But I just learnt that AsyncData is called once on ServerSide, then everytime the page is loaded on the client. That means that the client no longer has the token to make API calls, and anyways, I wouldn't let my Github token in the client.
And when I switch page (from another page to the page with the list) the data is not there I just have the default empty array
I can't figure out what is the best way to be sure that my data is always loaded on server side ?
export default defineComponent({
name: 'Index',
components: { GithubProject, Socials },
asyncData(context: Context) {
return context.$axios.$post<Query<UserPinnedRepositoriesQuery>>('https://api.github.com/graphql', {
query,
}, {
headers: {
// Token is defined on the server, but not on the client
Authorization: `bearer ${process.env.GITHUB_TOKEN}`,
},
})
.then((data) => ({ projects: data.data.user.pinnedItems.nodes }))
.catch(() => {});
},
setup() {
const projects = ref<Repository[]>([]);
return {
projects,
};
},
});
Wrap your request in if(process.server) within the asyncData method of the page.
If you absolutely require the server-side to call and cannot do it from the client side, then you can just manipulate the location.href to force the page to do a full load.
You should use Vuex with nuxtServerInit.
nuxtServerInit will fire always on first page load no matter on what page you are. So you should navigate first to store/index.js.
After that you create an state:
export const state = () => ({
data: []
})
Now you create the action that is always being executed whenever you refresh the page. Nuxt have access to the store even if its on the server side.
Now you need to get the data from the store in your component:
export const actions = {
async nuxtServerInit ({ state }, { req }) {
let response = await axios.get("some/path/...");
state.data = response.data;
}
}
You can store your token in an cookie. Cookies are on the client side but the nuxtServerInit has an second argument. The request req. With that you are able to access the headers and there is your cookie aswell.
let cookie = req.headers.cookie;

Keep Vuex state data without vuex-persist

weird question but i don't find an answer anywhere..
I return user data from an API call to Vuex. I save my user object into the Vuex state, along with a Token. (User object and Token are created and send back from Server to Vuex at the same time.)
Everything runs perfect and on the initialization of the component i fetch with a getter the user name etc.
But when i refresh i loose the user object from the state. But, i do not loose the Token. Which is weird cause i create them and return them together.
The question is, how can i keep the user in the state until i logout?
I don't need to keep them in localStorage or inside a cookie cause they are sensitive data (user). I just want to get them through a getter from my store. Which is the correct way to do it.
So vuex-persist is not an option..
Below you see my code:
store.js:
state: {
status: '',
token: localStorage.getItem('token'),
user: {}
},
mutations: {
auth_success(state, { token, user }) {
state.status = 'success';
state.token = token;
state.user = user;
},
actions: {
login({ commit }, user) {
return new Promise((resolve, reject) => {
commit('auth_request');
axios({
url: 'http://localhost:8085/login',
data: user,
method: 'POST'
.then((resp) => {
const token = resp.data.token;
const user = resp.data.user;
axios.defaults.headers.common['Authorization'] = token;
commit('auth_success', { token, user });
})
.catch((err) => {
commit('auth_error');
localStorage.removeItem('token');
reject(err);
});
}
},
getters: {
isLoggedIn(state) {
return state.token;
},
getUser(state){
return state.user;
}
User.vue:
<template>
<v-container>
<v-layout row wrap>
Welcome {{this.user.fullName}}
</v-layout>
</v-container>
</template>
<script>
export default {
data: function() {
return {
user: {}
}
},
mounted() {
this.getUser();
},
methods: {
getUser() {
return (this.user = this.$store.getters.getUser);
}
}
}
</script>
So to sum up:
Token stays in Vuex, user data does not. How to keep them in state without local Storage or cookies?
Any help would be greatly appreciated!
Basically, as Sang Đặng mentioned, if you want to have user data in your vuex (without storing it on the user side) you need to fetch them after every refresh. Refreshing the page means that whole Vue application (and your Vuex state) is removed from the memory (user's browser), which causes that you lose your current store data. token is also removed from the memory, but you load it on your store initialisation:
state: {
token: localStorage.getItem('token'),
...
}
Because of this you are seeing token "kept" in store, while other user data not. There are many ways to fetch user data after refresh - like mentioned beforeRouteEnter. Basically if you want to fetch them on the application load, so you can use Vue.created hook for example. You can also use lazy-loading in your getUser method - if there is no user data - fetch them from your API. Here you can read more about authentication patterns in SPA - for example using OAuth.

Middleware executing before Vuex Store restore from localstorage

In nuxtjs project, I created an auth middleware to protect page.
and using vuex-persistedstate (also tried vuex-persist and nuxt-vuex-persist) to persist vuex store.
Everything is working fine when navigating from page to page, but when i refresh page or directly land to protected route, it redirect me to login page.
localStorage plugin
import createPersistedState from 'vuex-persistedstate'
export default ({ store }) => {
createPersistedState({
key: 'store-key'
})(store)
}
auth middleware
export default function ({ req, store, redirect, route }) {
const userIsLoggedIn = !!store.state.auth.user
if (!userIsLoggedIn) {
return redirect(`/auth/login?redirect=${route.fullPath}`)
}
return Promise.resolve()
}
I solved this problem by using this plugin vuex-persistedstate instead of the vuex-persist plugin. It seems there's some bug (or probably design architecture) in vuex-persist that's causing it.
With the Current approach, we will always fail.
Actual Problem is Vuex Store can never be sync with server side Vuex store.
The fact is we only need data string to be sync with client and server (token).
We can achieve this synchronization with Cookies. because cookies automatically pass to every request from browser. So we don't need to set to any request. Either you just hit the URL from browser address bar or through navigation.
I recommend using module 'cookie-universal-nuxt' for set and remove of cookies.
For Setting cookie after login
this.$cookies.set('token', 'Bearer '+response.tokens.access_token, { path: '/', maxAge: 60 * 60 * 12 })
For Removing cookie on logout
this.$cookies.remove('token')
Please go through the docs for better understanding.
Also I'm using #nuxt/http module for api request.
Now nuxt has a function called nuxtServerInit() in vuex store index file. You should use it to retrieve the token from request and set to http module headers.
async nuxtServerInit ({dispatch, commit}, {app, $http, req}) {
return new Promise((resolve, reject) => {
let token = app.$cookies.get('token')
if(!!token) {
$http.setToken(token, 'Bearer')
}
return resolve(true)
})
},
Below is my nuxt page level middleware
export default function ({app, req, store, redirect, route, context }) {
if(process.server) {
let token = app.$cookies.get('token')
if(!token) {
return redirect({path: '/auth/login', query: {redirect: route.fullPath, message: 'Token Not Provided'}})
} else if(!isTokenValid(token.slice(7))) { // slice(7) used to trim Bearer(space)
return redirect({path: '/auth/login', query: {redirect: route.fullPath, message: 'Token Expired'}})
}
return Promise.resolve()
}
else {
const userIsLoggedIn = !!store.state.auth.user
if (!userIsLoggedIn) {
return redirect({path: '/auth/login', query: {redirect: route.fullPath}})
// return redirect(`/auth/login?redirect=${route.fullPath}`)
} else if (!isTokenValid(store.state.auth.tokens.access_token)) {
return redirect({path: '/auth/login', query: {redirect: route.fullPath, message: 'Token Expired'}})
// return redirect(`/auth/login?redirect=${route.fullPath}&message=Token Expired`)
} else if (isTokenValid(store.state.auth.tokens.refresh_token)) {
return redirect(`/auth/refresh`)
} else if (store.state.auth.user.role !== 'admin')
return redirect(`/403?message=Not having sufficient permission`)
return Promise.resolve()
}
}
I have write different condition for with different source of token, as in code. On Server Process i'm getting token from cookies and on client getting token store. (Here we can also get from cookies)
After this you may get Some hydration issue because of store data binding in layout. To overcome this issue use <no-ssr></no-ssr> wrapping for such type of template code.

Why is my Vuex getter returning TRUE on the client side and FALSE on the server side?

I'm using NUXT middleware to check if a user is logged in or not, and protect certain routes accordingly. The problem is, when a logged-in user refreshes the page on one of the protected routes, the session is lost.
I have a getter in my Vuex store state (using NUXT):
getters: {
isLoggedIn (state) {
return !isEmpty(state.auth.email) && !isEmpty(state.auth.token)
}
}
I'm accessing this getter in middleware to redirect unauthenticated users to a login page:
let isLoggedIn = context.store.getters.isLoggedIn
if (!isLoggedIn && protectedRoutes.includes(context.route.name)) {
let language = context.store.language ? context.store.language : 'en'
context.redirect(`/${language}/login`)
}
But it's not working. When I console.log() the value of this getter, I get TRUE on the client side and FALSE on the server side. How can I keep them both in sync with Vue/Vuex?
Furthermore, whenever I console.log() the context object on the server side, it appears to be in its initial state. There must be something fundamentally wrong with my approach.
When user refresh a page all vuex state is lost and start from new. You need to initialize user somewhere like nuxtServerInit
actions: {
nuxtServerInit ({ commit }, { req }) {
if (req.session.user) {
commit('user', req.session.user)
}
}
}