Your App's Superpowers: User Authentication
What if your app could remember a player's high score, greet them by name, or save their favorite settings? That's a real superpower! To do it, your app first needs to know *who* the user is. Today, you'll build the digital lock and key for a Top-Secret Diary app! Ready to become the bouncer of your own awesome creation? Let's go! π
Let's Build: Your Top-Secret Diary App π
We're going to build an app that needs to keep secrets safe. To do that, we need a way to let the right person in and keep everyone else out. This process is called authentication. Itβs the digital lock on your appβs front door. Let's start by planning how our app's security will work.
Step 1: Plan the Security - The Bouncer Game
Before we write a single line of code, let's think like a security expert by playing a game. Imagine your app is an exclusive club. You're the head bouncer! Your job is to check who is on the guest list and decide who gets in.
The Bouncer Challenge!
Drag each character to the VIP Club or the Try Again area. Pan the Bouncer is watching!
Club Guest List: Astronaut π©βπ & Robot π€
VIP Club β
Try Again β
π‘οΈ Safety Check: Your App's Superpowers & Responsibilities
When an app asks for your Location, Camera, or Microphone, it's asking for a superpower! Before you grant it, always ask: "Does this app *really* need this power to do its job?"
- A map app needs your location to give directions. That makes sense! π
- Does a simple calculator app need your location? Nope! That's a red flag. π€¨
- Your Password Power: A strong password is your own personal force field. Make it a long mix of letters, numbers, and symbols. "MyD0gSp@rky!" is way stronger than "password123".
- Pan's Rule: We're building 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!
Step 2: Build the Digital Door
Okay, planning is done! Time to build the doors for our diary app. We need a way for users to sign up, log in, and (if they are logged in) log out.
The Clubhouse Doors (HTML)
First, we need the forms. This is where users will type their email and password. We'll add some `div` containers so we can show and hide the right forms later.
<!-- This part shows when you're logged OUT -->
<div id="auth-container">
<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>
<button id="logInBtn">Log In</button>
</div>
<!-- This part shows when you're logged IN -->
<div id="diary-container" style="display:none;">
<h3>Welcome to your Secret Diary!</h3>
<p>Only you can see this message!</p>
<button id="logOutBtn">Log Out</button>
</div>
Hiring the Bouncer (Firebase)
We'll use a powerful tool called Firebase. It has a pre-built, super-secure "Digital Bouncer" service we can hire for free.
π¨βπ©βπ§ 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 a Google account, which requires parental permission. For a walkthrough, check out the official Firebase guide. Once your project is set up, here's how to turn on the bouncer:
Step 3: Test Your Lock in the Simulator
Before we write the real code, let's test the complete sign up, log in, and log out flow in a simulation. It's like a training mission for our app!
π§ͺ Authentication Flow Simulator!
Type a fake email and password below to create a Digital ID. Then try logging in and out!
Step 4: Giving the Bouncer Instructions (JavaScript)
This is the magic! Let's tell our JavaScript how to use Firebase to handle the full sign-up, log-in, and log-out cycle. The code can look like a lot, so we've hidden it in these handy dropdowns for curious explorers. Click to see the full JavaScript code! π΅οΈββοΈ
Part 1: How to Sign a User UP π
This is for when a new user creates an account. We tell Firebase to `createUserWithEmailAndPassword`. It's like telling the bouncer, "Add this person to the guest list!"
// First, import the functions you need from the Firebase SDK
import { getAuth, createUserWithEmailAndPassword } from "firebase/auth";
// ... your Firebase setup code ...
const auth = getAuth(app);
const signUpBtn = document.getElementById('signUpBtn');
const emailInput = document.getElementById('email');
const passwordInput = document.getElementById('password');
signUpBtn.addEventListener('click', () => {
const email = emailInput.value;
const password = passwordInput.value;
createUserWithEmailAndPassword(auth, 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);
alert('Oops! ' + error.message);
});
});
Part 2: How to Log a User IN β‘οΈ
Once a user is on the guest list, they can log in. We use `signInWithEmailAndPassword` to check their credentials.
// You'll also need to import this function
import { signInWithEmailAndPassword } from "firebase/auth";
const logInBtn = document.getElementById('logInBtn');
logInBtn.addEventListener('click', () => {
const email = emailInput.value;
const password = passwordInput.value;
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
console.log('Successfully logged in!', userCredential.user);
})
.catch((error) => {
console.error('Error logging in:', error.code);
alert('Wrong email or password, try again!');
});
});
Part 3: How to Log a User OUT πͺ
This one's easy! The `signOut` function tells Firebase to log the current user out.
// You'll also need to import this function
import { signOut } from "firebase/auth";
const logOutBtn = document.getElementById('logOutBtn');
logOutBtn.addEventListener('click', () => {
signOut(auth).then(() => {
console.log('User signed out.');
}).catch((error) => {
console.error('Sign out error', error);
});
});
Part 4: The Manager - Who's Here? π€
This is the most important part! How does our app know if someone is logged in or out? We use `onAuthStateChanged`. It's like a manager who constantly watches the door. When someone logs in or out, it tells our code so we can show or hide the right parts of our page.
// You'll also need to import this function
import { onAuthStateChanged } from "firebase/auth";
const authContainer = document.getElementById('auth-container');
const diaryContainer = document.getElementById('diary-container');
onAuthStateChanged(auth, (user) => {
if (user) {
// User is signed in!
console.log('Manager sees user:', user.email);
authContainer.style.display = 'none';
diaryContainer.style.display = 'block';
} else {
// User is signed out.
console.log('Manager sees no user.');
authContainer.style.display = 'block';
diaryContainer.style.display = 'none';
}
});
π§ Deep Dive: Client vs. Server Security
Imagine you have a wristband to get into the club. That's the first check (on the "client," your app). But to get into the super-special VIP lounge, a *different* bouncer inside checks your wristband again! That's the "server" double-checking to stay extra safe.
Pro apps always double-check important things on the server. With Firebase, we can write Security Rules that the server enforces. Here's a rule that says "Only let a user write to their own diary." Even if a hacker tried to trick the app, the server's rule would stop them!
{
"rules": {
"diaries": {
"$uid": {
// Only the logged-in user with this ID can write here
".write": "auth.uid === $uid"
}
}
}
}
This is an advanced topic we'll explore in a future lesson, but now you know the secret to building truly secure apps!
β¨ Level Up: Passwordless Login
Typing passwords is a pain, right? Many pro apps let you log in with a Google, Apple, or GitHub account. This is called Social Authentication. It's often easier and more secure for users. Firebase makes this super easy to add to your app! It's a great next step once you've mastered email and password login. You can learn more at the official Firebase docs.
ποΈ What's a Token? Your All-Access Pass
When you log in, Firebase gives your app a secret, invisible stamp. Every time your app wants to do something private, like read a diary entry, it shows the server its stamp to prove it's a real member. This is why you don't have to type your password every single time!
This special stamp is called an authentication token. For our diary app, it holds a super important piece of info: your unique user ID (`uid`). That `uid` is your user's secret ID. Every time they save a new diary entry, we'll secretly stamp it with this ID. That's how we'll make sure only *they* can read their own secrets!
Your Turn: Become a Code Detective! π΅οΈββοΈ
Pro developers use tools to peek inside tokens to fix bugs. Let's try it! Copy the sample token below. Then, open jwt.io in a new tab and paste it into the "Encoded" box on the left. Can you find the `uid` in the decoded "PAYLOAD" data on the right? That's your unique ID!
The Complete Code Recipe π
Want to get this running on your own computer? Here is the full, copy-pasteable code for a working example. Remember to replace the Firebase config with your own!
π index.html
<!DOCTYPE html>
<html>
<head>
<title>Secret Diary</title>
</head>
<body>
<h1>My Top-Secret Diary App</h1>
<!-- Shows when logged OUT -->
<div id="auth-container">
<h3>Log In or Sign Up</h3>
<input type="email" id="email" placeholder="Email" />
<input type="password" id="password" placeholder="Password" />
<button id="signUpBtn">Sign Up</button>
<button id="logInBtn">Log In</button>
</div>
<!-- Shows when logged IN -->
<div id="diary-container" style="display:none;">
<h3>Welcome! Your secrets are safe.</h3>
<button id="logOutBtn">Log Out</button>
</div>
<script type="module" src="script.js"></script>
</body>
</html>
βοΈ script.js
// 1. Import functions from the Firebase SDK
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-app.js";
import {
getAuth,
createUserWithEmailAndPassword,
signInWithEmailAndPassword,
signOut,
onAuthStateChanged
} from "https://www.gstatic.com/firebasejs/9.15.0/firebase-auth.js";
// 2. Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_AUTH_DOMAIN",
projectId: "YOUR_PROJECT_ID",
// ...and so on
};
// 3. Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
// 4. Get references to our HTML elements
const emailInput = document.getElementById('email');
const passwordInput = document.getElementById('password');
const signUpBtn = document.getElementById('signUpBtn');
const logInBtn = document.getElementById('logInBtn');
const logOutBtn = document.getElementById('logOutBtn');
const authContainer = document.getElementById('auth-container');
const diaryContainer = document.getElementById('diary-container');
// 5. Add event listeners
signUpBtn.addEventListener('click', () => { /* ... sign up code ... */ });
logInBtn.addEventListener('click', () => { /* ... log in code ... */ });
logOutBtn.addEventListener('click', () => { /* ... log out code ... */ });
// 6. Set up the auth state manager
onAuthStateChanged(auth, user => {
if (user) {
authContainer.style.display = 'none';
diaryContainer.style.display = 'block';
} else {
authContainer.style.display = 'block';
diaryContainer.style.display = 'none';
}
});
π¨βπ©βπ§ 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 the difference between signing up, logging in, and logging out. The "Client vs. Server Security" deep dive is also a great chance to discuss why "double-checking" is so important for safety, both online and in the real world!