Redirect authenticated users nuxt js

孤者浪人 提交于 2021-01-29 18:25:40

问题


I have the following code from my state to handle the login request and load the incoming data to state.

export const state = {
  userId: "",
  token: "",
  authenticated: false
};

export const getters = {};
export const actions = {
  async login({ commit, dispatch }, formData) {
    //codes to get data from server goes here
    // incoming datas are {status: true,token: 'token123', userId: '123'}
    const remainingMilliseconds = 60 * 60 * 1000;
    const expiryDate = new Date(new Date().getTime() + remainingMilliseconds);
    localStorage.setItem("expiryDate", expiryDate.toISOString());
    dispatch("autoLogout", remainingMilliseconds);
    localStorage.setItem("userId", response.data.userId);
    localStorage.setItem("token", response.data.token);
    commit("loadState", response.data);
    return response.status;
  }
};
export const mutations = {
  loadState(state, data) {
    state.userId = data.userId;
    state.token = data.token;
    state.authenticated = data.status;
  }
};

Methods from my login.vue:

    middleware:'nologin'
    async login() {
      const status = await this.$store.dispatch("admin/login", this.form);

      if (status === 200) {
        this.$router.push({ path: "/dashboard" });
      }
    },

And my methods from layouts/default.vue in order to save data into state when the user refreshes the page:

  methods: {
    loadState() {
      const token = localStorage.getItem("token");
      const userId = localStorage.getItem("userId");
      const payload = {
        status: true,
        token,
        userId,
      };
      if (token && userId) {
        this.$store.commit("admin/loadState", payload);
      }
    },
  },
  mounted() {
    this.loadState();
  },

And I have 2 middlewares nologin.js (prevent authenticated user from accessing login page) and auth.js (prevent unauthenticated user to access dashboard)

nologin.js

export default function ({ store, redirect }) {
  console.log(store.state.admin);
  if (store.state.admin.authenticated) {
    redirect("/dashboard");
  }
}

auth.js placed in dashboard.vue

export default function ({ store, redirect }) {
  console.log(store.state.admin);
  if (!store.state.admin.authenticated) {
    redirect("/login");
  }
}

Apparently this somehow works (navigating from routes) but when the user types the URL the redirect doesn't work. Is this the normal behavior of nuxt js ? Is there a way to overcome this issue ?? Here is the link to sandbox.

https://codesandbox.io/s/modest-jackson-wkfuj?file=/pages/index.vue

来源:https://stackoverflow.com/questions/64131342/redirect-authenticated-users-nuxt-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!