在初始页面加载时获取用户 - Nuxt 中间件
Get user on initial page load - Nuxt middleware
我在我的 Nuxt 应用程序中使用 Firebase Auth,但在使用受保护路由时遇到了一些问题。我启用了 nuxt 中间件,它根据用户是否登录页面导航来处理重定向。
我的问题是,如果您从地址栏访问受保护的路线并且您之前已注销,您将获得对该路线的访问权限。但是,如果您尝试从该路线访问另一条受保护路线,您将被重定向。我正在使用 Vuex 来处理用户登录状态。
如何让中间件在受保护路由的 'cold start' 上启动。
中间件:router-auth.js
export default function({ store, redirect, route }) {
const user = JSON.parse(store.state.Authentication.user)
console.log(user);
user !== null && route.name === '/' ? redirect('/dashboard') : ''
//user === null && route.name !== '/' ? redirect('/dashboard') : ''
}
插件:auth.js
import firebase from "firebase/app";
import "firebase/auth";
export default function ({store, router}) {
firebase.auth().onAuthStateChanged((user) => {
if(user){
store.dispatch('Authentication/SET_USER',JSON.stringify(user))
}else{
store.dispatch('Authentication/SET_USER', null)
}
})
}
Vuex:Authentication.js
export const state = () => ({
user: ''
});
export const getters = {
user: state => {
return state.user;
},
}
export const mutations = {
SET_USER: (state, payload) => {
state.user = payload;
},
}
export const actions = {
SET_USER({ commit }, payload) {
commit('SET_USER', payload)
},
}
您可以return在中间件中调用错误函数:
export default function({ store, redirect, route, error }) {
const accessDenied = true // ... your access route logic goes here
if (accessDenied) {
return error({
message: 'access denied',
statusCode: 403
})
}
}
我在我的 Nuxt 应用程序中使用 Firebase Auth,但在使用受保护路由时遇到了一些问题。我启用了 nuxt 中间件,它根据用户是否登录页面导航来处理重定向。
我的问题是,如果您从地址栏访问受保护的路线并且您之前已注销,您将获得对该路线的访问权限。但是,如果您尝试从该路线访问另一条受保护路线,您将被重定向。我正在使用 Vuex 来处理用户登录状态。
如何让中间件在受保护路由的 'cold start' 上启动。
中间件:router-auth.js
export default function({ store, redirect, route }) {
const user = JSON.parse(store.state.Authentication.user)
console.log(user);
user !== null && route.name === '/' ? redirect('/dashboard') : ''
//user === null && route.name !== '/' ? redirect('/dashboard') : ''
}
插件:auth.js
import firebase from "firebase/app";
import "firebase/auth";
export default function ({store, router}) {
firebase.auth().onAuthStateChanged((user) => {
if(user){
store.dispatch('Authentication/SET_USER',JSON.stringify(user))
}else{
store.dispatch('Authentication/SET_USER', null)
}
})
}
Vuex:Authentication.js
export const state = () => ({
user: ''
});
export const getters = {
user: state => {
return state.user;
},
}
export const mutations = {
SET_USER: (state, payload) => {
state.user = payload;
},
}
export const actions = {
SET_USER({ commit }, payload) {
commit('SET_USER', payload)
},
}
您可以return在中间件中调用错误函数:
export default function({ store, redirect, route, error }) {
const accessDenied = true // ... your access route logic goes here
if (accessDenied) {
return error({
message: 'access denied',
statusCode: 403
})
}
}