Ojasa Mirai

Ojasa Mirai

Cloud

Loading...

Learning Level

๐ŸŸข Beginner๐Ÿ”ต Advanced
๐Ÿ”ง Firebase Project Setup๐Ÿ”‘ Firebase Authentication๐Ÿ” Firestore Security Rules๐Ÿ” Firestore Advanced Queriesโšก Realtime Database๐Ÿ“ Firebase Storageโšก Firebase Functions Advanced๐Ÿงช Firebase Emulator๐Ÿ“Š Firebase Analyticsโšก Firebase Performance๐Ÿ“ฌ Firebase Cloud Messaging๐Ÿš€ Firebase Hosting Advanced
Cloud/Firebase Integration/Firebase Authentication

๐Ÿ”‘ Firebase Authentication

Introduction

Firebase Authentication provides secure, easy-to-use authentication with support for multiple providers including email/password, Google, Facebook, GitHub, and phone authentication.

Key Learning Outcomes

By the end of this lesson, you'll understand:

  • Email/password authentication
  • Social provider authentication (Google, Facebook, GitHub)
  • Phone number authentication
  • User management and profile handling
  • Custom claims for role-based access
  • Session management and token handling
  • Authentication state persistence

Authentication Methods

Email/Password Authentication

import { createUserWithEmailAndPassword, signInWithEmailAndPassword, signOut } from "firebase/auth";
import { auth } from "./firebase-config";

// Sign Up
async function handleSignUp(email, password) {
  try {
    const userCredential = await createUserWithEmailAndPassword(auth, email, password);
    console.log("User created:", userCredential.user.uid);
    return userCredential.user;
  } catch (error) {
    console.error("Sign up error:", error.message);
  }
}

// Sign In
async function handleSignIn(email, password) {
  try {
    const userCredential = await signInWithEmailAndPassword(auth, email, password);
    console.log("Signed in:", userCredential.user.email);
    return userCredential.user;
  } catch (error) {
    console.error("Sign in error:", error.message);
  }
}

// Sign Out
async function handleSignOut() {
  try {
    await signOut(auth);
    console.log("Signed out successfully");
  } catch (error) {
    console.error("Sign out error:", error.message);
  }
}

Google Sign-In

import { signInWithPopup, GoogleAuthProvider } from "firebase/auth";
import { auth } from "./firebase-config";

const googleProvider = new GoogleAuthProvider();

async function signInWithGoogle() {
  try {
    const result = await signInWithPopup(auth, googleProvider);
    console.log("Signed in:", result.user.email);
    return result.user;
  } catch (error) {
    console.error("Google sign-in error:", error.message);
  }
}

GitHub Sign-In

import { signInWithPopup, GithubAuthProvider } from "firebase/auth";
import { auth } from "./firebase-config";

const githubProvider = new GithubAuthProvider();

async function signInWithGitHub() {
  try {
    const result = await signInWithPopup(auth, githubProvider);
    console.log("GitHub user:", result.user.email);
    return result.user;
  } catch (error) {
    console.error("GitHub sign-in error:", error.message);
  }
}

User Management

Get Current User

import { onAuthStateChanged } from "firebase/auth";
import { auth } from "./firebase-config";

// Listen for authentication state changes
onAuthStateChanged(auth, (user) => {
  if (user) {
    console.log("User is signed in:", user.uid);
    console.log("Email:", user.email);
    console.log("Display Name:", user.displayName);
  } else {
    console.log("User is signed out");
  }
});

Update User Profile

import { updateProfile } from "firebase/auth";
import { auth } from "./firebase-config";

async function updateUserProfile(displayName, photoURL) {
  try {
    await updateProfile(auth.currentUser, {
      displayName: displayName,
      photoURL: photoURL
    });
    console.log("Profile updated");
  } catch (error) {
    console.error("Update error:", error.message);
  }
}

Reset Password

import { sendPasswordResetEmail } from "firebase/auth";
import { auth } from "./firebase-config";

async function resetPassword(email) {
  try {
    await sendPasswordResetEmail(auth, email);
    console.log("Password reset email sent");
  } catch (error) {
    console.error("Reset error:", error.message);
  }
}

React Integration Example

// useAuth.js - Custom Hook
import { useState, useEffect } from 'react';
import { auth } from './firebase-config';
import { onAuthStateChanged, signOut } from 'firebase/auth';

export function useAuth() {
  const [currentUser, setCurrentUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, (user) => {
      setCurrentUser(user);
      setLoading(false);
    });

    return unsubscribe;
  }, []);

  const logout = () => {
    return signOut(auth);
  };

  return { currentUser, loading, logout };
}

// App.js - Using the hook
import { useAuth } from './hooks/useAuth';

export default function App() {
  const { currentUser, loading } = useAuth();

  if (loading) return <div>Loading...</div>;

  return (
    <div>
      {currentUser ? (
        <div>Welcome, {currentUser.email}!</div>
      ) : (
        <div>Please sign in</div>
      )}
    </div>
  );
}

Phone Number Authentication

import { RecaptchaVerifier, signInWithPhoneNumber } from "firebase/auth";
import { auth } from "./firebase-config";

// Set up reCAPTCHA
window.recaptchaVerifier = new RecaptchaVerifier('recaptcha-container', {
  'size': 'invisible',
}, auth);

// Sign in with phone
async function signInWithPhone(phoneNumber) {
  try {
    const appVerifier = window.recaptchaVerifier;
    const confirmationResult = await signInWithPhoneNumber(
      auth,
      phoneNumber,
      appVerifier
    );
    window.confirmationResult = confirmationResult;
    console.log("SMS sent to", phoneNumber);
  } catch (error) {
    console.error("Phone sign-in error:", error.message);
  }
}

// Verify OTP
async function verifyOTP(code) {
  try {
    const result = await window.confirmationResult.confirm(code);
    console.log("User signed in:", result.user.uid);
  } catch (error) {
    console.error("Verification error:", error.message);
  }
}

Best Practices

1. Secure Password Requirements

const validatePassword = (password) => {
  const hasUpperCase = /[A-Z]/.test(password);
  const hasLowerCase = /[a-z]/.test(password);
  const hasNumbers = /\d/.test(password);
  const hasNonalphaNumericChar = /\W/.test(password);
  const isLengthValid = password.length >= 8;

  return hasUpperCase && hasLowerCase && hasNumbers && 
         hasNonalphaNumericChar && isLengthValid;
};

2. Error Handling

function getErrorMessage(error) {
  switch (error.code) {
    case 'auth/user-not-found':
      return 'No account with that email';
    case 'auth/wrong-password':
      return 'Incorrect password';
    case 'auth/email-already-in-use':
      return 'Email already in use';
    case 'auth/weak-password':
      return 'Password is too weak';
    default:
      return 'Authentication error';
  }
}

3. Session Persistence

import { setPersistence, browserLocalPersistence } from "firebase/auth";

// Enable persistence (default in web SDK)
await setPersistence(auth, browserLocalPersistence);

Key Takeaways

  • **Firebase Authentication** provides secure, scalable user authentication
  • **Multiple providers** enable users to choose their preferred sign-in method
  • **Auth state** should be managed with `onAuthStateChanged` listener
  • **Custom hooks** simplify authentication logic in React
  • **Error messages** should be user-friendly and specific
  • **Session persistence** keeps users logged in across browser sessions
  • **Password requirements** should enforce strong security standards
  • **Profile updates** enable customization of user information

Next Steps

Explore Firestore Security Rules for protecting user data, or implement multi-factor authentication for enhanced security.


Resources

Python Docs

Ojasa Mirai

Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.

Learn Deep โ€ข Build Real โ€ข Verify Skills โ€ข Launch Forward

Courses

PythonFastapiReactJSCloud

ยฉ 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn