POST /v1/auth/*: signup, login and refresh

You build POST /v1/auth/* to register accounts, exchange passwords for token pairs, and rotate refresh tokens. Each refresh token works once.

Ticket

Add the users table through a Database migration and build POST /v1/auth/signup, POST /v1/auth/login, and POST /v1/auth/refresh. Signup stores a bcrypt password hash and returns a signed JWT Access token with an opaque Refresh token. Login verifies the password, and refresh replaces the refresh token.

The app built in Week 4 needs these routes to authenticate users. W3B2 uses the access token to authenticate requests through bearer auth middleware.

For example, a successful signup uses a request like:

json
{
  "email": "learner@example.test",
  "password": "correct horse battery staple"
}

It returns HTTP 201 with a token pair. The access token is a verifiable JWT, and the refresh token is a new opaque credential.

Endpoints

POST/v1/auth/signup

Create an account and log it in

Request body JSON
  • emailstringrequired
  • passwordstringrequired
  • role"customer" | "restaurant" | "rider"
  • restaurant_idinteger
Response 201
  • access_tokenstringrequired

    A JWT signed with HS256 and JWT_SECRET, carrying exp. Its other claims are yours to choose.

  • refresh_tokenstringrequired

    32 random bytes as 64 lowercase hex characters.

  • token_type"Bearer"required
  • expires_in900required
Response 400 Bad Request

invalid_bodyinvalid_parameter

Response 409

email_taken

POST/v1/auth/login

Exchange email and password for a token pair

Request body JSON
  • emailstringrequired
  • passwordstringrequired
Response 200 OK
  • access_tokenstringrequired

    A JWT signed with HS256 and JWT_SECRET, carrying exp. Its other claims are yours to choose.

  • refresh_tokenstringrequired

    32 random bytes as 64 lowercase hex characters.

  • token_type"Bearer"required
  • expires_in900required
Response 400 Bad Request

invalid_body

Response 401

invalid_credentials

POST/v1/auth/refresh

Rotate a refresh token

Request body JSON
  • refresh_tokenstringrequired
Response 200 OK
  • access_tokenstringrequired

    A JWT signed with HS256 and JWT_SECRET, carrying exp. Its other claims are yours to choose.

  • refresh_tokenstringrequired

    32 random bytes as 64 lowercase hex characters.

  • token_type"Bearer"required
  • expires_in900required
Response 400 Bad Request

invalid_body

Response 401

invalid_refresh_token

Acceptance criteria

  • Signup with a valid email and password returns HTTP 201. The access token is a verifiable HS256 JWT signed with JWT_SECRET and expiring about 15 minutes ahead. The refresh token contains 64 lowercase hexadecimal characters. token_type is Bearer and expires_in is 900.
  • The new user's users.password_hash matches the bcrypt hash format and has a cost of at least 10.
  • Signup trims surrounding whitespace and lowercases the email before storing it. Exactly one user row exists under the normalized email, and login using the uppercase form returns HTTP 200 with a valid token pair.
  • A second signup using the same email in uppercase returns HTTP 409 with error email_taken.
  • Signup with email not-an-email or Bob <bob@test.local> returns HTTP 400 with error invalid_parameter and field email. An empty password or a password consisting of 73 a characters returns HTTP 400 with error invalid_parameter and field password. Role admin returns HTTP 400 with error invalid_parameter and field role. Role restaurant without restaurant_id, or role customer with restaurant_id set to 1, returns HTTP 400 with error invalid_parameter and field restaurant_id.
  • Sending the raw body email=a@b.c to signup returns HTTP 400 with error invalid_body.
  • Login with a registered email and the correct password returns HTTP 200 with a valid token pair. The response contains a verifiable access token, a non-empty refresh token, token_type set to Bearer, and expires_in set to 900. Sending that refresh token to the refresh endpoint returns HTTP 200 with another valid token pair.
  • Login with password wrong password returns HTTP 401 with error invalid_credentials for both a registered email and an unknown email.
  • Refreshing a valid token returns HTTP 200 with a valid token pair whose refresh token differs from the original. The replacement token also works for another refresh request, returning HTTP 200. Reusing the original token or submitting an unknown token made from 32 repetitions of ab returns HTTP 401 with error invalid_refresh_token.

Constraints

  • Passwords must contain between 1 and 72 bytes.
  • Stored bcrypt hashes must have a cost of at least 10.
  • Access tokens must be signed with HS256 using JWT_SECRET and expire about 15 minutes after issue.
  • Refresh tokens must contain 64 lowercase hexadecimal characters.

Design direction

A sensible layout is to keep authentication concerns in an internal/auth area. Separate password hashing, access-token issuing, refresh-token storage, and HTTP handlers. Keep the users schema change in db/migrations. Handlers should validate requests, coordinate these responsibilities, and return the API contract's responses. Any layout that meets the contract passes.

Think about these trade-offs:

  • Normalize email before both storing it and looking it up. Use a MySQL unique constraint to handle duplicate signups, including concurrent requests.
  • Consider a dummy bcrypt hash for unknown email addresses. It makes the password-verification path more comparable for unknown accounts and incorrect passwords.
  • Keep the access token stateless and the refresh token as an opaque credential stored in Redis. Redis TTLs limit how long refresh credentials remain usable.
  • Refresh requires a one-use operation. An atomic consume avoids the race in which two requests both check the same token before either deletes it. MySQL and Redis do not share a transaction, so consider what happens when one operation succeeds and the next fails.

How to check your work

Run these commands from the repository:

bash
cd backend && make up
cd backend && make test W=W3B1

Read the first failing assertion in the test output. It identifies the request, response, or stored value that differs from the expected behaviour. Fix that failure before investigating later assertions.

Finished Exercise 3.3?

Implementation

Run locally

Write the code in your editor inside zomato-prep, then work through this list.

  1. Create and reverse the users table migration.
  2. Store passwords as bcrypt hashes.
  3. Normalize email addresses and reject duplicate accounts.
  4. Implement signup and login token responses.
  5. Return consistent errors for invalid credentials and input.
  6. Rotate refresh tokens and reject reused or unknown tokens.

Commands

terminal
cd backend && make up
terminal
cd backend && make test W=W3B1

Tests

  1. Signup returns HTTP 201 with a verifiable token pair containing the required token fields and expiry.

    POST/v1/auth/signup
    Body raw JSON
    {
      "email": "asha@test.local",
      "password": "correct horse battery staple"
    }
    Response 201
    {
      "access_token": "eyJhbGciOiJIUzI1NiIs…",
      "refresh_token": "9f2c…(64 hex characters)",
      "token_type": "Bearer",
      "expires_in": 900
    }

    Input POST /v1/auth/signup with a unique email and password correct horse battery staple.

    Expected HTTP 201; an HS256 JWT signed with JWT_SECRET expiring about 15 minutes ahead; a 64-character lowercase hexadecimal refresh token; token_type Bearer; expires_in 900.

    TestW3B1_SignupReturns201WithAVerifiableTokenPair in backend/e2e/w3_auth_test.go