React Native Academy · บทเรียน

การยืนยันตัวตนด้วยอีเมลและโทรศัพท์ผ่าน Firebase

สร้างระบบสมัครสมาชิกและเข้าสู่ระบบด้วยอีเมลและรหัสผ่าน เพิ่มการยืนยันหมายเลขโทรศัพท์ด้วย SMS OTP และรับฟังตัวสังเกตการณ์ onAuthStateChanged เพื่อควบคุมการนำทาง

บทเรียน 2 จาก 413 ขั้นตอน

การยืนยันตัวตนด้วยอีเมลและโทรศัพท์ผ่าน Firebase เป็นบทเรียน React Native Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน React Native Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส React Native Academy มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Firebase Auth Overview

Firebase Authentication provides ready-made sign-in flows for email/password, phone OTP, and social providers like Google and Apple. All authentication methods are accessed through the auth() singleton from @react-native-firebase/auth.

Firebase Auth manages tokens, refreshes them automatically, and persists the user session in native storage. The onAuthStateChanged observer is the single source of truth for authentication state in your app — always drive navigation from this callback rather than from individual sign-in function results.

Listening to Auth State Changes

Register an onAuthStateChanged observer early in your app's lifecycle, typically in the root layout component. It fires once with the current user on mount, and again whenever the user signs in or out.

The observer returns an unsubscribe function — always call it in the useEffect cleanup to prevent memory leaks. The observer's user parameter is null when no one is signed in and a FirebaseAuthTypes.User object when authenticated.

import auth from '@react-native-firebase/auth';
import { useEffect, useState } from 'react';

export function useFirebaseAuth() {
  const [user, setUser] = useState(null);
  const [initializing, setInitializing] = useState(true);

  useEffect(() => {
    const unsubscribe = auth().onAuthStateChanged((user) => {
      setUser(user);
      if (initializing) setInitializing(false);
    });

    return unsubscribe; // auto-cleanup on unmount
  }, []);

  return { user, initializing };
}

Email and Password Sign-Up

To register a new user with email and password, call auth().createUserWithEmailAndPassword(email, password). Firebase validates the email format and enforces the minimum password length (6 characters by default) on the server.

After successful sign-up, Firebase automatically signs in the new user — the onAuthStateChanged observer fires immediately with the new user object. You can then prompt the user to verify their email by calling user.sendEmailVerification().

import auth from '@react-native-firebase/auth';

async function signUpWithEmail(email: string, password: string) {
  try {
    const { user } = await auth().createUserWithEmailAndPassword(email, password);
    await user.sendEmailVerification();
    console.log('Sign-up successful, verification email sent to', email);
  } catch (error: any) {
    if (error.code === 'auth/email-already-in-use') {
      Alert.alert('Error', 'That email address is already in use.');
    } else if (error.code === 'auth/invalid-email') {
      Alert.alert('Error', 'That email address is invalid.');
    }
  }
}

Email and Password Sign-In

Returning users sign in with auth().signInWithEmailAndPassword(email, password). This returns a UserCredential object, but in most cases you do not need to handle the return value — the onAuthStateChanged observer already handles navigation.

Wrap sign-in calls in a try/catch and check the error.code property to display user-friendly messages. Firebase uses error codes like auth/wrong-password and auth/user-not-found that you can map to readable messages.

async function signInWithEmail(email: string, password: string) {
  try {
    await auth().signInWithEmailAndPassword(email, password);
    // onAuthStateChanged will fire and handle navigation
  } catch (error: any) {
    const messages: Record<string, string> = {
      'auth/wrong-password': 'Incorrect password.',
      'auth/user-not-found': 'No account found with this email.',
      'auth/too-many-requests': 'Too many failed attempts. Try again later.',
    };
    Alert.alert('Sign In Failed', messages[error.code] ?? 'An error occurred.');
  }
}

Signing Out

Call auth().signOut() to sign out the current user. This clears the local session and triggers onAuthStateChanged with null. If you are driving navigation from the observer, the app will automatically redirect to the sign-in screen.

Sign out is synchronous in behavior but returns a Promise that resolves when the local session is cleared. You do not need to await it unless you want to confirm completion before performing additional actions.

async function handleSignOut() {
  try {
    await auth().signOut();
    // onAuthStateChanged fires with null, navigator switches to auth stack
  } catch (error) {
    console.error('Sign out error:', error);
  }
}

Phone Authentication Overview

Firebase Phone Authentication works by sending a one-time SMS code to the user's phone number and verifying it. The flow has two steps: (1) call signInWithPhoneNumber to trigger the SMS, and (2) confirm the code the user enters.

On iOS, Firebase may silently verify the phone using APNs silent push notifications, bypassing the manual code entry step for known devices. This requires Push Notification capability in your app. On Android, Firebase uses the Play Integrity API to auto-verify codes on trusted devices.

Step 1: Sending the SMS Code

Call auth().signInWithPhoneNumber(phoneNumber) where phoneNumber is in E.164 format (e.g., +14155552671). The method returns a confirmation object that you store in state to use in the second step.

Show a UI that asks the user to enter the 6-digit code they receive via SMS. Use a numeric TextInput with keyboardType='number-pad' and maxLength={6} for a clean code entry experience.

import auth from '@react-native-firebase/auth';
import { useState } from 'react';

export function PhoneAuthScreen() {
  const [phoneNumber, setPhoneNumber] = useState('');
  const [confirmation, setConfirmation] = useState(null);

  async function sendCode() {
    try {
      const confirm = await auth().signInWithPhoneNumber(phoneNumber);
      setConfirmation(confirm);
      // Now show the code entry screen
    } catch (error) {
      Alert.alert('Error', 'Failed to send verification code.');
    }
  }

  // ...
}

Step 2: Confirming the Code

When the user enters the SMS code, call confirmation.confirm(code). If the code is correct, Firebase signs in the user and onAuthStateChanged fires with the authenticated user. If the code is wrong, the method throws with code auth/invalid-verification-code.

Each confirmation object can only be used once. If the code expires or the user requests a new one, you must call signInWithPhoneNumber again to get a new confirmation object.

async function confirmCode(code: string) {
  try {
    await confirmation.confirm(code);
    // User is now signed in, onAuthStateChanged fires
  } catch (error: any) {
    if (error.code === 'auth/invalid-verification-code') {
      Alert.alert('Error', 'The code you entered is incorrect.');
    } else if (error.code === 'auth/code-expired') {
      Alert.alert('Code Expired', 'Please request a new code.');
      setConfirmation(null); // Reset to phone number entry
    }
  }
}

Updating User Profile

After sign-up, you can update the user's display name and photo URL using auth().currentUser.updateProfile(). This stores the data directly on the Firebase Auth user object, making it available without a separate database query.

However, for rich user profiles (bio, address, etc.), it is better to store additional data in Firestore under a users collection, using the user's UID as the document ID. The Auth profile is for core identity data only.

async function updateUserProfile(displayName: string, photoURL: string) {
  const user = auth().currentUser;
  if (!user) return;

  await user.updateProfile({ displayName, photoURL });
  console.log('Profile updated:', auth().currentUser?.displayName);
}

// Also save extended data to Firestore:
await firestore().collection('users').doc(user.uid).set({
  displayName,
  bio: '',
  createdAt: firestore.FieldValue.serverTimestamp(),
});

Password Reset via Email

If a user forgets their password, call auth().sendPasswordResetEmail(email). Firebase sends an email with a link to reset their password. The link opens a Firebase-hosted web page where the user can enter a new password.

This flow does not require any additional native setup. The link is not a deep link into your app — it goes to Firebase's hosted page. If you want the reset flow to open inside your app, configure the Action URL in Firebase Authentication settings to point to your app's domain with dynamic links.

async function sendPasswordReset(email: string) {
  try {
    await auth().sendPasswordResetEmail(email);
    Alert.alert(
      'Email Sent',
      'Check your inbox for a link to reset your password.'
    );
  } catch (error: any) {
    if (error.code === 'auth/user-not-found') {
      // For security, show the same message even if the email is not found
      Alert.alert('Email Sent', 'If this email is registered, you will receive a reset link.');
    }
  }
}

Checking Email Verification Status

After sign-up with email/password, you may want to prevent access to the main app until the user verifies their email. Check auth().currentUser?.emailVerified inside onAuthStateChanged.

Note that emailVerified is not updated in real time — the user must reload the token for the value to reflect verification. Call auth().currentUser?.reload() and then re-read the property after the user claims to have clicked the verification link.

async function checkEmailVerification() {
  const user = auth().currentUser;
  if (!user) return;

  await user.reload(); // Refresh the user object
  if (user.emailVerified) {
    console.log('Email is verified — grant access');
    navigation.replace('Main');
  } else {
    Alert.alert(
      'Not Verified',
      'Please click the link in your email. Tap Resend to get a new link.',
      [
        { text: 'Resend', onPress: () => user.sendEmailVerification() },
        { text: 'OK' },
      ]
    );
  }
}

Quick Check

Test your understanding of React Native Mobile Development concepts from this lesson.

Lesson Recap

In this lesson you learned: how to implement email/password sign-up and sign-in with Firebase Auth, the two-step phone OTP authentication flow using signInWithPhoneNumber and confirmation.confirm, and how to manage user profile updates and email verification. Next up we read and write documents in Cloud Firestore.

เริ่มต้นได้ฟรี

เรียนรู้ JavaScript ด้วย AI tutor — ฟรี

เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป

คอร์ส
30
บทเรียน
120

คำถามที่พบบ่อย

บทเรียน “การยืนยันตัวตนด้วยอีเมลและโทรศัพท์ผ่าน Firebase” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การยืนยันตัวตนด้วยอีเมลและโทรศัพท์ผ่าน Firebase” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส React Native Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส React Native Academy มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การยืนยันตัวตนด้วยอีเมลและโทรศัพท์ผ่าน Firebase”

สร้างระบบสมัครสมาชิกและเข้าสู่ระบบด้วยอีเมลและรหัสผ่าน เพิ่มการยืนยันหมายเลขโทรศัพท์ด้วย SMS OTP และรับฟังตัวสังเกตการณ์ onAuthStateChanged เพื่อควบคุมการนำทาง คุณปฏิบัติ React Native Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน React Native Academy หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน React Native Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน

บทเรียน “การยืนยันตัวตนด้วยอีเมลและโทรศัพท์ผ่าน Firebase” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน React Native Academy นี้ได้ไหม

ได้ บทเรียน React Native Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การเชื่อม React Native Firebase กับโปรเจกต์
  2. การยืนยันตัวตนด้วยอีเมลและโทรศัพท์ผ่าน Firebase
  3. การอ่านและเขียนเอกสาร Firestore
  4. ตัวรับฟังแบบเรียลไทม์และการคงข้อมูลออฟไลน์
← กลับไปที่ React Native Academy