168 lines
5.8 KiB
TypeScript
168 lines
5.8 KiB
TypeScript
'use client'
|
|
|
|
import { useState } from 'react'
|
|
import { useRouter } from 'next/navigation'
|
|
import useAuthStore from '../../store/authStore'
|
|
|
|
export interface LoginCredentials {
|
|
email: string
|
|
password: string
|
|
rememberMe?: boolean
|
|
}
|
|
|
|
export function useLogin() {
|
|
const [error, setError] = useState('')
|
|
const [loading, setLoading] = useState(false)
|
|
|
|
const router = useRouter()
|
|
const setAccessToken = useAuthStore(state => state.setAccessToken)
|
|
const setUser = useAuthStore(state => state.setUser)
|
|
|
|
const login = async (credentials: LoginCredentials) => {
|
|
setError('')
|
|
setLoading(true)
|
|
|
|
try {
|
|
console.log('Login attempt:', {
|
|
email: credentials.email,
|
|
rememberMe: credentials.rememberMe
|
|
})
|
|
|
|
// Call same-origin BFF route so it can set Domain=.profit-planet.partners cookie
|
|
const loginUrl = `/api/login`
|
|
console.log('Calling login API (BFF):', loginUrl)
|
|
|
|
const response = await fetch(loginUrl, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
},
|
|
credentials: 'include',
|
|
body: JSON.stringify({
|
|
email: credentials.email,
|
|
password: credentials.password,
|
|
}),
|
|
})
|
|
|
|
console.log('Login response status:', response.status)
|
|
|
|
const data = await response.json().catch(() => null)
|
|
|
|
if (!response.ok) {
|
|
// Handle HTTP errors
|
|
if (response.status === 403) {
|
|
return { success: false, error: 'Account suspended', redirectPath: '/suspended' }
|
|
}
|
|
if (response.status === 401) {
|
|
throw new Error('Invalid credentials')
|
|
} else if (response.status === 404) {
|
|
throw new Error('Account not found')
|
|
} else if (response.status === 423) {
|
|
throw new Error('Account locked')
|
|
} else {
|
|
throw new Error('Login failed. Please try again.')
|
|
}
|
|
}
|
|
console.log('Login response data:', data)
|
|
|
|
if (data.success && data.accessToken && data.user) {
|
|
// Update auth store
|
|
setAccessToken(data.accessToken)
|
|
setUser(data.user)
|
|
|
|
// Store session info if remember me is checked
|
|
if (credentials.rememberMe) {
|
|
if (typeof window !== 'undefined') {
|
|
sessionStorage.setItem('userType', data.user.userType)
|
|
sessionStorage.setItem('role', data.user.role)
|
|
}
|
|
}
|
|
|
|
console.log('✅ Login successful:', data.user)
|
|
|
|
// Fetch user status-progress
|
|
let redirectPath = '/quickaction-dashboard' // Default redirect
|
|
|
|
try {
|
|
const statusUrl = `${process.env.NEXT_PUBLIC_API_BASE_URL}/api/user/status-progress`
|
|
console.log('Fetching user status-progress:', statusUrl)
|
|
|
|
const statusResponse = await fetch(statusUrl, {
|
|
method: 'GET',
|
|
headers: {
|
|
'Authorization': `Bearer ${data.accessToken}`,
|
|
'Content-Type': 'application/json',
|
|
},
|
|
credentials: 'include',
|
|
})
|
|
|
|
console.log('Status-progress response status:', statusResponse.status)
|
|
|
|
if (statusResponse.ok) {
|
|
const statusData = await statusResponse.json()
|
|
console.log('📊 User status-progress data:', statusData)
|
|
|
|
// Check if all 4 steps are completed and status is active
|
|
// The API returns: statusData.progress.status and statusData.progress.steps
|
|
const progressData = statusData.progress || statusData
|
|
const steps = progressData.steps || []
|
|
const allStepsCompleted = steps.length === 4 && steps.every((step: any) => step.completed === true)
|
|
const isActive = progressData.status === 'active'
|
|
|
|
console.log('🔍 Status check:', {
|
|
allStepsCompleted,
|
|
isActive,
|
|
totalSteps: steps.length,
|
|
completedSteps: steps.filter((step: any) => step.completed).length,
|
|
status: progressData.status
|
|
})
|
|
|
|
// Redirect decision logic (keep as-is, but do not push here)
|
|
if (allStepsCompleted && isActive) {
|
|
redirectPath = '/dashboard'
|
|
console.log('✅ User fully onboarded, redirecting to dashboard')
|
|
} else {
|
|
console.log('⚠️ User needs to complete onboarding, redirecting to quickaction-dashboard')
|
|
}
|
|
} else {
|
|
console.warn('⚠️ Failed to fetch user status-progress:', statusResponse.status)
|
|
}
|
|
} catch (statusError) {
|
|
console.error('❌ Error fetching user status-progress:', statusError)
|
|
}
|
|
|
|
// NOTE: no router.push here; caller will handle redirect after showing toast
|
|
return { success: true, user: data.user, redirectPath }
|
|
} else {
|
|
throw new Error(data.message || 'Login failed')
|
|
}
|
|
|
|
} catch (err: any) {
|
|
console.error('❌ Login error:', err)
|
|
|
|
// Handle specific error cases
|
|
if (err.message?.includes('Invalid credentials')) {
|
|
setError('E-Mail oder Passwort falsch')
|
|
} else if (err.message?.includes('Account not found')) {
|
|
setError('Kein Account mit dieser E-Mail-Adresse gefunden')
|
|
} else if (err.message?.includes('Account locked')) {
|
|
setError('Account wurde gesperrt. Kontaktiere den Support.')
|
|
} else if (err.message?.includes('Failed to fetch')) {
|
|
setError('Verbindung zum Server fehlgeschlagen. Bitte versuche es später erneut.')
|
|
} else {
|
|
setError(err.message || 'Anmeldung fehlgeschlagen. Bitte versuche es erneut.')
|
|
}
|
|
|
|
return { success: false, error: err.message }
|
|
} finally {
|
|
setLoading(false)
|
|
}
|
|
}
|
|
|
|
return {
|
|
login,
|
|
error,
|
|
setError,
|
|
loading
|
|
}
|
|
} |