Skip to content

feat: implement user authentication system with login routes, JWT, va…#71

Open
ABEEGOLD wants to merge 1 commit into
SwiftChainn:mainfrom
ABEEGOLD:Implement-User-Login-API
Open

feat: implement user authentication system with login routes, JWT, va…#71
ABEEGOLD wants to merge 1 commit into
SwiftChainn:mainfrom
ABEEGOLD:Implement-User-Login-API

Conversation

@ABEEGOLD

Copy link
Copy Markdown

Closes #10

Summary

Implemented POST /api/v1/auth/login endpoint to authenticate users and issue JWT tokens. The implementation follows the strict Controller → Service → Model layered architecture with production-ready error handling, input validation, and comprehensive integration tests.

What This PR Does

  • Authenticates users by verifying email/password credentials against MongoDB
  • Generates and returns a signed JWT token containing userId and role
  • Validates request input using Zod v4 schemas
  • Returns sanitized user data (password is never exposed in responses)
  • Handles error cases with appropriate HTTP status codes

🏗 Architecture

Client Request
    ↓
Validate Middleware (Zod v4)
    ↓
Auth Controller (authController.ts)
    ↓
Auth Service (authService.ts)
    ↓
User Model (User.ts) ←→ MongoDB
    ↓
JWT (jsonwebtoken)
    ↓
Response

Files Changed

New Files

File Layer Purpose
src/config/env.ts Config Type-safe environment variable loader
src/interfaces/IUser.ts Types User interface, role enum, auth response types
src/models/User.ts Model Mongoose User schema with bcrypt hashing
src/services/authService.ts Service Login business logic & JWT generation
src/controllers/authController.ts Controller Login request handler
src/validators/authValidator.ts Validation Zod v4 login schema
src/middleware/validate.ts Middleware Generic Zod validation middleware
src/utils/AppError.ts Utility Custom error class with statusCode
src/utils/asyncHandler.ts Utility Async route handler wrapper
src/routes/authRoutes.ts Routing Auth route definitions
tests/auth.test.ts Testing 14 integration tests

Modified Files

File Change
src/routes/index.ts Wired auth routes under /auth prefix
src/middleware/errorHandler.ts Enhanced to handle AppError, ZodError, Mongoose & JWT errors
package.json Added zod@4.4.3 dependency

API Endpoint

POST /api/v1/auth/login

Request Body:

{
  "email": "user@example.com",
  "password": "SecurePass123!"
}

Success Response (200 OK):

{
  "status": "success",
  "message": "Login successful",
  "data": {
    "user": {
      "id": "667b...",
      "email": "user@example.com",
      "firstName": "John",
      "lastName": "Doe",
      "role": "user"
    },
    "token": "eyJhbGciOiJIUzI1NiIs..."
  }
}

Error Responses:

Status Scenario
400 Bad Request Invalid email format, missing fields
401 Unauthorized Wrong credentials, deactivated account

Security Measures

  • Password never returned in any API response (select: false on schema + toJSON transform)
  • Generic error messages for wrong email/password — prevents email enumeration attacks
  • bcrypt password hashing with configurable salt rounds
  • Account status check — deactivated accounts are rejected
  • Zod validation — malformed requests rejected before hitting the database

Tests

All 15 tests passing using mongodb-memory-server for real MongoDB integration testing (no mock data).

PASS tests/health.test.ts
PASS tests/auth.test.ts

Test Suites: 2 passed, 2 total
Tests:       15 passed, 15 total

Test Coverage

Category Test Case Status
Success Valid credentials → 200 + JWT
Success Valid JWT structure (3-part)
Success Case-insensitive email
Success Driver role login
Auth Failure Non-existent email → 401
Auth Failure Wrong password → 401
Auth Failure Deactivated account → 401
Auth Failure Email enumeration protection
Validation Empty body → 400
Validation Invalid email format → 400
Validation Missing password → 400
Validation Missing email → 400
Versioning /api/v1/auth/login → 200
Versioning /auth/login (unversioned) → 404

📸 Proof of Work

Attach your Postman/Browser screenshot here showing successful login response

How to Test Locally

# 1. Install dependencies
pnpm install

# 2. Set up environment
cp .env.example .env
# Edit .env with your MongoDB URI and JWT_SECRET

# 3. Run tests
JWT_SECRET=your-secret pnpm test

# 4. Run dev server
pnpm run dev

# 5. Test with curl
curl -X POST http://localhost:3000/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email": "user@example.com", "password": "SecurePass123!"}'

@drips-wave

drips-wave Bot commented Jun 29, 2026

Copy link
Copy Markdown

@ABEEGOLD Great news! 🎉 Based on an automated assessment of this PR, the linked Wave issue(s) no longer count against your application limits.

You can now already apply to more issues while waiting for a review of this PR. Keep up the great work! 🚀

Learn more about application limits

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Backend: Implement User Login API endpoint and JWT generation

1 participant