Search code examples
vue.jsvuexvue-router

Where to store the user role securely in Front


I'm working on a Vuejs app and the backend is returning only a token when a user login succefully.

What I wanna do, is to store somewhere the role of the user to use it in beforeEnter() in the router.

When the user logs in, a request fetchs the user informations (with the role). But when I refresh the page or when I change the route, I lose the states.

Si I was going to put the user infos in the LocalStage but I'm pretty sure that it's not safe at all because I can edit the role in Application (in Chrome)..

I need to have the role available all the time in the router but I don't know how except with the localstorage

Any solutions?

EDIT: Because I got only a token as response from the backend. Is it good to directly call another request to fetch the userdata(including role) ?

Like so:

export function loginUser ({ commit }, payload) {
    return new Promise(resolve => {
    LoginService.login(payload)
      .then(data => {
          console.log('enter')
          console.log(data)
            let tkn = data.access_token
            Cookies.set('tkn', tkn.toString())
            Cookies.set('cntd', 'true')
     --->   UserService.getB2cUserProfile()
            .then(data => {
                commit('LOGIN_USER', data)
                // will commit the data here to change the userInfos state
                resolve(data)

            })
      })
      .catch(err => {
        console.log(err)
      })
    })
}

Solution

  • You should go with vuex with vue-persistedstate which keeps the state the same in case you refresh the page with the help of cookies that is in sync with your states so whenever any state changes it will automatically get changed in the cookies and will help you for what you want (routing and on-refresh). When you get the token after login you can set the states and using persistence state you can mention the states in the paths that you want to save for the currently logged-in user. This can help you so much as after the user logs out from your website you can again set the role and other states to default. So, In-store for vuex you can do something like this:-

    import Vue from 'vue';
    import Vuex from 'vuex';
    import createPersistedState from "vuex-persistedstate";
    import * as Cookies from "js-cookie";
    
    Vue.use(Vuex);
    export const store = new Vuex.Store({
        state: {
            auth: "false",
            role: "",
            anyotherproperty:""
        },
        getters: {
            getRole: state => {
                return state.role;
            },
            getAuth: state => {
                return state.auth;
            },
        },
        plugins: [
            createPersistedState({
                paths: ['auth', 'role'],
                storage: {
                    getItem: (key) => Cookies.get(key),
                    setItem: (key, value) =>
                        Cookies.set(key, value, { expires: 7}),
                    removeItem: (key) => Cookies.remove(key),
                },
            }),
        ],
        mutations: {
            //mutation will change the states like auth and role
        },
        actions: { //your actions which commit a mutation
        }
    
    });
    

    Then, In the router, you can use the global states defined in vuex and check if the user role is A or B or default and if auth is true and false. This will help you manage everything very well.