Skip to content

Commit 72af548

Browse files
committed
Fix login flow to properly authenticate with Firebase
- Add Firebase signInWithCustomToken to login form after API success - Update SessionAuthInitializer to handle login redirects properly - Set authRedirectPending flag before Firebase authentication - Add redirect logic for both existing and new session creation - Ensure proper session management flow compliance This fixes the issue where users were kicked back to logged out page after login by ensuring Firebase auth state changes are properly handled.
1 parent b8ab358 commit 72af548

2 files changed

Lines changed: 33 additions & 18 deletions

File tree

app/components/auth/SessionAuthInitializer.tsx

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,12 +212,30 @@ function SessionAuthInitializer({ children }: SessionAuthInitializerProps) {
212212
console.warn('SessionAuthInitializer: Failed to transfer logged-out token allocations for existing user:', transferError);
213213
// Don't fail the login process if token transfer fails
214214
}
215+
216+
// Handle redirect after successful login
217+
if (isOnLoginPage && authRedirectPending) {
218+
console.log('SessionAuthInitializer: Login successful, redirecting to home page');
219+
localStorage.removeItem('authRedirectPending');
220+
setTimeout(() => {
221+
window.location.href = "/";
222+
}, 500);
223+
}
215224
} catch (sessionError) {
216225
// If no session exists for this user, create a new one
217226
console.log('SessionAuthInitializer: No session found for user, creating new session:', firebaseUser.uid);
218227
console.log('SessionAuthInitializer: Session error details:', sessionError);
219228
try {
220229
await createSessionFromFirebaseUser(firebaseUser);
230+
231+
// Handle redirect after successful new session creation
232+
if (isOnLoginPage && authRedirectPending) {
233+
console.log('SessionAuthInitializer: New session created, redirecting to home page');
234+
localStorage.removeItem('authRedirectPending');
235+
setTimeout(() => {
236+
window.location.href = "/";
237+
}, 500);
238+
}
221239
} catch (createError) {
222240
console.error('SessionAuthInitializer: Failed to create session for user:', firebaseUser.uid, createError);
223241
// If session creation fails, clear any active account

app/components/forms/modern-login-form.tsx

Lines changed: 15 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,8 @@ import { Button } from "../ui/button"
3838
import { Input } from "../ui/input"
3939
import { Label } from "../ui/label"
4040
import { useState, useEffect } from "react"
41-
// Removed direct Firebase imports - now using API endpoints
41+
import { signInWithCustomToken } from "firebase/auth"
42+
import { auth } from "../../firebase/config"
4243
import { Loader2, AlertCircle } from "lucide-react"
4344
import { Separator } from "../ui/separator"
4445
// reCAPTCHA functionality removed
@@ -105,29 +106,25 @@ export function ModernLoginForm({
105106
const result = await response.json()
106107

107108
if (response.ok && result.success) {
108-
// Successful login
109+
// Successful login - now sign into Firebase with the custom token
109110
console.log("Login successful:", result.data)
110111

111-
// The API already sets the session cookies, so we can proceed directly
112-
console.log("Session cookies set by API")
112+
try {
113+
// Sign into Firebase with the custom token from the API
114+
console.log("Signing into Firebase with custom token...")
115+
localStorage.setItem('authRedirectPending', 'true')
113116

114-
// Check if we're adding a new account to the account switcher
115-
const previousUserSession = localStorage.getItem('previousUserSession') ||
116-
sessionStorage.getItem('wewrite_previous_user')
117+
const userCredential = await signInWithCustomToken(auth, result.data.customToken)
118+
console.log("Firebase sign-in successful:", userCredential.user.uid)
117119

118-
if (previousUserSession) {
119-
console.log("Adding new account to account switcher...")
120-
// This is handled by the MultiAccountProvider
121-
}
122-
123-
// Increase timeout to allow auth state to fully propagate
124-
// and ensure cookies are properly set
125-
localStorage.setItem('authRedirectPending', 'true')
120+
// The Firebase auth state change will trigger the session management
121+
// and handle the redirect automatically through SessionAuthInitializer
126122

127-
setTimeout(() => {
123+
} catch (firebaseError: any) {
124+
console.error("Firebase sign-in error:", firebaseError)
128125
localStorage.removeItem('authRedirectPending')
129-
window.location.href = "/"; // Use direct navigation for better compatibility
130-
}, 1500)
126+
setError("Authentication failed. Please try again.")
127+
}
131128
} else {
132129
// Handle API error response
133130
let errorMessage = result.error || "Failed to sign in. Please try again."

0 commit comments

Comments
 (0)