创建项目

This commit is contained in:
Putoo
2026-04-21 16:54:18 +08:00
commit 6cdceccde7
59 changed files with 15320 additions and 0 deletions

View File

@@ -0,0 +1,164 @@
/**
* 权限校验组合式函数
* 提供登录检查、权限验证等功能
*/
import { useUserStore } from '~/stores/user'
import { useAppStore } from '~/stores/app'
/**
* 权限校验hook
* 用于页面/组件中的权限校验
*/
export const useAuth = () => {
const userStore = useUserStore()
const appStore = useAppStore()
/**
* 检查是否已登录
* @returns boolean 是否已登录
*/
const isAuthenticated = (): boolean => {
return userStore.isLogin
}
/**
* 检查是否未登录
* @returns boolean 是否未登录
*/
const isGuest = (): boolean => {
return !userStore.isLogin
}
/**
* 检查是否拥有指定角色
* @param roles 角色数组
* @returns boolean 是否有权限
*/
const hasRole = (roles: string | string[]): boolean => {
if (!userStore.isLogin) return false
const userRole = userStore.userRole
const roleList = Array.isArray(roles) ? roles : [roles]
return roleList.includes(userRole)
}
/**
* 检查是否为管理员
* @returns boolean 是否为管理员
*/
const isAdmin = (): boolean => {
return hasRole('admin')
}
/**
* 获取当前用户ID
* @returns number 用户ID
*/
const getUserId = (): number => {
return userStore.userId
}
/**
* 获取当前用户信息
* @returns IUserInfo | null 用户信息
*/
const getUserInfo = () => {
return userStore.userInfo
}
/**
* 获取当前用户昵称
* @returns string 用户昵称
*/
const getNickname = (): string => {
return userStore.userNickname
}
/**
* 跳转到登录页(如果未登录)
* @param redirectUrl 登录后重定向的URL
*/
const requireAuth = (redirectUrl?: string) => {
if (!userStore.isLogin) {
if (typeof window !== 'undefined') {
const url = redirectUrl || window.location.href
window.location.href = `/login?redirect=${encodeURIComponent(url)}`
}
return false
}
return true
}
/**
* 跳转到登录页(如果已登录)
* @param redirectUrl 登录后重定向的URL
*/
const requireGuest = (redirectUrl: string = '/') => {
if (userStore.isLogin) {
if (typeof window !== 'undefined') {
window.location.href = redirectUrl
}
return false
}
return true
}
/**
* 检查功能权限(基于角色)
* @param permission 权限标识
* @returns boolean 是否有权限
*/
const hasPermission = (permission: string): boolean => {
// 简化实现,实际项目中可以结合后端返回的权限列表
if (!userStore.isLogin) return false
// 管理员拥有所有权限
if (userStore.userRole === 'admin') return true
// TODO: 可以从用户信息中获取权限列表进行匹配
return false
}
/**
* 登出
* @param redirectUrl 退出后重定向的URL
*/
const logout = async (redirectUrl: string = '/login') => {
try {
// 调用退出登录API如果需要
// const userService = new UserSERVICE()
// await userService.logout()
} finally {
// 清除用户状态
userStore.clearUserInfo()
// 跳转到登录页
if (typeof window !== 'undefined') {
window.location.href = redirectUrl
}
}
}
return {
// 状态
isLogin: computed(() => userStore.isLogin),
userInfo: computed(() => userStore.userInfo),
userId: computed(() => userStore.userId),
nickname: computed(() => userStore.userNickname),
userRole: computed(() => userStore.userRole),
// 方法
isAuthenticated,
isGuest,
hasRole,
isAdmin,
getUserId,
getUserInfo,
getNickname,
requireAuth,
requireGuest,
hasPermission,
logout
}
}