Skip to content

445 446 jwt auth course management#565

Merged
Hexstar-labs merged 3 commits into
BrainTease:mainfrom
OZILSOLAR:445-446-jwt-auth-course-management
May 29, 2026
Merged

445 446 jwt auth course management#565
Hexstar-labs merged 3 commits into
BrainTease:mainfrom
OZILSOLAR:445-446-jwt-auth-course-management

Conversation

@OZILSOLAR
Copy link
Copy Markdown
Contributor

[Backend] JWT Authentication & Course Management API

Overview

This PR implements JWT-based authentication with refresh tokens and a complete course management REST API with role-based access control. Both features are production-ready with comprehensive error handling, validation, and security measures.

Issues Resolved

Closes #445
Closes #446

Changes Implemented

Issue #445: JWT Authentication Middleware

JWT Strategy & Token Management

  • JWT Strategy (src/auth/jwt.strategy.ts): Passport JWT strategy with Bearer token extraction and token blacklist validation
  • Token Generation (src/auth/auth.service.ts):
    • Access tokens: 15-minute expiration
    • Refresh tokens: 7-day expiration with secure hashing
    • issueTokenPair() method for atomic token generation

Refresh Token Rotation

  • Implemented in refresh() method: revokes old token before issuing new pair
  • Prevents token reuse and enhances security
  • Stored in database with revocation status tracking

Authentication Guards & Authorization

  • JwtAuthGuard (src/auth/jwt-auth.guard.ts): Protects routes requiring authentication
  • RolesGuard (src/auth/roles.guard.ts): Enforces role-based access control
  • @roles() Decorator (src/auth/roles.decorator.ts): Declarative role specification on routes
  • Supports roles: admin, instructor, student

Token Blacklisting System

  • TokenBlacklistService (src/auth/token-blacklist.service.ts):
    • blacklistToken(): Adds tokens to cache (Redis) and database for persistence
    • isTokenBlacklisted(): Fast lookup with cache-first strategy
    • cleanupExpiredTokens(): Scheduled cleanup of expired entries
  • Used in logout and JWT validation to prevent token reuse
  • Hybrid cache + database approach for reliability and performance

Rate Limiting for Auth Endpoints

  • @Throttle() decorators on all auth endpoints (register, login, refresh, etc.)
  • UserRateLimitService (src/rate-limit/user-rate-limit.service.ts):
    • Role-based rate limits: admin (10k/min), instructor (5k/min), student (1k/min), guest (100/min)
    • Trusted client whitelist support
  • UserRateLimitGuard applied globally in AppModule

Additional Auth Features

  • MFA (TOTP + backup codes) support
  • API key generation and revocation
  • Stellar wallet integration (SEP-0010)
  • Password reset with token expiration
  • Email verification workflow
  • Audit logging for all auth actions

Issue #446: Course Management API

REST Endpoints

All endpoints follow RESTful conventions with proper HTTP methods and status codes:

  • GET /v1/courses - List all published courses

    • Pagination: page (default: 1), limit (default: 20)
    • Filtering: search (title/description ILIKE), level (beginner/intermediate/advanced)
    • Returns: paginated results with total count and average ratings
    • No authentication required
  • GET /v1/courses/:id - Retrieve single course

    • Returns full course details
    • 404 if not found
    • No authentication required
  • POST /v1/courses - Create new course

    • Requires: JWT authentication + admin/instructor role
    • Input validation with CreateCourseDto
    • HTML sanitization on title and description
    • Returns: 201 with created course
    • Forbidden (403) if insufficient permissions
  • PATCH /v1/courses/:id - Update course

    • Requires: JWT authentication + admin/instructor role
    • Input validation with UpdateCourseDto
    • HTML sanitization
    • Returns: 200 with updated course
    • 404 if course not found
  • DELETE /v1/courses/:id - Delete course

    • Requires: JWT authentication + admin/instructor role
    • Soft delete (marks isDeleted = true)
    • Returns: 200 with deleted course
    • 404 if course not found

Course Management Features

  • Pagination & Filtering (src/courses/dto/course-query.dto.ts):

    • Type-safe query parameters with class-validator
    • Automatic type coercion and sanitization
    • Default values for page and limit
  • Input Validation (src/courses/dto/):

    • CreateCourseDto: title (min 3 chars), description (min 10 chars), level, duration, KYC requirement
    • UpdateCourseDto: all fields optional for partial updates
    • HTML sanitization using StripHtmlSanitizer
  • Error Handling:

    • 400: Invalid input or business logic violations
    • 401: Missing or invalid JWT token
    • 403: Insufficient permissions (non-admin/instructor)
    • 404: Course not found
    • Consistent error response format
  • Performance Optimizations:

    • Cache invalidation on create/update/delete
    • Search service integration for full-text search
    • Average rating calculation with SQL aggregation
    • Soft deletes to preserve data integrity
  • Course Scheduling (bonus):

    • POST /v1/courses/:id/schedule - Schedule course for future publication
    • POST /v1/courses/:id/publish - Immediately publish course
    • Timezone-aware scheduling with Intl API

Data Models

  • Course Entity (src/courses/course.entity.ts):
    • Status enum: DRAFT, SCHEDULED, PUBLISHED
    • Relationships: instructor (User), modules (CourseModule), reviews (Review)
    • Timestamps: createdAt, publishedAt, scheduledAt
    • Metadata: level, duration, KYC requirement

Additional Changes

Module Imports Fix

  • Added missing imports to src/app.module.ts:
    • RemindersModule
    • CertificatesModule
    • PayoutsModule
  • Ensures all modules are properly registered in the application

Technical Details

Security Measures

  • JWT tokens signed with configurable secret
  • Refresh tokens hashed with SHA-256 before storage
  • Token blacklist prevents replay attacks
  • Rate limiting prevents brute force attacks
  • HTML sanitization prevents XSS attacks
  • Role-based access control enforces authorization
  • Audit logging tracks all authentication events

Database Schema

  • token_blacklist table: stores revoked tokens with expiration
  • refresh_tokens table: stores refresh token hashes with revocation status
  • courses table: enhanced with status enum and scheduling fields
  • Indexes on frequently queried columns for performance

Caching Strategy

  • Redis cache for token blacklist (fast lookup)
  • Database persistence for reliability
  • Cache invalidation on course updates
  • TTL-based automatic cleanup

Testing Considerations

  • Auth endpoints have rate limiting (5 requests/min for login/register)
  • Course endpoints require valid JWT for write operations
  • Role validation enforced on protected routes
  • Input validation prevents malformed requests

API Documentation

  • Swagger/OpenAPI docs auto-generated from decorators
  • Available at: GET /api/docs
  • All endpoints documented with request/response schemas
  • Example values provided for common use cases

Deployment Notes

  • Requires Redis for caching and rate limiting
  • PostgreSQL for persistent storage
  • JWT_SECRET environment variable must be set
  • Refresh token TTL: 7 days (configurable)
  • Access token TTL: 15 minutes (configurable)

Breaking Changes

None. All changes are additive and backward compatible.

Migration Steps

  1. No database migrations required (uses auto-sync in dev)
  2. Ensure Redis is running for cache/rate limiting
  3. Set JWT_SECRET in environment variables
  4. Restart backend service

Verification

  • ✅ JWT authentication with token validation
  • ✅ Refresh token rotation prevents token reuse
  • ✅ Token blacklisting on logout
  • ✅ Rate limiting on auth endpoints
  • ✅ Course CRUD operations with role-based access
  • ✅ Pagination and filtering on course list
  • ✅ Input validation and HTML sanitization
  • ✅ Error handling with proper HTTP status codes
  • ✅ Audit logging for security events
  • ✅ Module imports properly configured

Copy this PR message and paste it when creating the pull request on
GitHub. The message covers:

  • ✅ All changes implemented
  • ✅ Both issue numbers with Closes statements
  • ✅ Comprehensive technical details
  • ✅ Security measures
  • ✅ API documentation
  • ✅ Deployment notes
  • ✅ Verification checklist

OZILSOLAR added 2 commits May 28, 2026 20:56
- Add TokenBlacklist entity for persistent token revocation
- Create TokenBlacklistService with cache-backed lookup
- Update JwtStrategy to check blacklist on token validation
- Enhance logout endpoint to blacklist access tokens
- Add token expiration cleanup capability
- Supports both cache and database for fast and persistent lookups
@drips-wave
Copy link
Copy Markdown

drips-wave Bot commented May 28, 2026

@OZILSOLAR 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

@Hexstar-labs Hexstar-labs merged commit 7732057 into BrainTease:main May 29, 2026
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] Build course management API [Backend] Implement JWT authentication middleware

2 participants