nuxt 自定義 auth 中間件實作令牌的持久化
核心點就是在process.server下,把之前存在 cookie 中的資料再用store.commit一下
auth.js
/* eslint-disable no-unused-vars */
/* eslint-disable no-useless-return */
export const TokenKey = 'Admin-token'
/**
* 決議服務端拿到的cookie
* @param {*} cookie
* @param {*} key
*/
export function getCookie(cookie, key) {
if (!cookie) return
const arrstr = cookie.split('; ')
for (let i = 0; i < arrstr.length; i++) {
const temp = arrstr[i].split('=')
if (temp[0] === key) return unescape(temp[1])
}
}
// 登錄頁
const loginPath = '/login'
// 首頁
const indexPath = '/home'
// 路由白名單,直接繞過路由守衛
const whiteList = [loginPath]
/**
* @description 鑒權中間件,用于校驗登陸
*
*/
export default async ({ store, redirect, env, route, req }) => {
const { path, fullPath, query } = route
const { redirect: redirectPath } = query
// 應對重繪 vuex狀態丟失的解決方案
if (process.server) {
const cookie = req.headers.cookie
const token = getCookie(cookie, TokenKey)
// 設定登錄狀態
if (token) {
store.commit('LOGIN', token) //'LOGIN' 和store中的mutations對應起來就可以了
}
if (token) {
// 已經登錄,進來的是登錄頁,且有重定向的路徑,直接調跳到重定向的路徑
if (path === loginPath && path !== redirectPath) {
redirect(redirectPath)
} else if (path === '/') {
redirect(indexPath)
} else {
// 其他的已經登錄過得直接跳過
return
}
} else {
// 鑒權白名單
if (whiteList.includes(path)) return
// 未登錄,進來的不是是登錄頁,全部重定向到登錄頁
if (!path.includes(loginPath)) {
redirect(`${loginPath}?redirect=${encodeURIComponent(fullPath)}`)
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/190942.html
標籤:java
