Skip to content

3urhan/auth-service

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

3 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ” Auth Service

Enterprise-grade secure authentication API supporting MySQL and MongoDB databases. Built with security best practices for production environments.

πŸš€ Features

Database Support

  • MySQL via Prisma ORM - Type-safe, structured database with migrations
  • MongoDB via Mongoose - Flexible document storage with validation
  • Switch between providers by changing DB_PROVIDER in .env

Security

  • βœ… Password hashing with bcryptjs (configurable salt rounds)
  • βœ… JWT authentication with access and refresh tokens
  • βœ… Account lockout after failed login attempts (prevents brute-force)
  • βœ… Rate limiting to prevent abuse
  • βœ… Helmet for secure HTTP headers
  • βœ… CORS configuration
  • βœ… XSS and SQL/NoSQL injection protection
  • βœ… Input validation with Joi

User Management

  • βœ… User registration and login
  • βœ… Password reset flow (forgot/reset)
  • βœ… Admin user management (list, view, update, delete)
  • βœ… Role-based access control (user, admin)

API Documentation

  • βœ… Swagger/OpenAPI documentation at /api-docs

Testing

  • βœ… Jest unit tests with coverage
  • βœ… Supertest for API integration tests

Professional

  • Winston logging with timestamps
  • Morgan HTTP request logging
  • Error handling middleware
  • Environment-based configuration

πŸ“ Project Structure

auth-service/
β”œβ”€β”€ prisma/
β”‚   └── schema.prisma        # MySQL database schema
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ config/
β”‚   β”‚   β”œβ”€β”€ config.js        # Environment configuration
β”‚   β”‚   └── db.js             # Database connection handler
β”‚   β”œβ”€β”€ controllers/
β”‚   β”‚   β”œβ”€β”€ authController.js # Authentication logic
β”‚   β”‚   └── adminController.js # Admin user management
β”‚   β”œβ”€β”€ middlewares/
β”‚   β”‚   β”œβ”€β”€ authMiddleware.js  # JWT verification
β”‚   β”‚   β”œβ”€β”€ adminMiddleware.js # Admin role check
β”‚   β”‚   β”œβ”€β”€ errorHandler.js    # Global error handling
β”‚   β”‚   β”œβ”€β”€ rateLimiter.js     # Rate limiting
β”‚   β”‚   └── validate.js         # Input validation
β”‚   β”œβ”€β”€ models/
β”‚   β”‚   β”œβ”€β”€ User.js            # Unified User model
β”‚   β”‚   └── Token.js            # Token storage model
β”‚   β”œβ”€β”€ routes/
β”‚   β”‚   └── authRoutes.js      # API routes + Swagger docs
β”‚   └── utils/
β”‚       β”œβ”€β”€ jwt.js             # JWT utilities
β”‚       └── logger.js          # Winston logger
β”œβ”€β”€ tests/
β”‚   β”œβ”€β”€ setup.js              # Jest test setup
β”‚   └── unit/
β”‚       β”œβ”€β”€ controllers/
β”‚       β”‚   └── authController.test.js
β”‚       β”œβ”€β”€ middlewares/
β”‚       β”‚   └── authMiddleware.test.js
β”‚       └── models/
β”‚           └── User.test.js
β”œβ”€β”€ .env                       # Environment variables
β”œβ”€β”€ .env.example               # Template for .env
β”œβ”€β”€ package.json
β”œβ”€β”€ server.js                  # Application entry point
└── My_Backend_Setup.txt       # Setup documentation

πŸ› οΈ Quick Start

1. Install Dependencies

npm install

2. Configure Environment

cp .env.example .env

Edit .env with your settings:

# Database Provider: mysql | mongodb
DB_PROVIDER=mysql

# MySQL Configuration
DATABASE_URL="mysql://root:password@localhost:3306/auth_service"

# MongoDB Configuration
MONGODB_URI="mongodb://localhost:27017/auth_service"

# JWT Secret (use a strong random string)
JWT_SECRET=your-super-secret-jwt-key-min-32-characters
JWT_EXPIRES_IN=7d
JWT_REFRESH_EXPIRES_IN=30d

3. Initialize Database

For MySQL:

# Generate Prisma client
npm run prisma:generate

# Create database tables
npm run prisma:migrate

# Or push schema directly
npm run prisma:push

For MongoDB: No initialization needed - schemas are created automatically.

4. Start Server

# Development mode (with hot reload)
npm run dev

# Production mode
npm start

πŸ§ͺ Testing

# Run all tests
npm test

# Run tests in watch mode
npm run test:watch

# Run tests with coverage report
npm run test:coverage

Test Coverage

Component Status Coverage
authController βœ… Full endpoint testing
authMiddleware βœ… JWT validation, auth flow
User Model βœ… Password hashing, validation

πŸ“‘ API Endpoints

Authentication

Method Endpoint Description Auth Required
POST /api/auth/register Register new user ❌
POST /api/auth/login User login ❌
POST /api/auth/logout User logout ❌
POST /api/auth/refresh Refresh access token ❌
POST /api/auth/forgot-password Request password reset ❌
POST /api/auth/reset-password Reset password with token ❌
GET /api/auth/me Get current user βœ…

Admin (Admin role required)

Method Endpoint Description Auth Required
GET /api/auth/users List all users (paginated) βœ… Admin
GET /api/auth/users/:id Get user by ID βœ… Admin
PATCH /api/auth/users/:id Update user role βœ… Admin
DELETE /api/auth/users/:id Delete user βœ… Admin

Health & Documentation

Method Endpoint Description
GET /health Service health status
GET /api-docs Swagger API documentation

πŸ“ Request/Response Examples

Register

curl -X POST http://localhost:3000/api/auth/register \
  -H "Content-Type: application/json" \
  -d '{"email": "user@example.com", "password": "SecurePassword123"}'

Response:

{
  "message": "Registration successful",
  "user": { "id": "1", "email": "user@example.com", "role": "user" },
  "accessToken": "eyJhbGciOiJIUzI1NiIs...",
  "refreshToken": "eyJhbGciOiJIUzI1NiIs..."
}

Login

curl -X POST http://localhost:3000/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email": "user@example.com", "password": "SecurePassword123"}'

Forgot Password

curl -X POST http://localhost:3000/api/auth/forgot-password \
  -H "Content-Type: application/json" \
  -d '{"email": "user@example.com"}'

Reset Password

curl -X POST http://localhost:3000/api/auth/reset-password \
  -H "Content-Type: application/json" \
  -d '{"token": "<reset-token>", "password": "NewSecurePassword123"}'

Get Current User

curl -X GET http://localhost:3000/api/auth/me \
  -H "Authorization: Bearer <access_token>"

Admin - List Users

curl -X GET "http://localhost:3000/api/auth/users?page=1&limit=10" \
  -H "Authorization: Bearer <admin_access_token>"

πŸ”§ Configuration

Environment Variables

Variable Default Description
PORT 3000 Server port
NODE_ENV development Environment mode
LOG_LEVEL info Logging level
DB_PROVIDER mysql Database provider (mysql/mongodb)
DATABASE_URL - MySQL connection string
MONGODB_URI - MongoDB connection string
JWT_SECRET - JWT signing secret (min 32 chars)
JWT_EXPIRES_IN 7d Access token expiration
JWT_REFRESH_EXPIRES_IN 30d Refresh token expiration
CORS_ORIGINS localhost:3000,localhost:5173 Allowed CORS origins
RATE_LIMIT_MAX 100 Max requests per window
RATE_LIMIT_WINDOW_MS 900000 Rate limit window (15 min)
SALT_ROUNDS 12 bcrypt salt rounds
LOCKOUT_MAX_ATTEMPTS 5 Failed attempts before lockout
LOCKOUT_DURATION_MS 900000 Lockout duration (15 min)

πŸ”’ Security Features

Password Security

  • Passwords hashed with bcrypt (configurable rounds, default 12)
  • Passwords never returned in API responses
  • Minimum 8 characters required

Account Lockout (Brute-Force Protection)

  • Account locks after 5 failed login attempts
  • Lockout duration: 15 minutes
  • Returns HTTP 423 (Locked) with retry time

Token Security

  • Access tokens expire in 7 days
  • Refresh tokens expire in 30 days
  • Refresh tokens are stored in database for revocation
  • Token rotation on refresh

HTTP Security

  • Helmet sets secure HTTP headers
  • CORS configured for allowed origins
  • Rate limiting prevents abuse (100 req/15 min)
  • XSS protection via xss-clean
  • Parameter pollution protection via hpp

Database Security

  • MySQL: SQL injection prevented by Prisma ORM
  • MongoDB: NoSQL injection protection via express-mongo-sanitize

πŸ—„οΈ Database Schemas

MySQL (Prisma)

model User {
  id            DateTime      @id @default(now())
  email         String        @unique
  password      String
  role          String        @default("user")
  isVerified    Boolean       @default(false)
  createdAt     DateTime      @default(now())
  updatedAt     DateTime      @updatedAt
  tokens        Token[]
  passwordResets PasswordReset?
}

model Token {
  id        String   @id @default(uuid())
  token     String   @unique
  userId    Int
  type      String
  expiresAt DateTime
  createdAt DateTime @default(now())
  user      User     @relation(fields: [userId], references: [id], onDelete: Cascade)
  @@index([userId])
}

model PasswordReset {
  id        String   @id @default(uuid())
  email     String
  token     String   @unique
  expiresAt DateTime
  createdAt DateTime @default(now())
  @@index([email])
}

MongoDB (Mongoose)

// User Schema
{
  email: String (unique, lowercase),
  password: String (min 8 chars),
  role: Enum ['user', 'admin'] (default: 'user'),
  failedLoginAttempts: Number (default: 0),
  lockoutUntil: Date (null = not locked),
  createdAt: Date,
  updatedAt: Date
}

// Token Schema
{
  token: String (unique),
  userId: ObjectId (ref: User),
  type: Enum ['access', 'refresh'],
  expiresAt: Date (TTL index for auto-expiry),
  createdAt: Date
}

// PasswordReset Schema
{
  email: String (lowercase),
  token: String (unique),
  expiresAt: Date (TTL index for auto-expiry),
  createdAt: Date
}

πŸ“œ Available Scripts

Command Description
npm start Start production server
npm run dev Start development server with hot reload
npm test Run all tests with coverage
npm run test:watch Run tests in watch mode
npm run test:coverage Run tests with coverage report
npm run prisma:generate Generate Prisma client
npm run prisma:migrate Create database migrations
npm run prisma:push Push schema to database

πŸ”„ Switching Databases

To switch from MySQL to MongoDB (or vice versa):

  1. Update DB_PROVIDER in .env:

    DB_PROVIDER=mongodb
    
  2. Update database connection string:

    MONGODB_URI="mongodb://localhost:27017/auth_service"
    
  3. Restart the server:

    npm run dev

Note: Data is not migrated automatically. Each database is independent.


πŸ“¦ Dependencies

Core

  • express - Web framework
  • jsonwebtoken - JWT authentication
  • bcryptjs - Password hashing

Database

  • mysql2 - MySQL client
  • prisma / @prisma/client - MySQL ORM
  • mongoose - MongoDB ODM

Security

  • helmet - Secure HTTP headers
  • cors - Cross-origin resource sharing
  • xss-clean - XSS protection
  • hpp - Parameter pollution protection
  • express-rate-limit - Rate limiting
  • express-mongo-sanitize - NoSQL injection protection

Validation & Logging

  • joi - Input validation
  • winston - Logging
  • morgan - HTTP request logging

Documentation

  • swagger-jsdoc - OpenAPI specification generator
  • swagger-ui-express - Swagger UI

Testing

  • jest - Test framework
  • supertest - HTTP assertions

πŸ“„ License

ISC

About

Building a secure authentication api

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors