migration to web

This commit is contained in:
tanyar09
2025-10-31 12:10:44 -04:00
parent d6b1e85998
commit 94385e3dcc
3560 changed files with 575829 additions and 169 deletions
+84
View File
@@ -0,0 +1,84 @@
import { useState, useEffect } from 'react'
import { authApi, TokenResponse } from '../api/auth'
interface AuthState {
isAuthenticated: boolean
username: string | null
isLoading: boolean
}
export function useAuth() {
const [authState, setAuthState] = useState<AuthState>({
isAuthenticated: false,
username: null,
isLoading: true,
})
useEffect(() => {
const token = localStorage.getItem('access_token')
if (token) {
// Verify token by fetching user info
authApi
.me()
.then((user) => {
setAuthState({
isAuthenticated: true,
username: user.username,
isLoading: false,
})
})
.catch(() => {
localStorage.removeItem('access_token')
localStorage.removeItem('refresh_token')
setAuthState({
isAuthenticated: false,
username: null,
isLoading: false,
})
})
} else {
setAuthState({
isAuthenticated: false,
username: null,
isLoading: false,
})
}
}, [])
const login = async (username: string, password: string) => {
try {
const tokens: TokenResponse = await authApi.login({ username, password })
localStorage.setItem('access_token', tokens.access_token)
localStorage.setItem('refresh_token', tokens.refresh_token)
const user = await authApi.me()
setAuthState({
isAuthenticated: true,
username: user.username,
isLoading: false,
})
return { success: true }
} catch (error: any) {
return {
success: false,
error: error.response?.data?.detail || 'Login failed',
}
}
}
const logout = () => {
localStorage.removeItem('access_token')
localStorage.removeItem('refresh_token')
setAuthState({
isAuthenticated: false,
username: null,
isLoading: false,
})
}
return {
...authState,
login,
logout,
}
}