[英]Forbid authenticated users from visiting login page in nuxt js
I have the following code snipped from my middleware/auth.js
that redirects users to login page if the users are unauthenticated.我从我的
middleware/auth.js
了以下代码,如果用户未经身份验证,这些代码会将用户重定向到登录页面。
export default function ({ store, redirect }) { if (!store.state.admin.isAdmin) { redirect('/auth/login') } }
Now I want to forbid authenticated users visiting login page and redirect to ('/manage/dashboard') when they hit the login url.现在我想禁止经过身份验证的用户访问登录页面并在他们点击登录 url 时重定向到 ('/manage/dashboard')。
I have used the following approach in my login view:我在登录视图中使用了以下方法:
mounted () { if (localStorage.getItem('token') && localStorage.getItem('userId')) { this.$router.replace({ path: '/admin/dashboard' }) } }
This works but the execution is too slow and user can see login page for few seconds.这有效,但执行速度太慢,用户可以看到登录页面几秒钟。
What is the efficient way to achieve the redirect ?实现重定向的有效方法是什么?
I wouldn't access localStorage from the login view, I would prefer to set it in your store and then access the store.我不会从登录视图访问 localStorage,我更愿意将它设置在您的商店中,然后访问商店。 I have not run this code but I think you want to do something like this.
我还没有运行这段代码,但我认为你想做这样的事情。
You can create another check-auth.js middleware and add that to your login view.您可以创建另一个 check-auth.js 中间件并将其添加到您的登录视图中。
check-auth.js检查 auth.js
export default function (context) {
context.store.dispatch('initAuth', context.req);
}
store/index.js商店/index.js
state:{
authenticated:false;
}
mutations: {
setAuthentication(state, auth) {
state.authenticated = auth;
},
}
actions: {
initAuth(vuexContext, req) {
if (localStorage.getItem('token') && localStorage.getItem('userId')){
vuexContext.commit('setAuthentication', true);
}else{
vuexContext.commit('setAuthentication', false);
}
}
},
getters: {
isAuthenticated(state) {
return state.authenticated;
},
},
Then check if the user is authenticated auth.js然后检查用户是否通过身份验证 auth.js
if (!context.store.getters.isAuthenticated) {
context.redirect('/auth/login');
}
add middleware to your view将中间件添加到您的视图中
export default {
middleware: ['check-auth', 'auth'],
components: {},
methods: {},
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.