0

LLMs are failing me on this seemingly simple task, so I'm seeking community advise. I have a django application, which works fine. Both when I develop locally, and in production at https://my.domain

Now, I need to add one more page to the application, that will be behind firebase authentication flow. The reason being I've already gotten a pool of users from my mobile application (unrelated to https://my.domain). I want to give access to the same users to their data they generated through my mobile app. My understanding was if they used same firebase ID (either google id, or apple id) as in app, it should be doable.

Problems start pretty much off the bat. Here's what I did

  1. I've created firebase app and generated config data in firebaseConfig. enter image description here
  2. Since I'm developing locally, I've added localhost to the list of Authorized domains list in firebase console.
  3. Google, Apple, Email logins are enabled. As they always were because of my mobile application.
  4. Service account credentials file is downloaded, stored, pointed at in django.
  5. I ran local server through
python manage.py runserver
  1. I added login button in my login template.

enter image description here

  1. When I hit login (through google popup), list of my google accounts open. But after selecting one - it kind of gets stuck for a while and closes.

enter image description here enter image description here

I'm not entirely sure what other info to give at this point, but if I'm missing something please let me know.

Thanks

PS: Relevant code snippets from various parts of the codebase (python+javascript)

  1. urls.py
...
path("newpage/", newpage, name="newpage"),  # page that I want to put behind the authwall
...
  1. firebase-auth.js

// Firebase Auth Handling
document.addEventListener('DOMContentLoaded', function () {
    console.log("Firebase auth script loaded");
    
    try {
        // Initialize Firebase
        const firebaseConfig = {
            ...my_config
        };
        
        console.log("Initializing Firebase with config:", firebaseConfig);
        
        // Check if Firebase is loaded
        if (typeof firebase === 'undefined') {
            console.error("Firebase SDK not loaded");
            return;
        }
        
        firebase.initializeApp(firebaseConfig);
        console.log("Firebase initialized successfully");

        // UI configuration for FirebaseUI
        const uiConfig = {
            signInOptions: [
                firebase.auth.GoogleAuthProvider.PROVIDER_ID,
                firebase.auth.EmailAuthProvider.PROVIDER_ID
            ],
            signInFlow: 'popup',
            signInSuccessUrl: '/newpage/', // Add this for redirect after success
            callbacks: {
                signInSuccessWithAuthResult: function (authResult, redirectUrl) {
                    console.log("Sign in success", authResult);
                    // User successfully signed in
                    const user = authResult.user;
                    document.getElementById('auth-container').style.display = 'none';
                    document.getElementById('content-container').style.display = 'block';
                    document.getElementById('user-display-name').textContent = user.displayName || user.email;
                    return false; // Don't redirect
                },
                signInFailure: function(error) {
                    console.error("Sign in failure:", error);
                }
            }
        };

    // Initialize auth 
    firebase.auth().onAuthStateChanged(function (user) {
        console.log("Auth state changed:", user ? "User logged in" : "User logged out");
        if (user) {
            // User is signed in
            console.log("User info:", user.displayName, user.email);
            document.getElementById('auth-container').style.display = 'none';
            document.getElementById('content-container').style.display = 'block';
            document.getElementById('user-display-name').textContent = user.displayName || user.email;
        } else {
            // No user is signed in
            console.log("No user signed in, initializing FirebaseUI");
            document.getElementById('auth-container').style.display = 'block';
            document.getElementById('content-container').style.display = 'none';

            try {
                // Initialize FirebaseUI
                if (typeof firebaseui === 'undefined') {
                    console.error("FirebaseUI is not defined");
                    return;
                }
                
                const ui = new firebaseui.auth.AuthUI(firebase.auth());
                ui.start('#firebaseui-auth-container', uiConfig);
                console.log("FirebaseUI initialized");
            } catch (error) {
                console.error("Error initializing FirebaseUI:", error);
            }
        }
    });

    // Logout function
    const logoutButton = document.getElementById('logout-button');
    if (logoutButton) {
        logoutButton.addEventListener('click', function () {
            console.log("Logout button clicked");
            firebase.auth().signOut().then(function () {
                // Sign-out successful
                console.log('User signed out');
            }).catch(function (error) {
                // An error happened
                console.error('Sign out error:', error);
            });
        });
    } else {
        console.error("Logout button not found in the DOM");
    }
    
    } catch (error) {
        console.error("Global error in Firebase initialization:", error);
    }
});

  1. new_page.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>New Page</title>
    
    <!-- Firebase v9 SDK using CDN for compatibility -->
    <script src="https://www.gstatic.com/firebasejs/9.6.0/firebase-app-compat.js"></script>
    <script src="https://www.gstatic.com/firebasejs/9.6.0/firebase-auth-compat.js"></script>
</head>
<body>
    <div class="container">
        <!-- Auth container (visible when not logged in) -->
        <div id="auth-container">
            <h1>New Page Login</h1>
            <p>Please sign in to continue:</p>
            <div>
                <button id="login-google">Sign in with Google</button>
                <div style="margin-top: 20px; border-top: 1px solid #eee; padding-top: 20px;">
                    <h3>Development Mode Login</h3>
                    <p>For local testing when Google auth doesn't work:</p>
                    <div style="margin-bottom: 10px;">
                        <input type="email" id="email-input" placeholder="Email" style="padding: 8px; width: 100%; margin-bottom: 10px;">
                        <input type="password" id="password-input" placeholder="Password" style="padding: 8px; width: 100%;">
                    </div>
                    <button id="login-email">Sign in with Email</button>
                    <button id="register-email">Create Account</button>
                </div>
            </div>
            <div id="login-status"></div>
        </div>
        
        <!-- Content container (visible when logged in) -->
        <div id="content-container" style="display: none;">
            <div class="header">
                <h1>New Page Dashboard</h1>
                <div class="user-info">
                    <span>Welcome, <span id="user-display-name"></span></span>
                    <button id="logout-button">Logout</button>
                </div>
            </div>
            <div class="content">
                <h2>Hello World!</h2>
                <p>This is your Firebase-authenticated New Page page.</p>
                <div id="auth-details">
                    <p>User ID: <strong id="user-id"></strong></p>
                    <p>Authentication Method: <span id="auth-method"></span></p>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Initialize Firebase with Firebase v9 compat SDK
        const firebaseConfig = {
            ...my_config
        };
        
        // Initialize Firebase
        firebase.initializeApp(firebaseConfig);
        
        // Elements
        const authContainer = document.getElementById('auth-container');
        const contentContainer = document.getElementById('content-container');
        const userDisplayName = document.getElementById('user-display-name');
        const userId = document.getElementById('user-id');
        const authMethod = document.getElementById('auth-method');
        const loginGoogleBtn = document.getElementById('login-google');
        const logoutButton = document.getElementById('logout-button');
        const loginStatus = document.getElementById('login-status');
        
        // Listen for auth state changes
        firebase.auth().onAuthStateChanged(function(user) {
            console.log("Auth state changed", user ? "User logged in" : "No user");
            
            if (user) {
                // User is signed in
                authContainer.style.display = 'none';
                contentContainer.style.display = 'block';
                
                // Update user info
                userDisplayName.textContent = user.isAnonymous ? 
                    "Guest User (Dev Mode)" : 
                    (user.displayName || user.email || "Authenticated User");
                    
                userId.textContent = user.uid;
                authMethod.textContent = user.isAnonymous ? 
                    "Anonymous (Development Mode)" : 
                    (user.providerData.length > 0 ? user.providerData[0].providerId : "Unknown");
                
                console.log("User details:", {
                    displayName: user.displayName,
                    email: user.email,
                    uid: user.uid,
                    isAnonymous: user.isAnonymous,
                    providers: user.providerData.map(p => p.providerId)
                });
            } else {
                // User is signed out
                authContainer.style.display = 'block';
                contentContainer.style.display = 'none';
            }
        });
        
        // Sign in with Google
        loginGoogleBtn.addEventListener('click', function() {
            loginStatus.textContent = "Connecting to Google...";
            
            const provider = new firebase.auth.GoogleAuthProvider();
            
            // Log environment info for debugging
            console.log("Starting Google sign in from:", window.location.href);
            
            firebase.auth().signInWithPopup(provider)
                .then(function(result) {
                    console.log("Google sign in successful", result.user);
                    loginStatus.textContent = "";
                })
                .catch(function(error) {
                    console.error("Google sign in error:", error);
                    loginStatus.textContent = "Error: " + error.message;
                    
                    if (error.code === 'auth/popup-closed-by-user') {
                        loginStatus.textContent += " Try using the Guest login for development.";
                    }
                });
        });
        
        // Sign in with email/password
        document.getElementById('login-email').addEventListener('click', function() {
            const email = document.getElementById('email-input').value;
            const password = document.getElementById('password-input').value;
            
            if (!email || !password) {
                loginStatus.textContent = "Please enter both email and password";
                return;
            }
            
            loginStatus.textContent = "Signing in...";
            
            firebase.auth().signInWithEmailAndPassword(email, password)
                .then(function(result) {
                    console.log("Email sign in successful", result.user);
                    loginStatus.textContent = "";
                })
                .catch(function(error) {
                    console.error("Email sign in error:", error);
                    loginStatus.textContent = "Error: " + error.message;
                });
        });
        
        // Register with email/password
        document.getElementById('register-email').addEventListener('click', function() {
            const email = document.getElementById('email-input').value;
            const password = document.getElementById('password-input').value;
            
            if (!email || !password) {
                loginStatus.textContent = "Please enter both email and password";
                return;
            }
            
            if (password.length < 6) {
                loginStatus.textContent = "Password must be at least 6 characters";
                return;
            }
            
            loginStatus.textContent = "Creating account...";
            
            firebase.auth().createUserWithEmailAndPassword(email, password)
                .then(function(result) {
                    console.log("Account created successfully", result.user);
                    loginStatus.textContent = "Account created! Signing in...";
                })
                .catch(function(error) {
                    console.error("Account creation error:", error);
                    loginStatus.textContent = "Error: " + error.message;
                });
        });
        
        // Sign out
        logoutButton.addEventListener('click', function() {
            firebase.auth().signOut()
                .then(function() {
                    console.log("Sign out successful");
                })
                .catch(function(error) {
                    console.error("Sign out error:", error);
                });
        });
    </script>
</body>
</html>

3
  • 1
    Please edit the question to show the application code that doesn't work the way you expect. This doesn't sound like it has anything to do with djang, but everything to do with your web app and its (javascript?) code that you wrote for integration with Firebase Auth. Without seeing that, we can't see if you might be doing something wrong there. We should be able to take your code and instructions and use it to reproduce the same behavior. Commented Apr 7 at 22:28
  • Fair enough. I'll try to add relevant snippets to the post Commented Apr 7 at 22:34
  • @DougStevenson Done. pardon the debug stuff. Commented Apr 8 at 2:03

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.