Initial monorepo structure
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
import { createContext, useContext, useState, useEffect } from 'react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { authApi } from '../api/client'
|
||||
|
||||
interface User {
|
||||
id: number
|
||||
email: string
|
||||
first_name: string
|
||||
last_name: string
|
||||
is_active: boolean
|
||||
roles: string[]
|
||||
module_roles: Record<string, string[]>
|
||||
}
|
||||
|
||||
interface AuthContextType {
|
||||
user: User | null
|
||||
loading: boolean
|
||||
login: (email: string, password: string) => Promise<void>
|
||||
logout: () => void
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextType | undefined>(undefined)
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [user, setUser] = useState<User | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
useEffect(() => {
|
||||
const token = localStorage.getItem('platform_token')
|
||||
if (token) {
|
||||
authApi.me()
|
||||
.then(res => setUser(res.data))
|
||||
.catch(() => localStorage.removeItem('platform_token'))
|
||||
.finally(() => setLoading(false))
|
||||
} else {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const login = async (email: string, password: string) => {
|
||||
const res = await authApi.login({ email, password })
|
||||
localStorage.setItem('platform_token', res.data.access_token)
|
||||
setUser(res.data.user)
|
||||
}
|
||||
|
||||
const logout = () => {
|
||||
localStorage.removeItem('platform_token')
|
||||
setUser(null)
|
||||
}
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ user, loading, login, logout }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export function useAuth() {
|
||||
const ctx = useContext(AuthContext)
|
||||
if (!ctx) throw new Error('useAuth must be inside AuthProvider')
|
||||
return ctx
|
||||
}
|
||||
Reference in New Issue
Block a user