Skip to content

DIYA73/api-auth-service

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

9 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ” API Authentication Service

Production-ready authentication microservice built with Node.js, Express, MongoDB, and JWT. Provides secure user registration, login, and token-based authentication for modern web applications.

Node.js Express MongoDB JWT License


πŸ“– Overview

A standalone authentication microservice designed to handle user management and authentication for any frontend application. Built with security best practices, it provides a robust foundation for implementing authentication in React, Vue, Angular, or vanilla JavaScript applications.

🎯 Key Features

  • πŸ” Secure Authentication: JWT-based stateless authentication
  • πŸ‘€ User Management: Registration, login, profile management
  • πŸ”’ Password Security: bcrypt hashing with salt rounds
  • πŸ›‘οΈ Protected Routes: Middleware for route protection
  • πŸ‘₯ Role-Based Access: Admin, User role support
  • πŸ”„ Token Refresh: Automatic token renewal
  • πŸ“§ Email Verification: Optional email confirmation (planned)
  • πŸ”‘ Password Reset: Secure password recovery flow (planned)
  • ⚑ High Performance: Optimized for speed and scalability
  • πŸ“Š MongoDB Integration: Efficient data storage with Mongoose

πŸ› οΈ Tech Stack

Core

πŸš€  Node.js 18+ (JavaScript Runtime)
🌐  Express.js 4+ (Web Framework)
πŸ—„οΈ  MongoDB 6+ (Database)
πŸ”—  Mongoose (ODM)

Security

πŸ”  jsonwebtoken (JWT Auth)
πŸ›‘οΈ  bcrypt (Password Hashing)
πŸ”’  helmet (Security Headers)
βœ…  express-validator (Input Validation)
🌍  cors (Cross-Origin Resource Sharing)

Development

πŸ“¦  dotenv (Environment Variables)
πŸ”„  nodemon (Auto-restart)
πŸ§ͺ  Jest (Testing - optional)

πŸ—οΈ Architecture

Service-Oriented Design

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚        Frontend Applications         β”‚
β”‚  (React / Vue / Angular / Vanilla)   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
               β”‚
               β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚     API Authentication Service       β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚                                      β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
β”‚  β”‚  Register  β”‚   β”‚    Login     β”‚  β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
β”‚                                      β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
β”‚  β”‚   Token    β”‚   β”‚   Refresh    β”‚  β”‚
β”‚  β”‚   Verify   β”‚   β”‚    Token     β”‚  β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
β”‚                                      β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
β”‚  β”‚  Profile   β”‚   β”‚    Logout    β”‚  β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
β”‚                                      β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
               β”‚
               β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚          MongoDB Database            β”‚
β”‚         (Users Collection)           β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

✨ Features Breakdown

1. User Registration

Endpoint: POST /api/auth/register

Features:

  • Email uniqueness validation
  • Password strength requirements
  • Automatic password hashing (bcrypt)
  • User role assignment
  • Creation timestamp

Request:

{
  "name": "John Doe",
  "email": "john@example.com",
  "password": "SecurePass123!"
}

Response:

{
  "success": true,
  "message": "User registered successfully",
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "user": {
    "id": "123abc",
    "name": "John Doe",
    "email": "john@example.com",
    "role": "user"
  }
}

2. User Login

Endpoint: POST /api/auth/login

Features:

  • Email/password verification
  • Password comparison (bcrypt)
  • JWT token generation
  • Refresh token issuance (optional)

Request:

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

Response:

{
  "success": true,
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "refreshToken": "...",
  "expiresIn": "7d"
}

3. Protected Routes

Endpoint: GET /api/users/profile

Features:

  • JWT verification middleware
  • Token expiration check
  • User data retrieval
  • Role-based access control

Headers:

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Response:

{
  "success": true,
  "user": {
    "id": "123abc",
    "name": "John Doe",
    "email": "john@example.com",
    "role": "user",
    "createdAt": "2024-01-15T10:00:00Z"
  }
}

4. Token Refresh

Endpoint: POST /api/auth/refresh

Features:

  • Refresh token validation
  • New access token generation
  • Extended session management

πŸš€ Quick Start

Prerequisites

  • Node.js 18+
  • MongoDB 6+ (local or MongoDB Atlas)
  • npm or yarn

Installation

1. Clone Repository

git clone https://github.com/DIYA73/api-auth-service.git
cd api-auth-service

2. Install Dependencies

npm install

3. Environment Setup

Create .env file:

# Server Configuration
NODE_ENV=development
PORT=5000

# MongoDB
MONGODB_URI=mongodb://localhost:27017/auth_service
# Or MongoDB Atlas:
# MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/auth_service

# JWT Configuration
JWT_SECRET=your-super-secret-jwt-key-minimum-32-characters-long
JWT_EXPIRES_IN=7d
JWT_REFRESH_SECRET=your-refresh-token-secret-also-32-chars-min
JWT_REFRESH_EXPIRES_IN=30d

# bcrypt Configuration
BCRYPT_SALT_ROUNDS=10

# CORS Configuration
ALLOWED_ORIGINS=http://localhost:3000,http://localhost:5173

# Optional: Email Service (for verification)
# EMAIL_HOST=smtp.gmail.com
# EMAIL_PORT=587
# EMAIL_USER=your-email@gmail.com
# EMAIL_PASSWORD=your-app-password

4. Start Server

# Development mode (with nodemon)
npm run dev

# Production mode
npm start

Server runs on http://localhost:5000


πŸ“ Project Structure

api-auth-service/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ controllers/           # Request handlers
β”‚   β”‚   └── auth.controller.js
β”‚   β”œβ”€β”€ models/                # Mongoose schemas
β”‚   β”‚   └── User.model.js
β”‚   β”œβ”€β”€ routes/                # API routes
β”‚   β”‚   └── auth.routes.js
β”‚   β”œβ”€β”€ middleware/            # Express middleware
β”‚   β”‚   β”œβ”€β”€ auth.middleware.js
β”‚   β”‚   β”œβ”€β”€ validate.middleware.js
β”‚   β”‚   └── error.middleware.js
β”‚   β”œβ”€β”€ config/                # Configuration
β”‚   β”‚   β”œβ”€β”€ db.config.js
β”‚   β”‚   └── jwt.config.js
β”‚   β”œβ”€β”€ utils/                 # Utilities
β”‚   β”‚   β”œβ”€β”€ token.util.js
β”‚   β”‚   └── password.util.js
β”‚   β”œβ”€β”€ validators/            # Input validation
β”‚   β”‚   └── auth.validator.js
β”‚   └── server.js              # Entry point
β”œβ”€β”€ .env.example               # Environment template
β”œβ”€β”€ .gitignore
β”œβ”€β”€ LICENSE
β”œβ”€β”€ package.json
└── README.md

πŸ”Œ API Endpoints

Authentication

Method Endpoint Description Auth Required
POST /api/auth/register Register new user No
POST /api/auth/login User login No
POST /api/auth/refresh Refresh access token Yes (Refresh Token)
POST /api/auth/logout User logout Yes
POST /api/auth/forgot-password Request password reset No
POST /api/auth/reset-password Reset password No

User Management

Method Endpoint Description Auth Required
GET /api/users/profile Get user profile Yes
PUT /api/users/profile Update user profile Yes
PUT /api/users/password Change password Yes
DELETE /api/users/account Delete account Yes

Admin (Role-based)

Method Endpoint Description Auth Required
GET /api/admin/users List all users Yes (Admin)
GET /api/admin/users/:id Get user by ID Yes (Admin)
PUT /api/admin/users/:id/role Update user role Yes (Admin)
DELETE /api/admin/users/:id Delete user Yes (Admin)

πŸ”’ Security Implementation

Password Security

// Password hashing (bcrypt)
const bcrypt = require('bcrypt');
const saltRounds = 10;

const hashPassword = async (password) => {
  return await bcrypt.hash(password, saltRounds);
};

const comparePassword = async (password, hash) => {
  return await bcrypt.compare(password, hash);
};

JWT Token Generation

const jwt = require('jsonwebtoken');

const generateToken = (userId, role) => {
  return jwt.sign(
    { userId, role },
    process.env.JWT_SECRET,
    { expiresIn: process.env.JWT_EXPIRES_IN }
  );
};

Authentication Middleware

const authMiddleware = async (req, res, next) => {
  try {
    const token = req.headers.authorization?.split(' ')[1];
    
    if (!token) {
      return res.status(401).json({ message: 'No token provided' });
    }
    
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    req.user = decoded;
    next();
  } catch (error) {
    res.status(401).json({ message: 'Invalid token' });
  }
};

πŸ’» Frontend Integration

React Example

// services/auth.service.js
const API_URL = 'http://localhost:5000/api/auth';

export const authService = {
  register: async (userData) => {
    const response = await fetch(`${API_URL}/register`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(userData)
    });
    return response.json();
  },
  
  login: async (credentials) => {
    const response = await fetch(`${API_URL}/login`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(credentials)
    });
    const data = await response.json();
    if (data.token) {
      localStorage.setItem('token', data.token);
    }
    return data;
  },
  
  logout: () => {
    localStorage.removeItem('token');
  },
  
  getProfile: async () => {
    const token = localStorage.getItem('token');
    const response = await fetch('http://localhost:5000/api/users/profile', {
      headers: { 'Authorization': `Bearer ${token}` }
    });
    return response.json();
  }
};

Axios Interceptor

import axios from 'axios';

const apiClient = axios.create({
  baseURL: 'http://localhost:5000/api'
});

// Add token to all requests
apiClient.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => Promise.reject(error)
);

// Handle token expiration
apiClient.interceptors.response.use(
  (response) => response,
  async (error) => {
    if (error.response?.status === 401) {
      // Redirect to login
      window.location = '/login';
    }
    return Promise.reject(error);
  }
);

πŸ§ͺ Testing

Manual Testing with cURL

Register User:

curl -X POST http://localhost:5000/api/auth/register \
  -H "Content-Type: application/json" \
  -d '{"name":"John Doe","email":"john@example.com","password":"SecurePass123!"}'

Login:

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

Get Profile (with token):

curl -X GET http://localhost:5000/api/users/profile \
  -H "Authorization: Bearer YOUR_TOKEN_HERE"

Automated Testing

# Run tests
npm test

# Watch mode
npm run test:watch

# Coverage
npm run test:coverage

πŸ—„οΈ Database Schema

User Model

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, 'Name is required'],
    trim: true,
    minlength: 2,
    maxlength: 50
  },
  email: {
    type: String,
    required: [true, 'Email is required'],
    unique: true,
    lowercase: true,
    trim: true,
    match: [/^\S+@\S+\.\S+$/, 'Please provide a valid email']
  },
  password: {
    type: String,
    required: [true, 'Password is required'],
    minlength: 8,
    select: false // Don't return password by default
  },
  role: {
    type: String,
    enum: ['user', 'admin'],
    default: 'user'
  },
  isVerified: {
    type: Boolean,
    default: false
  },
  verificationToken: String,
  resetPasswordToken: String,
  resetPasswordExpires: Date,
  lastLogin: Date,
  createdAt: {
    type: Date,
    default: Date.now
  },
  updatedAt: {
    type: Date,
    default: Date.now
  }
});

πŸ”’ Security Best Practices

Implemented:

  • βœ… Password hashing with bcrypt (salt rounds: 10)
  • βœ… JWT token-based authentication
  • βœ… Input validation and sanitization
  • βœ… Environment variable protection
  • βœ… CORS configuration
  • βœ… Helmet.js security headers
  • βœ… Rate limiting (optional)
  • βœ… HTTPS enforcement (production)

Recommended:

  • Two-factor authentication (2FA)
  • Account lockout after failed attempts
  • IP-based access control
  • Session management
  • Regular security audits

πŸš€ Deployment

Deploy to Render

  1. Create new Web Service
  2. Connect GitHub repository
  3. Configure:
    • Build Command: npm install
    • Start Command: npm start
  4. Add environment variables
  5. Deploy

Deploy to Heroku

heroku create api-auth-service
heroku config:set JWT_SECRET=your-secret
heroku config:set MONGODB_URI=your-mongodb-uri
git push heroku main

Docker Deployment

FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
EXPOSE 5000
CMD ["npm", "start"]

πŸ—ΊοΈ Roadmap

βœ… Phase 1: Core (Completed)

  • User registration
  • User login
  • JWT authentication
  • Protected routes
  • Password hashing

🚧 Phase 2: Enhanced Features (In Progress)

  • Email verification
  • Password reset flow
  • Refresh token implementation
  • Role-based access control
  • Account deactivation

πŸ“‹ Phase 3: Advanced Features (Planned)

  • Two-factor authentication (2FA)
  • OAuth integration (Google, GitHub)
  • Session management
  • Rate limiting per user
  • Admin dashboard API
  • Audit logging

🀝 Contributing

Contributions welcome! Please:

  1. Fork the repository
  2. Create a feature branch
  3. Write tests for new features
  4. Follow existing code style
  5. Submit a Pull Request

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.


πŸ‘¨β€πŸ’» Author

DIYA73


πŸ™ Acknowledgments

  • Express.js community
  • MongoDB documentation
  • JWT.io resources
  • bcrypt library maintainers

πŸ”— Related Projects

Microservices:

Full Applications:


⭐ If this auth service helps secure your apps, please star the repository!

πŸ” Securing applications, one token at a time.


Made with ❀️ for secure authentication

About

πŸ” Production-ready authentication microservice with Node.js, Express, MongoDB, JWT. User registration, login, token refresh, role-based access

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors