- Added EmailVerificationBanner component to notify users about unverified email status and provide a resend verification option. - Introduced VerifyPage for handling email verification via a token in the URL, including success and error handling. - Updated LoginPage and AccountSettingsPage to allow users to resend verification emails directly from these pages. - Enhanced API utility with new functions for verifying emails and resending verification requests. - Updated routing to include the new verification page and improved link structure for verification links.
82 lines
1.7 KiB
JavaScript
82 lines
1.7 KiB
JavaScript
import { createContext, useContext, useState, useEffect, useCallback } from 'react'
|
|
import api from '../utils/api'
|
|
|
|
const AuthContext = createContext(null)
|
|
|
|
export function AuthProvider({ children }) {
|
|
const [user, setUser] = useState(null)
|
|
const [loading, setLoading] = useState(true)
|
|
|
|
const checkAuth = useCallback(async () => {
|
|
const token = localStorage.getItem('authToken')
|
|
if (!token) {
|
|
setLoading(false)
|
|
return
|
|
}
|
|
|
|
try {
|
|
const profile = await api.getCurrentProfile()
|
|
setUser(profile)
|
|
} catch (err) {
|
|
console.error('Auth check failed:', err)
|
|
localStorage.removeItem('authToken')
|
|
} finally {
|
|
setLoading(false)
|
|
}
|
|
}, [])
|
|
|
|
useEffect(() => {
|
|
checkAuth()
|
|
}, [checkAuth])
|
|
|
|
/** Fallback, falls ohne checkAuth gesetzt wird (Legacy / Token-Injektion) */
|
|
const login = (payload) => {
|
|
if (payload?.profile != null) {
|
|
setUser(payload.profile)
|
|
return
|
|
}
|
|
const p = payload
|
|
if (p?.profile_id != null || p?.id != null) {
|
|
setUser({
|
|
id: p.profile_id ?? p.id,
|
|
name: p.name ?? null,
|
|
email: p.email ?? null,
|
|
role: p.role ?? 'user',
|
|
tier: p.tier ?? 'free',
|
|
})
|
|
return
|
|
}
|
|
setUser(payload)
|
|
}
|
|
|
|
const logout = () => {
|
|
setUser(null)
|
|
localStorage.removeItem('authToken')
|
|
}
|
|
|
|
const value = {
|
|
user,
|
|
isAuthenticated: !!user,
|
|
loading,
|
|
login,
|
|
logout,
|
|
checkAuth
|
|
}
|
|
|
|
return (
|
|
<AuthContext.Provider value={value}>
|
|
{children}
|
|
</AuthContext.Provider>
|
|
)
|
|
}
|
|
|
|
export function useAuth() {
|
|
const context = useContext(AuthContext)
|
|
if (!context) {
|
|
throw new Error('useAuth must be used within AuthProvider')
|
|
}
|
|
return context
|
|
}
|
|
|
|
export default AuthContext
|