feat: implement authentication flow with login, registration, and OAuth support
This commit is contained in:
74
src/contexts/AuthContext.tsx
Normal file
74
src/contexts/AuthContext.tsx
Normal file
@@ -0,0 +1,74 @@
|
||||
import { createContext, useContext, useEffect, useState, type ReactNode } from 'react'
|
||||
import { apiService } from '@/lib/api'
|
||||
import type { AuthContextType, User, LoginRequest, RegisterRequest } from '@/types/auth'
|
||||
|
||||
const AuthContext = createContext<AuthContextType | null>(null)
|
||||
|
||||
export function useAuth() {
|
||||
const context = useContext(AuthContext)
|
||||
if (!context) {
|
||||
throw new Error('useAuth must be used within an AuthProvider')
|
||||
}
|
||||
return context
|
||||
}
|
||||
|
||||
interface AuthProviderProps {
|
||||
children: ReactNode
|
||||
}
|
||||
|
||||
export function AuthProvider({ children }: AuthProviderProps) {
|
||||
const [user, setUser] = useState<User | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
useEffect(() => {
|
||||
const initAuth = async () => {
|
||||
try {
|
||||
// Try to get user info using cookies
|
||||
const user = await apiService.getMe()
|
||||
setUser(user)
|
||||
} catch {
|
||||
// User is not authenticated - this is normal for logged out users
|
||||
}
|
||||
setLoading(false)
|
||||
}
|
||||
|
||||
initAuth()
|
||||
}, [])
|
||||
|
||||
const login = async (credentials: LoginRequest) => {
|
||||
try {
|
||||
const response = await apiService.login(credentials)
|
||||
setUser(response.user)
|
||||
} catch (error) {
|
||||
console.error('Login failed:', error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const register = async (data: RegisterRequest) => {
|
||||
try {
|
||||
const response = await apiService.register(data)
|
||||
setUser(response.user)
|
||||
} catch (error) {
|
||||
console.error('Registration failed:', error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const logout = async () => {
|
||||
await apiService.logout()
|
||||
setUser(null)
|
||||
}
|
||||
|
||||
const value: AuthContextType = {
|
||||
user,
|
||||
token: user ? 'cookie-based' : null,
|
||||
login,
|
||||
register,
|
||||
logout,
|
||||
loading,
|
||||
setUser,
|
||||
}
|
||||
|
||||
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>
|
||||
}
|
||||
Reference in New Issue
Block a user