61 lines
1.6 KiB
React
61 lines
1.6 KiB
React
import { createContext, useContext, useEffect, useState } from 'react'
|
|
import apiClient from '../api/client'
|
|
|
|
const AuthContext = createContext(null)
|
|
|
|
export function AuthProvider({ children }) {
|
|
const [user, setUser] = useState(null)
|
|
const [isLoading, setIsLoading] = useState(true)
|
|
|
|
useEffect(() => {
|
|
const token = localStorage.getItem('access_token')
|
|
if (!token) {
|
|
setIsLoading(false)
|
|
return
|
|
}
|
|
apiClient
|
|
.get('/api/users/me')
|
|
.then((res) => setUser(res.data))
|
|
.catch(() => localStorage.removeItem('access_token'))
|
|
.finally(() => setIsLoading(false))
|
|
}, [])
|
|
|
|
async function login(username, password) {
|
|
const form = new URLSearchParams()
|
|
form.append('username', username)
|
|
form.append('password', password)
|
|
|
|
const { data } = await apiClient.post('/api/auth/token', form, {
|
|
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
})
|
|
localStorage.setItem('access_token', data.access_token)
|
|
|
|
const me = await apiClient.get('/api/users/me')
|
|
setUser(me.data)
|
|
}
|
|
|
|
async function register(username, password) {
|
|
await apiClient.post('/api/auth/register', { username, password })
|
|
await login(username, password)
|
|
}
|
|
|
|
function logout() {
|
|
localStorage.removeItem('access_token')
|
|
setUser(null)
|
|
}
|
|
|
|
return (
|
|
<AuthContext.Provider
|
|
value={{ user, setUser, isAuthenticated: !!user, isLoading, login, register, logout }}
|
|
>
|
|
{children}
|
|
</AuthContext.Provider>
|
|
)
|
|
}
|
|
|
|
export function useAuth() {
|
|
const ctx = useContext(AuthContext)
|
|
if (!ctx) throw new Error('useAuth must be used within an AuthProvider')
|
|
return ctx
|
|
}
|