Monday, 22 August 2022

Nuxt + Firebase redirect to restricted page after login

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
})


from Nuxt + Firebase redirect to restricted page after login

No comments:

Post a Comment