1. Set Up User Authentication Foundation

Prepare your API for user authentication:

  1. Add a password field to your users table using ALTER TABLE.
  2. Install bcrypt and jsonwebtoken packages with their TypeScript types.
  3. Update your User interface and create a UserResponse interface.
  4. Set up JWT utilities and add JWT_SECRET to your environment variables.

2. Build Authentication Endpoints

Create user registration and login functionality:

  1. Create routes/auth.ts with registration and login endpoints.
  2. Implement secure password hashing using bcrypt in the registration endpoint.
  3. Use your Zod validation schemas from the previous lesson for input validation.
  4. Generate and return JWT tokens on successful login.

3. Protect Routes with JWT Authentication

Add authentication and authorisation to your existing routes:

  1. Create JWT authentication middleware to verify tokens.
  2. Add authentication middleware to protect routes and authorisation checks so users can only access/modify their own data.
  3. Test the complete authentication flow with valid/invalid tokens and different user access attempts.
Tags: