0
votes

i am developing a website where i use Firebase and Vue js. I do state management with vuex. I am stuck when i referesh tha page the token doesn't reload. Until now i havel implemented the a action called autoSignIn he's task is keep user logged after refresh the page. I tried the same way with token, but it seems doesn't work. I can't find out what i am doing wrong? My idea is: when a user refresh the page, it also has to reload the token as do for user authetication.

When reload the page, the program what does is: Call the getter, and the getter is null. Then call the action autoSignIn.

¿How can i call first autoSignWhen page Refresh for token? Beacause i do same for user authentication and it's work

It is a good paractice to save token in Session storage, cookies or localStorage?

When i sing in for the first time it's wrok fine, but when refresh the page, it show next Error. https://i.stack.imgur.com/Suhfl.png

Here is my auth handler, where i control user auth in page refresh.

router.beforeEach(async (to, from, next) => {
    const user = await new Promise((resolve) => {
        firebase.auth().onAuthStateChanged(async user => {
             await store.dispatch("autoSignIn", user),
            resolve(user)
        });

    });

Inside autoSignIn i implemented the code to commit token in state.

 autoSignIn ({commit},payload) {

            if (payload !== null){
                commit('setUser',{email:payload.email, userId:payload.uid})
                payload.getIdTokenResult(true).then(token =>{
                    commit('setToken',token)
                    console.log(token)
                })
            }

        },

Here is my getter of token:

 getToken:(state) => {
            return state.token !== null && state.user !== null ? state.token : null
        }
`````

I use getter in this action to retrieve certain depending on user role.

`````
getEventsByUser({getters,commit}){
            let data = [];

                if (getters.getToken.claims.admin) {
                    firebase.database().ref('usuario')
                        .on('value',event =>{
                            event.forEach(user =>{
                                user.child('eventos').forEach(evento =>{
                                    data.push({ "id": evento.key, ...evento.val() })
                                })
                            });
                            commit('setEventsByUser',data)
                        });

                }else if( getters.getToken.claims.student){
                    firebase.database().ref('usuario/' + getters.isAuthenticated.userId + '/eventos/')
                        .on("value", eventos =>{
                            eventos.forEach(evento =>{
                                data.push({"id":evento.key, ...evento.val()})
                            });
                            commit('setEventsByUser',data)
                        })
                }


        }
````

This is my componente from where i call the action getEventByUser for getting data.
````
computed:{
            getEventsByUser(){
                return  this.$store.getters.getEventsByUser;
            },

        },

        mounted() {
            this.$store.dispatch('getEventsByUser')
        },
````






1

1 Answers

0
votes

In order for you to actually make the token consitant throughout the application you can store the token in local storage once you login.

const token = res.data.access_token;
localStorage.setItem('access_token', token);

Everytime you reload the page you can take the token from local storage and save it vuex. You can create a js file under plugins and have the below code in it.

export default ({store}) => {

  const token = localStorage.getItem('access_token') || null;

  store.commit('retrieveToken', token);

}