@bty/react-auth
v0.0.13
Published
> 提供路由守卫和权限控制的 React 组件
Downloads
130
Readme
@bty/react-auth
提供路由守卫和权限控制的 React 组件
约定了 src/auth.ts 为我们的权限定义文件,该文件需要默认导出一个方法。该方法需要返回一个对象,对象的每一个值就对应定义了一条权限。如下所示:
使用
// src/auth.ts
import { FeatureFlag, type User } from './apis/user'
export interface AuthState {
token?: string
user: User
}
export default function (sate: AuthState) {
return {
auth: !!sate.token,
canCreateWorkspace: sate.user?.featureFlag.includes(FeatureFlag.WORKSPACE_CREATION),
}
}
页面权限控制
// router.ts
import { createAuthBrowserRouter } from '@bty/react-auth'
import auth from '@/auth'
const router = createAuthBrowserRouter([
{
path: '/',
element: <>Home</>,
auth: 'auth', // 该路由需要 auth.ts 中的 auth 字段为 true时 可访问
}
], { auth })
export default router
// App.tsx
import { AuthProvider } from '@bty/react-auth'
import { RouterProvider } from 'react-router-dom'
import router from './router'
import { tokenStorage } from '@/utils/storage'
import { useUserStore } from '@/store'
import auth from '@/auth'
function App() {
const { user } = useUserStore()
return (
<AuthProvider state={{ user, token: tokenStorage.get() }} authFn={auth} >{children}
<RouterProvider router={router} />
</AuthProvider>
)
}
useAuth
import { useAuth } from '@bty/react-auth'
function Component() {
const { access } = useAuth()
return (
<div>
{access.auth && <div>登录了</div>}
{access.canCreateWorkspace && <div>有创建空间权限</div>}
</div>
)
}
Access 组件(按钮权限)
import { Access, useAuth } from '@bty/react-auth'
function Component() {
const { access } = useAuth()
return (
<Access access={access.canCreateWorkspace} callback={() => message.warning('您没有创建工作空间的权限,请联系管理员')} >
<div>创建工作空间</div>
</Access>
)
}
Access 组件 Props
export interface AccessProps {
children: React.ReactNode
access: boolean // 是否有权限
hide?: boolean // 无权限时是否隐藏按钮 默认 hide = false
fallback?: React.ReactNode // 无权限时的回调内容
callback?: () => void // 无权限时点击的回调内容
}