Home β€Ί User Authentication
πŸ” Module 04 Β· Intermediate

User Authentication

What if your app could remember your favorite color, greet you by name, and save your high score? To do that, it first needs to know who *you* are! Today, you'll learn how to build the digital lock and key for your very own apps, starting with a Top-Secret Diary! Ready to become the bouncer of your own creation? Let's go! πŸš€

πŸ’‘ Pay attention! This video explains the difference between Authentication (proving who you are) and Authorization (what you're allowed to do). In this lesson, we're building the front doorβ€”that's Authentication. Next, you'll learn how to build the special rooms insideβ€”that's Authorization!

Meet the Digital Bouncer πŸ€–

Before we write any code, let's play a little game. Imagine your app is an exclusive club. Not just anyone can get in! You need an Authentication system β€” a fancy word for a bouncer that checks who is allowed inside. In the developer world, this 'bouncer' is called an authentication service, and the process of checking your password against the guest list is called verifying credentials.

The Digital Bouncer Game!

An astronaut, a wizard, and a T-Rex walk up to a club. Click on each one to see if Pan the Bouncer lets them in.

πŸ‘©β€πŸš€
"Password123"
πŸ§™β€β™‚οΈ
"Abracadabra"
πŸ¦–
(no password)
πŸ€–
Pan the Bouncer

See? The bouncer has a list (the database) and only lets in the person with the matching password. That's exactly how login screens work! Here's the whole process:

πŸ‘€ ➑️ ⌨️ ➑️ πŸ€– ❓ ➑️ βœ… or ❌

You type your password, Pan checks the list, and you're either in or out!

🧠 Concept Checkpoint

In our "Digital Bouncer" game, what does the bouncer check to see if you can get in?

A) Your cool shoes
B) Your password
C) Your favorite color

πŸ›‘οΈ Safety Check: The Secret Handshake Rule

Before you build a place for secrets, you need to know how to keep them safe! Your password is like a secret handshake. Don't share it with anyone! Why? Because your data is important. When an app asks for permission to use your location or camera, it's asking to know something about you. Always ask a parent before granting permissions you don't understand.

  • πŸ’ͺ What makes a strong password? A mix of letters (upper and lower case!), numbers, and symbols. "P@s$w0rd!" is way stronger than "password".
  • 🚫 Why shouldn't you reuse passwords? If a snooper figures out your password for one app, they could try it everywhere! Use a unique one for every important account.
  • πŸ•ΉοΈ Pan's Rule: We're going to build a fun diary app, but NEVER store real, super-personal secrets or passwords in apps you build for practice. Think of it like a superhero's training simulation!

Let's Build: Your Top-Secret Diary App πŸ“”

Time to build the digital door and lock for your own app. We'll use a powerful tool called Firebase, which has a pre-built, super-secure "Digital Bouncer" service we can hire.

1

Step 1: The Clubhouse Doors (HTML)

First, we need a sign-up form. This is the door where new people can ask to be put on the guest list. Add this HTML to your project.

<!-- Your sign-up form -->
<h3>Create Your Secret Diary Account</h3>
<input type="email" id="email" placeholder="Your Email">
<input type="password" id="password" placeholder="Choose a Strong Password">
<button id="signUpBtn">Sign Up</button>

πŸ§ͺ Try it in the Simulator!

Setting up Firebase takes a few steps. Before you do that, let's see what the code *does* in a simulation. Type a fake email and password below and see the 'developer console' output!

2

Step 2: Hiring the Bouncer (Firebase)

Now, we need to connect our app to Firebase Authentication.

πŸ‘¨β€πŸ‘©β€πŸ‘§ Hey, grab a parent for this part!

Setting up a developer tool like Firebase is a great first project to do together. You'll need an account, which requires parental permission. Go to firebase.google.com, create a new project, and enable "Email/Password" authentication in the "Authentication" section.

Firebase will give you a special set of configuration keys. You'll add these to your JavaScript file to connect your app to your new Firebase project.

3

Step 3: Giving the Bouncer the Guest List (JS)

This is the magic! First, let's hook up our button and tell Firebase to create a new user. This is the "happy path" β€” what happens when everything goes right!

// Get the authentication service and your HTML elements
const auth = firebase.auth();
const signUpBtn = document.getElementById('signUpBtn');
const emailInput = document.getElementById('email');
const passwordInput = document.getElementById('password');

// Listen for a click on the sign-up button
signUpBtn.addEventListener('click', () => {
  const email = emailInput.value;
  const password = passwordInput.value;

  // Tell Firebase to create a new user!
  auth.createUserWithEmailAndPassword(email, password)
    .then((userCredential) => {
      // Hooray! You're on the list!
      console.log('Successfully signed up!', userCredential.user);
      alert('Welcome to the club!');
    });
});

🧠 Pro Tip: What's a `userCredential`?

See that `userCredential` thing? When a user signs up, Firebase sends back a treasure chest of info about them, including their unique User ID (`uid`). This ID is like their permanent VIP membership number. In the next lesson, we'll use that ID to make sure only *they* can read *their* diary entries!

✨ Level Up: Handling Errors

What if something goes wrong? A pro developer's app doesn't just crash; it gives helpful feedback! We can "catch" errors using a block called .catch(). Let's add it to our code.

// ... same code as before ...
auth.createUserWithEmailAndPassword(email, password)
    .then((userCredential) => {
      // Hooray! You're on the list!
      console.log('Successfully signed up!', userCredential.user);
      alert('Welcome to the club!');
    })
    .catch((error) => {
      // Uh oh, something went wrong.
      console.error('Error signing up:', error.code, error.message);
      
      // Give the user a more helpful error!
      if (error.code === 'auth/email-already-in-use') {
        alert('Looks like that email already has an account! Try logging in instead.');
      } else if (error.code === 'auth/weak-password') {
        alert('This password is too weak! It needs to be at least 6 characters long.');
      } else {
        alert('Oops! Something went wrong: ' + error.message);
      }
    });

Notice how we can check `error.code` to give the user a much more helpful message? That's what pros do!

Your Turn: The VIP Section πŸ‘‘

Signing up is great, but what about returning members? Your challenge is to add a "Log In" button. It's very similar, but uses a different function.

Hint: The best developers know how to find answers! Try searching the Official Firebase Docs for 'sign in with email and password'.

Stuck? Get a Hint! πŸ•΅οΈ

The function you need is signInWithEmailAndPassword(auth, email, password). It works just like the sign-up function, using .then() for success and .catch() for errors!

🧠 What's a Token? Your All-Access Pass 🎟️

When you log in, Firebase gives your app a secret, invisible stamp on its digital hand. You can't see it, but the bouncer (the server) has a special blacklight. Every time your app wants to do something secret, it shows the bouncer its stamp, and the bouncer says 'Yep, you're a real member, go ahead!' This is why you don't have to type your password every single time!

This special stamp is called an authentication token. In the professional world, these tokens are often called JWTs (JSON Web Tokens). They're the standard 'digital wristband' used to secure millions of websites and apps!

πŸš€ Advanced Challenge: Add Google Sign-In!

Pro apps don't just use email and password. They let you sign in with Google, Apple, or other accounts. Firebase makes this easy! Your mission: figure out how to add a "Sign in with Google" button to your app.

πŸš€ Show me the launch code!

First, you need a button in your HTML like <button id="googleSignInBtn">Sign In with Google</button>. Then, use this JavaScript to power it up!

// Import the necessary functions at the top of your script
import { GoogleAuthProvider, signInWithPopup } from "firebase/auth";

const provider = new GoogleAuthProvider();
const googleBtn = document.getElementById('googleSignInBtn');

googleBtn.addEventListener('click', () => {
  signInWithPopup(auth, provider)
    .then((result) => {
      console.log("Signed in with Google!", result.user);
      alert("Welcome, " + result.user.displayName);
    }).catch((error) => {
      console.error("Google sign-in error", error);
    });
});

Brain Fuel ⚑ What Else Can You Build?

You've just learned one of the most important skills in app development! You can use this exact same authentication logic to build:

  • A high-score leaderboard for a game you made.
  • A "members-only" section of a website for your friends.
  • A personalized profile page where users can set their own color theme or avatar.

Authentication is the key that unlocks personalization. Go build something awesome!

πŸš€ What's Next: The VIP Room Key

You've built the front door for your clubhouse. But how do you stop people from reading each other's diaries? To do that, you need to connect each diary entry to a specific user ID.

This next step is called Authorizationβ€”and it's how you'll make sure only the right person has the key to see their own secrets. Get ready to build your app's security rules in the next module!

πŸ“š Learn More

πŸ‘¨β€πŸ‘©β€πŸ‘§ Parent Corner

What is Firebase? Firebase is a toolkit from Google that helps developers build apps faster and more securely. We're using its "Authentication" feature, which is an industry-standard way to manage user logins. It's the same powerful (and safe) technology used by thousands of popular apps.

Conversation Starter: Ask your child to explain the "Digital Bouncer" analogy to you. See if they can describe why it's important not to store passwords as plain text, and why they should never use the same password on multiple websites.