Skip to content

yunji0387/express-auth-server

Repository files navigation

Express Authentication Server

Run Tests CodeQL Dependabot Updates

License: MIT Node.js Version

GitHub issues GitHub forks GitHub stars

Maintenance PRs Welcome

A robust and secure Node.js Express server providing complete user authentication functionality including registration, login, logout, password reset, and session validation with JWT tokens and OAuth integration.

✨ Features

  • πŸ” User Registration - Secure account creation with password hashing
  • πŸ”‘ User Login - JWT-based authentication with HTTPOnly cookies
  • πŸšͺ User Logout - Secure session termination with token blacklisting
  • βœ… Session Validation - Middleware for protected routes
  • πŸ”„ Password Reset - Email-based password recovery system
  • 🌐 OAuth Integration - Google OAuth with Passport.js
  • πŸ›‘οΈ Security Features - Rate limiting, CORS, input validation
  • 🐳 Docker Support - Containerized deployment ready
  • πŸ§ͺ Comprehensive Testing - 87%+ test coverage with Jest

πŸ“‹ Prerequisites

Before you begin, ensure you have met the following requirements:

  • Node.js >= 16.0.0 and npm installed
  • MongoDB running locally or remotely (MongoDB Atlas recommended)
  • Git for version control
  • Google OAuth Credentials (optional, for OAuth features)

πŸš€ Installation and Local Setup

1. Clone the repository

git clone https://github.com/yunji0387/express-auth-server.git
cd express-auth-server

2. Install dependencies

npm install

3. Environment Configuration

Create a .env file in the project root:

# Database
URI=mongodb://localhost:27017/your-database-name
# or for MongoDB Atlas:
# URI=mongodb+srv://username:[email protected]/database-name

# Server Configuration
PORT=5005
NODE_ENV=development

# JWT Configuration
SECRET_ACCESS_TOKEN=your-super-secret-jwt-key-here

# Google OAuth (Optional)
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret

# Email Configuration (for password reset)
EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
[email protected]
EMAIL_PASS=your-app-password

4. Start the development server

npm start

The server will start running on http://localhost:5005

5. Run tests (optional)

# Run all tests
npm test

# Run tests with coverage
npm run test:coverage

🐳 Docker Setup

Quick Start with Docker

  1. Build the Docker image:

    docker build -t express-auth-server .
  2. Run with Docker Compose (recommended):

    # Create docker-compose.yml with MongoDB service
    docker-compose up -d
  3. Or run the container directly:

    docker run -p 5005:5005 --env-file .env express-auth-server

Note: Ensure your .env file is properly configured before running with Docker.


πŸ“š API Documentation

Base URL

http://localhost:5005

Authentication Endpoints

1. Register New User

  • URL: /auth/register
  • Method: POST
  • Content-Type: application/json

Request Body:

{
  "first_name": "John",
  "last_name": "Doe", 
  "email": "[email protected]",
  "password": "SecurePassword123!"
}

Success Response: 201 Created

{
  "status": "success",
  "data": {
    "first_name": "John",
    "last_name": "Doe",
    "email": "[email protected]"
  },
  "message": "Your account has been successfully created."
}

Error Response: 400 Bad Request

{
  "error": {
    "status": "failed",
    "message": "It seems you already have an account, please log in instead."
  }
}

2. User Login

  • URL: /auth/login
  • Method: POST
  • Content-Type: application/json

Request Body:

{
  "email": "[email protected]",
  "password": "SecurePassword123!"
}

Success Response: 200 OK + JWT cookie set

{
  "status": "success",
  "data": {
    "first_name": "John",
    "last_name": "Doe",
    "email": "[email protected]"
  },
  "message": "You have successfully logged in."
}

Error Response: 401 Unauthorized

{
  "error": {
    "status": "failed",
    "message": "Invalid email or password. Please try again with the correct credentials."
  }
}

3. User Logout

  • URL: /auth/logout
  • Method: GET
  • Authentication: Required (JWT cookie)

Success Response: 200 OK

{
  "status": "success",
  "message": "You have successfully logged out."
}

4. Verify Session

  • URL: /auth/verify
  • Method: GET
  • Authentication: Required (JWT cookie)

Success Response: 200 OK

{
  "status": "success",
  "message": "You are authenticated."
}

Error Response: 401 Unauthorized

{
  "error": {
    "status": "failed",
    "message": "Access denied. No valid token provided."
  }
}

5. Get User Profile

  • URL: /auth/user
  • Method: GET
  • Authentication: Required (JWT cookie)

Success Response: 200 OK

{
  "status": "success",
  "data": {
    "first_name": "John",
    "last_name": "Doe",
    "email": "[email protected]"
  }
}

πŸ› οΈ Technology Stack

  • Runtime: Node.js (>= 16.0.0)
  • Framework: Express.js
  • Database: MongoDB with Mongoose
  • Authentication: JWT + Passport.js (Google OAuth)
  • Security: bcrypt, CORS, cookie-parser
  • Testing: Jest with 87%+ coverage
  • Container: Docker & Docker Compose
  • Environment: dotenv for configuration

πŸ—οΈ Project Structure

β”œβ”€β”€ config/
β”‚   β”œβ”€β”€ index.js              # Passport configuration
β”‚   └── __tests__/            # Config tests
β”œβ”€β”€ controllers/
β”‚   β”œβ”€β”€ auth.js               # Authentication logic
β”‚   └── __tests__/            # Controller tests
β”œβ”€β”€ middleware/
β”‚   β”œβ”€β”€ validate.js           # Input validation
β”‚   β”œβ”€β”€ verify.js             # JWT verification
β”‚   └── __tests__/            # Middleware tests
β”œβ”€β”€ models/
β”‚   β”œβ”€β”€ User.js               # User schema
β”‚   β”œβ”€β”€ Blacklist.js          # Token blacklist
β”‚   └── __tests__/            # Model tests
β”œβ”€β”€ routes/
β”‚   β”œβ”€β”€ auth.js               # Auth routes
β”‚   └── index.js              # Route exports
β”œβ”€β”€ views/
β”‚   └── reset-password.ejs    # Password reset template
β”œβ”€β”€ public/
β”‚   └── assets/               # Static files
β”œβ”€β”€ .env.example              # Environment template
β”œβ”€β”€ server.js                 # Application entry point
β”œβ”€β”€ Dockerfile                # Docker configuration
└── package.json              # Dependencies & scripts

πŸ§ͺ Testing

This project includes comprehensive test coverage:

# Run all tests
npm test

# Run tests with coverage report
npm run test:coverage

# Run specific test file
npm test -- auth.test.js

Current Coverage: Run npm run test:coverage to view the latest coverage report.

🀝 Contributing

We welcome contributions! Please follow these steps:

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Make your changes and add tests
  4. Ensure tests pass: npm test
  5. Commit your changes: git commit -m 'Add amazing feature'
  6. Push to branch: git push origin feature/amazing-feature
  7. Submit a Pull Request

Please read CONTRIBUTING.md for detailed guidelines.

πŸ“ License

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

πŸ†˜ Support & Issues

πŸ™ Acknowledgments

  • Express.js community for the robust framework
  • MongoDB team for the excellent database solution
  • Passport.js for authentication strategies
  • Jest team for the testing framework

⭐ If this project helped you, please consider giving it a star!

About

No description, website, or topics provided.

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 5

Languages