fork download
  1. import React, { useState, useEffect } from "react";
  2. import { initializeApp } from "firebase/app";
  3. import { getAuth, signInWithPopup, GoogleAuthProvider, signOut, onAuthStateChanged } from "firebase/auth";
  4. import { getDatabase, ref, onValue, set, remove } from "firebase/database";
  5.  
  6. const firebaseConfig = {
  7. apiKey: "YOUR_API_KEY",
  8. authDomain: "YOUR_AUTH_DOMAIN",
  9. projectId: "YOUR_PROJECT_ID",
  10. storageBucket: "YOUR_STORAGE_BUCKET",
  11. messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
  12. appId: "YOUR_APP_ID",
  13. databaseURL: "YOUR_DATABASE_URL"
  14. };
  15.  
  16. const app = initializeApp(firebaseConfig);
  17. const auth = getAuth(app);
  18. const database = getDatabase(app);
  19. const provider = new GoogleAuthProvider();
  20.  
  21. export default function LoginPage() {
  22. const [user, setUser] = useState(null);
  23. const [onlineUsers, setOnlineUsers] = useState(0);
  24.  
  25. useEffect(() => {
  26. const unsubscribeAuth = onAuthStateChanged(auth, (user) => {
  27. if (user) {
  28. setUser(user);
  29. set(ref(database, `onlineUsers/${user.uid}`), {
  30. displayName: user.displayName,
  31. email: user.email
  32. }).catch((error) => console.error("Database Error:", error));
  33. } else {
  34. setUser(null);
  35. }
  36. });
  37.  
  38. const usersRef = ref(database, "onlineUsers");
  39. const unsubscribeUsers = onValue(usersRef, (snapshot) => {
  40. setOnlineUsers(snapshot.exists() ? Object.keys(snapshot.val()).length : 0);
  41. }, (error) => console.error("Database Read Error:", error));
  42.  
  43. return () => {
  44. unsubscribeAuth();
  45. unsubscribeUsers();
  46. };
  47. }, []);
  48.  
  49. const handleLogin = async () => {
  50. try {
  51. await signInWithPopup(auth, provider);
  52. } catch (error) {
  53. console.error("Login Error:", error);
  54. }
  55. };
  56.  
  57. const handleLogout = async () => {
  58. if (user) {
  59. try {
  60. await signOut(auth);
  61. await remove(ref(database, `onlineUsers/${user.uid}`));
  62. } catch (error) {
  63. console.error("Logout Error:", error);
  64. }
  65. }
  66. };
  67.  
  68. return (
  69. <div className="flex flex-col items-center justify-center min-h-screen bg-gray-100">
  70. <h1 className="text-2xl font-bold mb-4">Login System</h1>
  71. {user ? (
  72. <div className="text-center">
  73. <p>Welcome, {user.displayName}</p>
  74. <button onClick={handleLogout} className="bg-red-500 text-white px-4 py-2 mt-2 rounded">Logout</button>
  75. </div>
  76. ) : (
  77. <button onClick={handleLogin} className="bg-blue-500 text-white px-4 py-2 rounded">Login with Google</button>
  78. )}
  79. <p className="mt-4">Active Users: {onlineUsers}</p>
  80. </div>
  81. );
  82. }
  83.  
Success #stdin #stdout 0.04s 25632KB
stdin
Standard input is empty
stdout
import React, { useState, useEffect } from "react";
import { initializeApp } from "firebase/app";
import { getAuth, signInWithPopup, GoogleAuthProvider, signOut, onAuthStateChanged } from "firebase/auth";
import { getDatabase, ref, onValue, set, remove } from "firebase/database";

const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_AUTH_DOMAIN",
  projectId: "YOUR_PROJECT_ID",
  storageBucket: "YOUR_STORAGE_BUCKET",
  messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
  appId: "YOUR_APP_ID",
  databaseURL: "YOUR_DATABASE_URL"
};

const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const database = getDatabase(app);
const provider = new GoogleAuthProvider();

export default function LoginPage() {
  const [user, setUser] = useState(null);
  const [onlineUsers, setOnlineUsers] = useState(0);

  useEffect(() => {
    const unsubscribeAuth = onAuthStateChanged(auth, (user) => {
      if (user) {
        setUser(user);
        set(ref(database, `onlineUsers/${user.uid}`), {
          displayName: user.displayName,
          email: user.email
        }).catch((error) => console.error("Database Error:", error));
      } else {
        setUser(null);
      }
    });

    const usersRef = ref(database, "onlineUsers");
    const unsubscribeUsers = onValue(usersRef, (snapshot) => {
      setOnlineUsers(snapshot.exists() ? Object.keys(snapshot.val()).length : 0);
    }, (error) => console.error("Database Read Error:", error));

    return () => {
      unsubscribeAuth();
      unsubscribeUsers();
    };
  }, []);

  const handleLogin = async () => {
    try {
      await signInWithPopup(auth, provider);
    } catch (error) {
      console.error("Login Error:", error);
    }
  };

  const handleLogout = async () => {
    if (user) {
      try {
        await signOut(auth);
        await remove(ref(database, `onlineUsers/${user.uid}`));
      } catch (error) {
        console.error("Logout Error:", error);
      }
    }
  };

  return (
    <div className="flex flex-col items-center justify-center min-h-screen bg-gray-100">
      <h1 className="text-2xl font-bold mb-4">Login System</h1>
      {user ? (
        <div className="text-center">
          <p>Welcome, {user.displayName}</p>
          <button onClick={handleLogout} className="bg-red-500 text-white px-4 py-2 mt-2 rounded">Logout</button>
        </div>
      ) : (
        <button onClick={handleLogin} className="bg-blue-500 text-white px-4 py-2 rounded">Login with Google</button>
      )}
      <p className="mt-4">Active Users: {onlineUsers}</p>
    </div>
  );
}