Signup Rules
Part of the Auth and Security section of Coddy's Node.js journey. Lesson 3 of 17.
Right now anyone can sign up twice with the same name, or with the password 1. Signup has to check what it receives before it stores anything.
Two status codes say what went wrong. 400 Bad Request means the request itself is not acceptable, like a password that is too short. 409 Conflict means it clashes with data you already have, like a name that is taken.
Names also need one spelling. Ada and ada look like one person to everyone reading them, so lowercase a name before you store it and before you look it up:
const email = String(req.body.email ?? '').trim().toLowerCase();
if (await subscribers.findOne({ email })) {
return res.status(409).json({ error: 'Already subscribed' });
}Challenge
EasyPOST /signupanswers 400{ error }without a username or with a password under 8 characters.- It answers 409
{ error }for a taken username. - Usernames are stored lowercase, and
POST /loginaccepts any case.
Sign up Ada, then ada, then log in as ADA. Try the password 1234 too.
Try it yourself
import express from 'express';
import { users } from './db.js';
import { hashPassword, verifyPassword } from './passwords.js';
const app = express();
app.use(express.json());
app.post('/signup', async (req, res) => {
const { username, password } = req.body;
await users.insertOne({ username, passwordHash: await hashPassword(password) });
res.status(201).json({ username });
});
app.post('/login', async (req, res) => {
const { username, password } = req.body;
const user = await users.findOne({ username });
if (!user || !(await verifyPassword(password, user.passwordHash))) {
return res.status(401).json({ error: 'Wrong username or password' });
}
res.json({ username: user.username });
});
// Shows what signup stored. For learning only: a real app never has this route.
app.get('/debug/users/:username', async (req, res) => {
const user = await users.findOne({ username: req.params.username });
res.json(user ? { username: user.username, passwordHash: user.passwordHash } : null);
});
app.listen(3000, () => {
console.log('Vault is running on port 3000');
});
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Auth and Security
2Sessions and Cookies
Remembering with CookiesLogin Sessions