Start learning free

LESSON 85 OF 173 · BACKEND: USERS AND SECURITY

Sign Up in Java

Practice

So far only the owner and the staff have keys, and they are written into the code in API_KEYS. Customers need accounts of their own: they sign up with an email and a password, and the shop keeps each one as a row in a new table, users.

A table is created once with CREATE TABLE IF NOT EXISTS, so the shop can start again and again. A column marked UNIQUE never holds the same value twice. To know whether a value is taken, look for it with a SELECT: db.queryForList gives the matching rows, and an empty list when nothing matches. Here is the same idea for a made-up coupons table:

db.execute("CREATE TABLE IF NOT EXISTS coupons (id INTEGER PRIMARY KEY, code TEXT NOT NULL UNIQUE)");
List<Map<String, Object>> rows = db.queryForList("SELECT id FROM coupons WHERE code = ?", "SPRING10");
if (rows.isEmpty()) {
    System.out.println("No such coupon");
}

An email that is already registered gets 409 Conflict: the request clashes with what the server already has. A new user gets 201 Created with their id and email. The answer never sends the password back.

These are the requests your code must answer:

POST /register  {"email": "ana@example.com", "password": "secret123"}  →  201  {"email": "ana@example.com", "id": 1}
POST /register  {"email": "ana@example.com", "password": "hello456"}   →  409  {"error": "Email already registered"}
POST /register  {"email": "ben@example.com", "password": "secret123"}  →  201  {"email": "ben@example.com", "id": 2}
POST /register  {"email": "ben@example.com", "password": "other789"}   →  409  {"error": "Email already registered"}

Your task: in the constructor, create the users table, then add POST /register to ShopController. When the email is taken, answer {"error": "Email already registered"} with 409; otherwise save the user and answer 201 with its id and email.


Assignment
Follow the Coding Tutorial to create the users table and the sign-up route.


Hint
Look for the email before the INSERT. End the INSERT with RETURNING id and run it with db.queryForObject(…, Integer.class, …), like in addProduct: that gives you the id the database chose for the new row.


STEP 1 OF 8
    Ctrl + Enter to check

    Auth Register in Java

    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free