码桶

发现社区成员的开源项目

奶狗 /

ng-webot

公开
main
ng-webot/web/src/lib/auth.tsx
auth.tsx1.2 KB
import { createContext, useContext, useEffect, useState, type ReactNode } from 'react'
import { api, type Bot, type MeResponse } from './api'

interface AuthState {
  me: MeResponse | null
  bots: Bot[]
  loading: boolean
  isAdmin: boolean
  refresh: () => Promise<void>
}

const AuthContext = createContext<AuthState>({
  me: null, bots: [], loading: true, isAdmin: true,
  refresh: async () => {},
})

export function AuthProvider({ children }: { children: ReactNode }) {
  const [me, setMe] = useState<MeResponse | null>(null)
  const [loading, setLoading] = useState(true)

  async function refresh() {
    try {
      const data = await api.post('/api/me')
      if (data.ok) {
        setMe(data)
        return
      }
    } catch {
      /* 加载失败 */
    }
    setMe(null)
  }

  useEffect(() => {
    refresh().finally(() => setLoading(false))
  }, [])

  const bots = me?.bots || []
  // 开源单用户版:始终为管理员
  const isAdmin = true

  return (
    <AuthContext.Provider value={{ me, bots, loading, isAdmin, refresh }}>
      {children}
    </AuthContext.Provider>
  )
}

export function useAuth() {
  return useContext(AuthContext)
}