feat: 新增路由鉴权
This commit is contained in:
@@ -6,6 +6,7 @@ import App from "./App.vue";
|
||||
import ElementPlus from 'element-plus'
|
||||
import 'element-plus/dist/index.css'
|
||||
import locale from 'element-plus/es/locale/lang/zh-cn'
|
||||
import './permission'
|
||||
|
||||
// 创建 Vue 应用实例
|
||||
const app = createApp(App);
|
||||
|
||||
29
src/renderer/permission.ts
Normal file
29
src/renderer/permission.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import router from './router'
|
||||
import { isPathMatch } from '@utils/validate'
|
||||
import { getToken } from '@utils/auth'
|
||||
|
||||
// 白名单
|
||||
const whiteList = ['/login', '/register']
|
||||
|
||||
const isWhiteList = (path: string) => whiteList.some(pattern => isPathMatch(pattern, path))
|
||||
|
||||
router.beforeEach((to: any, _from: any, next: any) => {
|
||||
if(getToken()) {
|
||||
// has token
|
||||
if (to.path === '/login') {
|
||||
next({path: '/home'})
|
||||
} else if (isWhiteList(to.path)) {
|
||||
next()
|
||||
} else {
|
||||
|
||||
}
|
||||
} else {
|
||||
// no token
|
||||
if (isWhiteList(to.path)) {
|
||||
// 在免登录白名单,直接进入
|
||||
next()
|
||||
} else {
|
||||
next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
|
||||
}
|
||||
}
|
||||
})
|
||||
15
src/renderer/utils/auth.ts
Normal file
15
src/renderer/utils/auth.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import Cookies from 'js-cookie'
|
||||
|
||||
const TokenKey = 'Nianxx-Token'
|
||||
|
||||
export function getToken() {
|
||||
return Cookies.get(TokenKey)
|
||||
}
|
||||
|
||||
export function setToken(token: string) {
|
||||
return Cookies.set(TokenKey, token)
|
||||
}
|
||||
|
||||
export function removeToken() {
|
||||
return Cookies.remove(TokenKey)
|
||||
}
|
||||
12
src/renderer/utils/validate.ts
Normal file
12
src/renderer/utils/validate.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* 路径匹配器
|
||||
* @param {string} pattern
|
||||
* @param {string} path
|
||||
* @returns {Boolean}
|
||||
*/
|
||||
export function isPathMatch(pattern: string, path: string): boolean {
|
||||
const regexPattern = pattern.replace(/\//g, '\\/').replace(/\*\*/g, '.*').replace(/\*/g, '[^\\/]*')
|
||||
const regex = new RegExp(`^${regexPattern}$`)
|
||||
|
||||
return regex.test(path)
|
||||
}
|
||||
Reference in New Issue
Block a user