Firebase Authentication Starter Guide: Building a Secure Login System

Firebase Authentication Starter Guide – Build a Secure Login System
Introduction

This guide walks you through creating a complete authentication system using Firebase. We'll cover email/password login, signup, password reset, and user session management.

 The project includes:
- Login/Signup forms
- Password recovery
- Welcome dashboard
- Session persistence


Project Structure

auth-starter-master/
├── firebase.js          # Firebase configuration
├── index.css            # Styling for auth pages
├── index.html           # Login/Signup page
├── index.js             # Auth logic
├── welcome.html         # Dashboard after login
└── welcome.js           # Logout functionality


1. Firebase Configuration (firebase.js)

```javascript
const firebaseConfig = {
  apiKey: "Your Key",
  authDomain: "Your Auth Domain",
  projectId: "Your Id,
  storageBucket: "Your Storage Bucket,
  messagingSenderId: "Your Id,
  appId: "Your AppId",
  measurementId: "Your
};

// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
```

2. Stylish Login Form (index.css)

```css
@import url('https://fonts.googleapis.com/css?family=Ubuntu:wght@700&display=swap');

body {
  background: #F8F8F8;
  font-family: 'Roboto', sans-serif;
}

.card {
  width: 400px;
  margin-top: 50px;
  box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}

.custom-field {
  position: relative;
  margin: 20px 0;
}

.custom-field input {
  padding: 12px;
  width: 300px;
  border: 1.5px solid gray;
  border-radius: 3px;
  outline-color: deepskyblue;
}

.placeholder {
  position: absolute;
  left: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #aaa;
  transition: all 0.3s ease;
}

input:focus + .placeholder,
input:valid + .placeholder {
  top: 10px;
  font-size: 10px;
  color: #222;
  background: white;
  padding: 0 5px;
}

.message {
  font-size: 24px;
  color: steelblue;
}

.success {
  font-size: 18px;
  color: seagreen;
  margin: 15px 0;
}
```

3. Login/Signup Page (index.html)

```html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Auth Demo</title>
  <!-- Font Awesome -->
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css" rel="stylesheet">
  <!-- Google Fonts -->
  <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" rel="stylesheet">
  <!-- MDB -->
  <link href="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/3.5.0/mdb.min.css" rel="stylesheet">
  <!-- Custom CSS -->
  <link href="./index.css" rel="stylesheet">
</head>
<body class="d-flex justify-content-center p-5">
  <div class="card">
    <div class="card-header">
      <center><h3>Login Form</h3></center>
    </div>
    <form id="loginForm" class="card-body px-5 py-4">
      <center>
        <small><span id="error" style="color: red"></span></small>
      </center>
      <center>
        <label class="custom-field">
          <input id="email" type="email" class="input" required />
          <span class="placeholder">Email</span>
        </label>
        <br />
        <label class="custom-field">
          <input id="password" type="password" class="input" required />
          <span class="placeholder">Password</span>
        </label>
      </center>
      <br/><br/>
      <a href="#" onclick="forgotPass()">Forgot Password?</a>
      <center>
        <button type="submit" class="btn btn-primary">Login</button>
        <button type="button" onclick="signUp()" class="btn btn-secondary">Sign Up</button>
      </center>
    </form>
  </div>

  <!-- Firebase SDK -->
  <script src="https://www.gstatic.com/firebasejs/8.6.7/firebase-app.js"></script>
  <script src="https://www.gstatic.com/firebasejs/8.6.7/firebase-auth.js"></script>
  <script src="firebase.js"></script>
  <script src="index.js"></script>
</body>
</html>
```

4. Authentication Logic (index.js)

```javascript
// Prevent form submission
document.getElementById("loginForm").addEventListener("submit", (event) => {
  event.preventDefault();
  login();
});

// Redirect if already logged in
firebase.auth().onAuthStateChanged((user) => {
  if (user) {
    location.replace("welcome.html");
  }
});

function login() {
  const email = document.getElementById("email").value;
  const password = document.getElementById("password").value;
  
  firebase.auth().signInWithEmailAndPassword(email, password)
    .catch((error) => {
      document.getElementById("error").innerHTML = error.message;
    });
https://unhealthyirreparable.com/cit2c8ca?key=7566cfdb82de49ba4912160b26b7621f
}

function signUp() {
  const email = document.getElementById("email").value;
  const password = document.getElementById("password").value;
  
  firebase.auth().createUserWithEmailAndPassword(email, password)
    .catch((error) => {
      document.getElementById("error").innerHTML = error.message;
    });
}

function forgotPass() {
  const email = document.getElementById("email").value;
  
  firebase.auth().sendPasswordResetEmail(email)
    .then(() => {
      alert("Password reset link sent to your email");
    })
    .catch((error) => {
      document.getElementById("error").innerHTML = error.message;
    });
}
```

5. Welcome Dashboard (welcome.html)

```html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Welcome</title>
  <link rel="stylesheet" href="./index.css">
  <!-- MDB -->
  <link href="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/3.5.0/mdb.min.css" rel="stylesheet">
</head>
<body>
  <center>
    <div style="margin:100px">
      <span id="user" class="message">Hello, User</span>
      <div class="success">
        <span>Welcome to Auth Starter! You're successfully logged in!</span>
      </div>
      <br/>
      <button class="btn btn-danger" onclick="logout()">Logout</button>
    </div>
  </center>

  <!-- Firebase SDK -->
  <script src="https://www.gstatic.com/firebasejs/8.6.7/firebase-app.js"></script>
  <script src="https://www.gstatic.com/firebasejs/8.6.7/firebase-auth.js"></script>
  <script src="firebase.js"></script>
  <script src="welcome.js"></script>
</body>
</html>
```

6. Logout Functionality (welcome.js)

```javascript
// Check auth state
firebase.auth().onAuthStateChanged((user) => {
  if (!user) {
    location.replace("index.html");
  } else {
    document.getElementById("user").innerHTML = `Hello, ${user.email}`;
  }
});

// Logout function
function logout() {
  firebase.auth().signOut();
}
```

Key Features Implemented
1. Email/Password Authentication
   - Secure login/signup
   - Form validation
   - Error handling

2. Password Recovery
   - Reset link via email

3. Session Management
   - Persistent login state
   - Automatic redirection

4. Responsive UI
   - Clean material design
   - Animated form fields

Security Notes
- Always use HTTPS in production
- Enable email verification for signups
- Consider adding reCAPTCHA
- Set up Firebase Security Rules

This complete authentication system can be extended with:
- Social logins (Google, Facebook)
- Phone authentication
- Multi-factor auth
- User profile management


Comments

Popular posts from this blog

How to Upload Your Local Project to GitHub Properly

YouTube Videos, Translation, AI Tools Aur Hindi Mein Dekhne Ka Experience

How to Build a Telegram Bot Using Node.js – Step-by-Step Guide