Skip to content

kom50/2FA-authentication-API

Repository files navigation

2FA-authentication-API

Two-Factor Authentication (2FA) Backend

A complete Two-Factor Authentication implementation using Node.js, Express, and MongoDB.

Prerequisites

  • Node.js v18+
  • MongoDB v6.0+
  • npm/yarn
  • Google Authenticator or similar TOTP app

Tech Stack

  • Node.js & Express
  • MongoDB with Prisma ORM
  • TypeScript
  • otplib for TOTP implementation
  • QRCode for QR code generation

Project Structure

backend/
├── src/
│   ├── controllers/
│   │   └── auth.controller.ts
│   ├── services/
│   │   └── auth.service.ts
│   ├── prisma/
│   │   ├── schema.prisma
│   │   └── index.ts
│   └── server.ts
├── package.json
└── .env

Setup Instructions

  1. Install dependencies:
npm install
  1. Create environment file (.env):
DATABASE_URL="mongodb://localhost:27017/2fa-demo?replicaSet=rs0"
PORT=5000
  1. Generate Prisma client:
npx prisma generate

API Endpoints

Authentication

Method Endpoint Description
POST /api/auth/register Register new user
POST /api/auth/login User login

Two-Factor Authentication

Method Endpoint Description
POST /api/2fa/setup Setup 2FA
POST /api/2fa/verify Verify and enable 2FA
POST /api/2fa/validate Validate 2FA token
POST /api/2fa/disable Disable 2FA

API Usage Examples

1. Register User

curl -X POST http://localhost:5000/api/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "email": "[email protected]",
    "password": "password123"
  }'

2. Login User

curl -X POST http://localhost:5000/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "[email protected]",
    "password": "password123"
  }'

3. Setup 2FA

curl -X POST http://localhost:5000/api/2fa/setup \
  -H "Content-Type: application/json" \
  -d '{
    "userId": "your_user_id"
  }'

4. Verify 2FA

curl -X POST http://localhost:5000/api/2fa/verify \
  -H "Content-Type: application/json" \
  -d '{
    "userId": "your_user_id",
    "token": "123456"
  }'

Development

Start the server:

npm run dev

Security Considerations

  • Use environment variables for sensitive data
  • Implement rate limiting for API endpoints
  • Sanitize user inputs
  • Use secure session management
  • Handle errors properly
  • Store hashed passwords only

License

MIT License

About

A complete Two-Factor Authentication implementation using Node.js, Express, and MongoDB.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published