Skip to main content

Lazy Migration Explained with Code


What is lazy migration?

Lazy migration is a technique used when you want to migrate your database or user accounts gradually. For example, your usernames and passwords are stored in MySQL, but now you are using Firebase for authentication. However, you do not want to lose your existing users. In this case, you can apply lazy migration.

How does it work?

The login page is designed in such a way that it first checks the user's credentials in the old database. If the user is found, the system creates a Firebase account for that user and redirects them to the intended page where they are logged in.

If the user lookup fails, the system shows an error message such as "username or password not available" or may redirect the user to the signup page.

What are the benefits of lazy migration?

  • Existing users can log in seamlessly without facing difficulties.

  • There is no need for users to reset their passwords.

  • New users can directly sign up using the new authentication system.


Backend


import os
import requests
import bcrypt

from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel

from sqlalchemy.orm import Session

from passlib.context import CryptContext


# ===========================
# Import your database files
# ===========================
from database import SessionLocal
from models import User

# ===========================
# FastAPI App
# ===========================

app = FastAPI(
    title="Authentication API",
    version="1.0.0"
)

# ===========================
# CORS Middleware
# ===========================

app.add_middleware(
    CORSMiddleware,
    allow_origins=[
        "http://localhost:3000",
        "http://localhost:5173",
    ],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


FIREBASE_API_KEY = "FIREBASE_API_KEY"





class LoginRequest(BaseModel):

    email:str

    password:str





class LoginResponse(BaseModel):

    access_token:str

    token_type:str

    role:str


def hash_password(password: str) -> str:
    return bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode()

def verify_password(plain_password: str, hashed_password: str) -> bool:
    return bcrypt.checkpw(plain_password.encode(), hashed_password.encode())


def create_firebase_user(email,password):


    signup_url = (
        "https://identitytoolkit.googleapis.com/"
        "v1/accounts:signUp?key="
        + FIREBASE_API_KEY
    )



    response = requests.post(

        signup_url,

        json={

            "email":email,

            "password":password,

            "returnSecureToken":True

        }

    )



    result=response.json()



    # User already migrated

    if (
        "error" in result and
        result["error"]["message"]
        == "EMAIL_EXISTS"
    ):



        login_url=(

        "https://identitytoolkit.googleapis.com/"
        "v1/accounts:signInWithPassword?key="
        + FIREBASE_API_KEY

        )



        response=requests.post(

            login_url,

            json={

                "email":email,

                "password":password,

                "returnSecureToken":True

            }

        )



        result=response.json()




    if "idToken" not in result:


        raise HTTPException(

            status_code=500,

            detail="Firebase login failed"

        )



    return result







@app.post(
    "/loginFirebase",
    response_model=LoginResponse
)
def login(data:LoginRequest):



    db=SessionLocal()



    try:


        # CHANGE THIS IF YOUR COLUMN IS username

        user=db.query(User).filter(

            User.username == data.email

        ).first()



    finally:

        db.close()





    if not user:


        raise HTTPException(

            status_code=400,

            detail="Incorrect email or password"

        )






    # Existing bcrypt check

    if not verify_password(

        data.password,

        user.password

    ):


        raise HTTPException(

            status_code=400,

            detail="Incorrect email or password"

        )






    # Lazy migration to Firebase

    firebase_user=create_firebase_user(

        data.email,

        data.password

    )






    return {


        "access_token":

            firebase_user["idToken"],


        "token_type":

            "bearer",


        "role":

            user.role

    }

Frontend

<div id="login-container" style="font-family: sans-serif; margin:auto auto; max-width: 300px;">
  <h2>Login to Access Premium Content</h2>

  <form id="login-form">

    <div style="margin-bottom: 10px;">
      <label>Email:</label><br />
      <input id="username" placeholder="email@example.com" required
        style="box-sizing: border-box; padding: 8px; width: 100%;"
        type="email" />
    </div>

    <div style="margin-bottom: 10px;">
      <label>Password:</label><br />
      <input id="password" required
        style="box-sizing: border-box; padding: 8px; width: 100%;"
        type="password" />
    </div>

    <div id="error-message" style="color:red; margin-bottom:10px;"></div>

    <button id="login-btn"
      style="background: rgb(0,123,255); color:white; cursor:pointer; padding:10px; width:100%; border:none;"
      type="submit">
      Login
    </button>

  </form>

<script type="module">

const loginForm = document.getElementById("login-form");
const errorDisplay = document.getElementById("error-message");
const loginBtn = document.getElementById("login-btn");

const API_URL = "http://localhost:8000/loginFirebase";

loginForm.addEventListener("submit", async (e)=>{

    e.preventDefault();

    errorDisplay.textContent = "";

    loginBtn.disabled = true;
    loginBtn.textContent = "Checking...";

    const email = document.getElementById("username").value;

    const password = document.getElementById("password").value;

    try {

        const response = await fetch(
            API_URL,
            {
                method:"POST",

                headers:{
                    "Content-Type":"application/json"
                },

                body:JSON.stringify({
                    email:email,
                    password:password
                })
            }
        );

        const data = await response.json();

        if(!response.ok){
            throw new Error(
                data.detail || "Login failed"
            );
        }

        localStorage.setItem(
            "firebase_token",
            data.access_token
        );

        localStorage.setItem(
            "role",
            data.role
        );

        window.location.href =
        "https://www.salimwireless.com";

    }

    catch(error){

        errorDisplay.style.color="red";

        errorDisplay.textContent =
        error.message;

        loginBtn.disabled=false;

        loginBtn.textContent="Login";

    }

});

</script>



Contact Us

Name

Email *

Message *

Popular Posts

GMSK BER vs SNR (with Simulation)

  GMSK Performance: Why the BER vs. SNR Curve Matters If you’ve ever wondered why GMSK (Gaussian Minimum Shift Keying) became the backbone of the global GSM revolution, the answer lies in its unique balance of spectral efficiency and power performance. But there is no free lunch in engineering. To get that sleek, narrow spectrum, you have to pay a price in Bit Error Rate (BER) . In this guide, we break down the theoretical BER vs. SNR performance of GMSK, the "magic" of the BT product, and how to optimize your link budget for real-world conditions. What is GMSK and Why Should You Care? GMSK is a derivative of MSK (Minimum Shift Keying) that uses a Gaussian pre-modulation filter. This filter "smooths" the phase transitions, significantly reducing sideband power. The result? A constant envelope signal that allows you to use high-efficiency Class-C amplifiers without distorting the signal. This is the secr...

UGC NET Electronic Science Previous Year Question Papers with Solutions

Download Papers and Solutions Exam Pattern Preparation Tips FAQs More Home / Engineering & Other Exams / UGC NET 2026 PYQ 📊 Exam Highlights: Electronic Science (88) Feature Details Junior Research Fellowship (JRF) ₹37,000 + HRA per month Eligibility M.Sc/M.Tech in Electronics (55%) Validity of Certificate JRF (3 Years) | Lectureship (Lifetime) 📥 Download UGC NET Electronics PDFs Complete collection of previous year question papers, answer keys and explanations for Subject Code 88. Start Downloading 📂 View All Question Papers June 2026 - Question Paper Download PDF June 202...

What is a Supernode?

  Circuit Analysis What Is a Supernode? A supernode is formed when an ideal voltage source connects two non-reference nodes. It allows us to apply Kirchhoff's Current Law (KCL) to the combined circuit boundary. 1. Understanding a Supernode In nodal analysis, a voltage source between two unknown-voltage nodes makes the current through that source difficult to express directly using Ohm's law. We combine the two nodes and the voltage source into one extended region called a supernode. Key idea Apply KCL around the outer boundary of the supernode, then use the voltage source to write an additional voltage equation. 2. Supernode Circuit Diagram The voltage source connects nodes V L an...

A binary ripple counter is designed to count (0)₁₀ to (64)₁₀. Which of the following is/are the number of flip-flops required ...

  Q. A binary ripple counter is designed to count  (0)₁₀ to (64)₁₀ . Which of the following is/are the number of flip-flops required to design the counter?   (A) 6 (B) 7 (C) 4 (D) 5 Solution A binary ripple counter must count from (0)₁₀ to (64)₁₀ , including both endpoints. Step 1: Calculate the total number of states Since both 0 and 64 are included, add 1 to the difference: N = Last value − First value + 1 N = 64 − 0 + 1 = 65 states The counter visits every integer from 0 through 64: 0, 1, 2, 3, ..., 63, 64 There are 65 distinct states in total. Step 2: Calculate the number of flip-flops Each flip-flop stores one bit. With n flip-flops, the counter can represent 2ⁿ distinct states. 2⁶ = 64 states (not enough) 2⁷ = 128 states (eno...

The cutoff frequency (in GHz) for the dominant TE10 mode of an air-filled rectangular waveguide of ...

  Q. The cutoff frequency (in GHz) for the dominant TE10 mode of an air-filled rectangular waveguide of inner dimension 0.28 inch×0.14 inch is __. (rounded off to two decimal places). Given Information Waveguide dimensions = 0.28 inch × 0.14 inch Wider dimension (a) = 0.28 inch Smaller dimension (b) = 0.14 inch Medium = Air Dominant mode = TE 10 Speed of light (c) = 3 × 10 8 m/s Step 1: Cutoff Frequency Formula The cutoff frequency of a rectangular waveguide is: f c = (c / 2) √[(m/a) 2 + (n/b) 2 ] For the dominant TE 10 mode: m = 1, n = 0 f c = c / 2a Step 2: Convert Inch into Meter We know that 1 inch = 0.0254 meter. a = 0.28 × 0.0254 a = 0.007112 m ...

SRAM, DRAM, EPROM, MRAM, and DDRAM Explained

Computer Fundamentals Types of Memory and Their Technologies Understand the fundamental relationship between different types of computer memory and the technologies used to implement them. Fundamental Matching Memory type, technology, and key characteristics Memory Type Technology Key Characteristic Cache Memory SRAM Very fast; stores frequently accessed data Main Memory DRAM Holds programs and data currently in use Au...

Parametric Down-Conversion of Photons

  Nonlinear Optics One incoming photon is converted into two lower-energy photons, typically in a nonlinear optical medium. Energy is conserved: E in = E 1 + E 2 E in ​ = E 1 ​ + E 2 ​ . Parametric Down-Conversion A nonlinear optical process in which one pump photon is converted into two lower-energy photons, known as the signal and idler photons. 1 Energy Conservation The energy of the pump photon equals the sum of the energies of the signal and idler photons. \[ \boxed{\hbar\omega_p=\hbar\omega_s+\hbar\omega_i} \] \[ \boxed{\omega_p=\omega_s+\omega_i} \] ωₚ Pump angular frequency ...

An S-band radar transmitting at 3 GHz radiates 200 kW of power. Determine the signal power density at a range of 100 ...

Q. An S-band radar transmitting at 3 GHz radiates 200 kW of power. Determine the signal power density at a range of 100 nautical miles if the effective area of the radar antenna is 9 m². Solution Given, Transmitted power: P t = 200 kW = 200,000 W Frequency: f = 3 GHz = 3 × 10⁹ Hz Range: R = 100 nautical miles Effective antenna area: A e = 9 m² Speed of light: c = 3 × 10⁸ m/s Step 1: Convert Nautical Miles to Meters One nautical mile equals 1852 meters. R = 100 × 1852 = 185200 m Step 2: Calculate the Wavelength The wavelength is calculated using the relationship between the speed of light and frequency: λ = c / f λ = (3 × 10⁸) / (3 × 10⁹) λ = 0.1 m Step 3: Calculate the Antenna Gain The relationship between effective aperture and antenna gain is: G = (4πAₑ) / λ² ...