skip to Main Content

I’m using Nuxt with Firebase auth, but having problems with redirecting to restricted page after login. Login works fine, but when I redirect the user to his profile page after login it redirects to ‘/login’ instead of ‘/profile’ – like it didn’t notice the login yet. But I can access to the profile page after normally. Here are my codes. Any help appriciated.

middleware/auth.js

export default function ({ store, redirect }) {
if (!store.getters.isLoggedIn) {
  return redirect('/login')
}

}

Login method

async login() {
        await this.$fire.auth.signInWithEmailAndPassword(this.formPrijava.email, this.formPrijava.geslo)
        .then(data => {
            this.$modal.hideAll();
            alert(data.user.uid);
            this.$router.push('profil');
        })
        .catch(function(error) {
        var errorCode = error.code;
        var errorMessage = error.message;
        if (errorCode === 'auth/wrong-password') {
            alert('Wrong password.');
        } else {
            alert(errorMessage);
        }
        console.log(error);
        });
    }

And on /profile I’m using middleware: ‘auth’.

I’ll add mutations.js, getters.js and state.js just in case.

getters.js

    export default {
    isLoggedIn: (state) => {
      try {
        return state.authUser.uid !== null
      } catch {
        return false
      }
    }
  }

mutations.js

import initialState from './state'

export default {
  RESET_STORE: (state) => {
    Object.assign(state, initialState())
  },

  SET_AUTH_USER: (state, { authUser }) => {
    state.authUser = {
      uid: authUser.uid,
      email: authUser.email
    }
  }
}

state.js

export default () => ({
    authUser: null
})

2

Answers


  1. Not sure, but I think you have typo on router.push

    enter image description here

    Should the path string be ‘profile’ ?

    Login or Signup to reply.
  2. You never update your vuex store after login that’s why the middleware still redirects you to the login page as this condition is still true:

    export default function ({ store, redirect }) {
    if (!store.getters.isLoggedIn) {
      return redirect('/login')
    }
    

    After login with firebase you have to dispatch an action to update the vuex store:

    await this.$fire.auth.signInWithEmailAndPassword(this.formPrijava.email, this.formPrijava.geslo)
            .then(data => {
            store.commit('SET_AUTH_USER', {
                authUser: data.user
            });
            // rest of the code.
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search