Spaces:
Running

microfunnel-api / frontend /contexts /AuthContext.tsx
axeronis
feat: Granular notifications, Channel support, and 3-level Escalation
1d33ce6
Raw History Blame Contribute Delete
21.2 kB
'use client'
import { createContext, useContext, useState, useEffect, ReactNode } from 'react'
import { useRouter, usePathname } from 'next/navigation'
interface User {
id: string
email: string
full_name: string | null
avatar_url: string | null
phone: string | null
tenant_id: string
tenant_name: string
role: string // 'OWNER' or 'MANAGER'
is_superuser: boolean // Admin access
telegram_chat_id?: string | null // Personal notification ID
}
interface AuthContextType {
user: User | null
token: string | null
login: (email: string, password: string) => Promise<void>
register: (email: string, password: string, company_name: string, full_name?: string, referral_code?: string | null) => Promise<void>
verify: (email: string, code: string) => Promise<void>
resendCode: (email: string) => Promise<void>
forgotPassword: (email: string) => Promise<void>
resetPassword: (email: string, code: string, newPassword: string) => Promise<void>
changePassword: (currentPassword: string, newPassword: string) => Promise<void>
googleAuth: (token: string, company_name?: string, referral_code?: string | null) => Promise<void>
logout: () => void
setUser: (user: User | null) => void
refreshUser: () => Promise<void>
isLoading: boolean
}
const AuthContext = createContext<AuthContextType | undefined>(undefined)
// Cache keys
const CACHE_KEY_USER = 'cached_user_data'
const CACHE_KEY_VERIFIED = 'auth_session_verified'
// Helper to get initial cached user (runs synchronously during first render)
function getInitialCachedUser(): User | null {
if (typeof window === 'undefined') return null
try {
const cached = localStorage.getItem(CACHE_KEY_USER)
const token = localStorage.getItem('auth_token')
if (cached && token) {
return JSON.parse(cached)
}
} catch (e) {
console.warn('Failed to parse cached user')
}
return null
}
// Helper to get initial token
function getInitialToken(): string | null {
if (typeof window === 'undefined') return null
return localStorage.getItem('auth_token')
}
export function AuthProvider({ children }: { children: ReactNode }) {
// CRITICAL: Initialize from cache SYNCHRONOUSLY to avoid loading flash
const [user, setUser] = useState<User | null>(getInitialCachedUser)
const [token, setToken] = useState<string | null>(getInitialToken)
// If we have cached user, we're not loading!
const [isLoading, setIsLoading] = useState(() => {
if (typeof window === 'undefined') return true
const cached = localStorage.getItem(CACHE_KEY_USER)
const token = localStorage.getItem('auth_token')
return !(cached && token) // Only loading if no cache
})
const [hasCheckedAuth, setHasCheckedAuth] = useState(false)
const router = useRouter()
const pathname = usePathname()
// OPTIMIZED: Check for existing token on mount with CACHING
useEffect(() => {
// SSR guard: только в браузере
if (typeof window === 'undefined') {
return
}
// Only run once on mount
if (hasCheckedAuth) {
return
}
const checkAuth = async () => {
console.log('🔐 [AuthContext] Starting auth check...')
// Public pages don't need auth check
const publicPages = ['/', '/login', '/register', '/verify-email', '/terms', '/privacy', '/refund', '/pricing']
const isPublicPage = publicPages.some(page => pathname === page || pathname.startsWith(`${page}/`))
if (isPublicPage) {
console.log('🌐 [AuthContext] On public page, skipping token check')
setHasCheckedAuth(true)
setIsLoading(false)
return
}
const storedToken = localStorage.getItem('auth_token')
if (!storedToken) {
console.log('❌ [AuthContext] No token found')
document.cookie = 'auth_token=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT'
window.location.href = '/login'
return
}
// OPTIMIZATION: Load cached user data FIRST for instant UI
const cachedUserJson = localStorage.getItem(CACHE_KEY_USER)
const sessionVerified = sessionStorage.getItem(CACHE_KEY_VERIFIED)
if (cachedUserJson) {
try {
const cachedUser = JSON.parse(cachedUserJson)
console.log('⚡ [AuthContext] Using cached user data - INSTANT LOAD!')
setUser(cachedUser)
setToken(storedToken)
setIsLoading(false) // INSTANT - no waiting!
setHasCheckedAuth(true)
// If already verified this session, skip API call entirely
if (sessionVerified === 'true') {
console.log('✅ [AuthContext] Session already verified, skipping API')
document.cookie = `auth_token=${storedToken}; path=/; max-age=${7 * 24 * 60 * 60}; SameSite=Lax`
return
}
} catch (e) {
console.warn('⚠️ [AuthContext] Cache parse failed, will fetch fresh')
}
}
// Sync token to cookie
document.cookie = `auth_token=${storedToken}; path=/; max-age=${7 * 24 * 60 * 60}; SameSite=Lax`
// BACKGROUND REFRESH: Verify token and update cache
try {
await fetchUserData(storedToken)
sessionStorage.setItem(CACHE_KEY_VERIFIED, 'true')
console.log('✅ [AuthContext] Background refresh complete')
} catch (error) {
console.error('💥 [AuthContext] Auth check failed:', error)
// Clear everything and redirect
clearAuthState()
window.location.href = '/login'
return
} finally {
// If we didn't have cache, stop loading now
if (!cachedUserJson) {
setHasCheckedAuth(true)
setIsLoading(false)
}
}
}
checkAuth()
}, [])
// MULTI-TAB SYNC: Detect when user logs in/out in another tab
useEffect(() => {
if (typeof window === 'undefined') return
const handleStorageChange = (event: StorageEvent) => {
// SKIP sync on admin pages - admin may be impersonating in another tab
if (window.location.pathname.startsWith('/admin')) {
console.log('🔄 [AuthContext] On admin page, skipping storage sync')
return
}
// If auth_token changed in another tab
if (event.key === 'auth_token') {
const newToken = event.newValue
const currentToken = token
// Token removed (logout in another tab)
if (!newToken && currentToken) {
console.log('🔄 [AuthContext] Logout detected in another tab - reloading...')
window.location.href = '/login'
return
}
// Token changed (different user logged in)
if (newToken && newToken !== currentToken) {
console.log('🔄 [AuthContext] Account change detected in another tab - reloading...')
window.location.reload()
return
}
}
// If cached user data changed
if (event.key === CACHE_KEY_USER) {
const newUserData = event.newValue
if (newUserData) {
try {
const newUser = JSON.parse(newUserData)
// If user ID changed, force reload
if (user && newUser.id !== user.id) {
console.log('🔄 [AuthContext] User changed in another tab - reloading...')
window.location.reload()
}
} catch (e) {
// Invalid JSON, ignore
}
}
}
}
window.addEventListener('storage', handleStorageChange)
return () => {
window.removeEventListener('storage', handleStorageChange)
}
}, [token, user])
// Helper to clear all auth state
const clearAuthState = () => {
localStorage.removeItem('auth_token')
localStorage.removeItem(CACHE_KEY_USER)
sessionStorage.removeItem(CACHE_KEY_VERIFIED)
document.cookie = 'auth_token=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT'
setUser(null)
setToken(null)
}
// Helper to set user AND update cache
const setUserWithCache = (userData: User | null) => {
setUser(userData)
if (userData && typeof window !== 'undefined') {
localStorage.setItem(CACHE_KEY_USER, JSON.stringify(userData))
console.log('💾 [AuthContext] User cached to localStorage')
}
}
// Refresh user data from API
const refreshUser = async () => {
const storedToken = localStorage.getItem('auth_token')
if (storedToken) {
await fetchUserData(storedToken)
}
}
const fetchUserData = async (authToken: string) => {
const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000'
const fullUrl = `${API_URL}/api/v1/auth/me`
try {
const response = await fetch(fullUrl, {
headers: {
'Authorization': `Bearer ${authToken}`,
},
})
console.log('📊 [AuthContext] Response status:', response.status, response.statusText)
// FAIL-SAFE: Auto-logout on any auth error
if (!response.ok) {
console.error(`❌ [AuthContext] Auth failed: ${response.status} ${response.statusText}`)
const errorText = await response.text()
console.error('📄 [AuthContext] Error response:', errorText)
// 401/403 = invalid/expired token -> immediate logout
if (response.status === 401 || response.status === 403) {
console.warn('🔒 [AuthContext] Token expired or invalid - logging out')
throw new Error('LOGOUT_REQUIRED')
}
throw new Error(`Server error: ${response.status}`)
}
const userData = await response.json()
console.log('📦 [AuthContext] User data received:', userData)
// Ensure user object has role field
if (!userData.role) {
console.warn('⚠️ [AuthContext] User data missing role field, setting default MANAGER')
userData.role = 'MANAGER' // Safe default
}
console.log('✅ [AuthContext] User authenticated successfully:', { email: userData.email, role: userData.role })
setUser(userData)
setToken(authToken)
// CACHE: Save user data for instant load on next page
localStorage.setItem(CACHE_KEY_USER, JSON.stringify(userData))
} catch (error) {
console.error('💥 [AuthContext] Failed to fetch user data:', error)
// CRITICAL: Always cleanup on error including cache
console.log('🧹 [AuthContext] Cleaning up auth state...')
clearAuthState()
// Don't redirect here - let middleware handle it
// Re-throw to trigger outer catch in useEffect
throw error
}
}
const login = async (email: string, password: string) => {
try {
const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000'
const response = await fetch(`${API_URL}/api/v1/auth/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ email, password }),
})
if (!response.ok) {
const error = await response.json()
// If email not verified, redirect to verify page instead of showing error
if (response.status === 403 && error.detail?.includes('Email not verified')) {
router.push(`/verify-email?email=${encodeURIComponent(email)}`)
return
}
throw new Error(error.detail || 'Login failed')
}
const data = await response.json()
// SSR guard: только в браузере
if (typeof window !== 'undefined') {
// Save token to localStorage and cookie
localStorage.setItem('auth_token', data.access_token)
document.cookie = `auth_token=${data.access_token}; path=/; max-age=${7 * 24 * 60 * 60}; SameSite=Lax`
}
setToken(data.access_token)
setUserWithCache(data.user)
// Reset auth check flag to allow re-checking on next mount
setHasCheckedAuth(false)
// Redirect to settings/brain
router.push('/settings/brain')
} catch (error) {
console.error('Login error:', error)
throw error
}
}
const register = async (
email: string,
password: string,
company_name: string,
full_name?: string,
referral_code?: string | null
) => {
console.log('🎯 [AuthContext.register] Function called with:', { email, company_name })
try {
const payload: any = { email, password, company_name, full_name }
// Add referral_code if present
if (referral_code) {
payload.referral_code = referral_code
console.log('🔗 Registering with referral code:', referral_code)
}
const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000'
console.log('🌐 [AuthContext.register] API URL:', API_URL)
console.log('📤 [AuthContext.register] Sending request to /api/v1/auth/register')
const response = await fetch(`${API_URL}/api/v1/auth/register`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
})
if (!response.ok) {
const error = await response.json()
console.error('Registration error response:', error)
throw new Error(error.detail || 'Registration failed')
}
const data = await response.json()
// If verification is pending, redirect to verify page
if (data.access_token === 'verification_pending') {
console.log('✅ [Register] Registration successful, redirecting to verify-email')
console.log('📧 [Register] Email:', email)
// Use window.location for immediate, reliable redirect
if (typeof window !== 'undefined') {
const verifyUrl = `/verify-email?email=${encodeURIComponent(email)}`
console.log('🔄 [Register] Redirecting to:', verifyUrl)
window.location.href = verifyUrl
}
return
}
// SSR guard: только в браузере
if (typeof window !== 'undefined') {
// Save token to localStorage and cookie
localStorage.setItem('auth_token', data.access_token)
document.cookie = `auth_token=${data.access_token}; path=/; max-age=${7 * 24 * 60 * 60}; SameSite=Lax`
// Show success message with referral code
alert(`✅ Регистрация успешна!\n\nВаш реферальный код: ${data.user.referral_code}`)
}
setToken(data.access_token)
setUser(data.user)
// Reset auth check flag to allow re-checking on next mount
setHasCheckedAuth(false)
// Redirect to settings/brain
router.push('/settings/brain')
} catch (error) {
console.error('Registration error:', error)
throw error
}
}
const verify = async (email: string, code: string) => {
try {
const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000'
const response = await fetch(`${API_URL}/api/v1/auth/verify`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ email, code }),
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || 'Verification failed')
}
const data = await response.json()
if (typeof window !== 'undefined') {
localStorage.setItem('auth_token', data.access_token)
document.cookie = `auth_token=${data.access_token}; path=/; max-age=${7 * 24 * 60 * 60}; SameSite=Lax`
}
setToken(data.access_token)
setUser(data.user)
setHasCheckedAuth(false)
router.push('/settings/brain')
} catch (error) {
console.error('Verification error:', error)
throw error
}
}
const resendCode = async (email: string) => {
try {
const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000'
const response = await fetch(`${API_URL}/api/v1/auth/resend-code`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ email }),
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || 'Failed to resend code')
}
} catch (error) {
console.error('Resend code error:', error)
throw error
}
}
const forgotPassword = async (email: string) => {
try {
const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000'
const response = await fetch(`${API_URL}/api/v1/auth/forgot-password`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ email }),
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || 'Failed to request password reset')
}
} catch (error) {
console.error('Forgot password error:', error)
throw error
}
}
const resetPassword = async (email: string, code: string, newPassword: string) => {
try {
const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000'
const response = await fetch(`${API_URL}/api/v1/auth/reset-password`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ email, code, new_password: newPassword }),
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || 'Failed to reset password')
}
} catch (error) {
console.error('Reset password error:', error)
throw error
}
}
const changePassword = async (currentPassword: string, newPassword: string) => {
try {
const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000'
const response = await fetch(`${API_URL}/api/v1/auth/change-password`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({ current_password: currentPassword, new_password: newPassword }),
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || 'Failed to change password')
}
} catch (error) {
console.error('Change password error:', error)
throw error
}
}
const googleAuth = async (token: string, company_name?: string, referral_code?: string | null) => {
try {
const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000'
const response = await fetch(`${API_URL}/api/v1/auth/google`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ token, company_name, referral_code }),
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || 'Google authentication failed')
}
const data = await response.json()
// SSR guard: только в браузере
if (typeof window !== 'undefined') {
// Save token to localStorage and cookie
localStorage.setItem('auth_token', data.access_token)
document.cookie = `auth_token=${data.access_token}; path=/; max-age=${7 * 24 * 60 * 60}; SameSite=Lax`
}
setToken(data.access_token)
setUser(data.user)
// Redirect to settings/brain
router.push('/settings/brain')
} catch (error) {
console.error('Google auth error:', error)
throw error
}
}
const logout = () => {
console.log('🚪 [AuthContext] Logging out...')
// SSR guard: только в браузере
if (typeof window !== 'undefined') {
// Clear all auth state including cache
clearAuthState()
// CRITICAL: Clear ALL localStorage to prevent data leakage between accounts
// This includes any cached leads, settings, or other user-specific data
const keysToPreserve = ['microfunnel_language'] // Only preserve non-user-specific settings
const allKeys = Object.keys(localStorage)
allKeys.forEach(key => {
if (!keysToPreserve.includes(key)) {
localStorage.removeItem(key)
}
})
// Clear all sessionStorage
sessionStorage.clear()
console.log('🧹 [AuthContext] Cleared all user data from storage')
}
// Immediate redirect using window.location for hard refresh
if (typeof window !== 'undefined') {
console.log('🔄 [AuthContext] Redirecting to login...')
window.location.href = '/login'
}
}
return (
<AuthContext.Provider
value={{
user,
token,
login,
register,
verify,
resendCode,
forgotPassword,
resetPassword,
changePassword,
googleAuth,
logout,
setUser: setUserWithCache,
refreshUser,
isLoading,
}}
>
{children}
</AuthContext.Provider>
)
}
export function useAuth() {
const context = useContext(AuthContext)
if (context === undefined) {
throw new Error('useAuth must be used within an AuthProvider')
}
return context
}