A comprehensive Node.js authentication system built with Express.js and MongoDB, featuring user registration, email verification, JWT-based authentication, session management, and secure logout functionality.
- User Registration: Secure user signup with email and username validation
- Email Verification: OTP-based email verification system
- JWT Authentication: Access and refresh token implementation
- Session Management: Multi-device session tracking and management
- Secure Logout: Single device and all-devices logout options
- Password Hashing: SHA-256 password encryption
- Email Notifications: Gmail OAuth2 integration for sending verification emails
- Middleware Integration: Morgan logging, cookie parsing, and CORS support
- Backend Framework: Express.js
- Database: MongoDB with Mongoose ODM
- Authentication: JSON Web Tokens (JWT)
- Email Service: Nodemailer with Gmail OAuth2
- Password Hashing: Crypto (SHA-256)
- Logging: Morgan
- Environment Management: dotenv
Before running this application, make sure you have the following installed:
- Node.js (v14 or higher)
- MongoDB Atlas account or local MongoDB instance
- Gmail account for email notifications
-
Clone the repository
git clone <repository-url> cd Backend-Authentication-System
-
Install dependencies
npm install
-
Set up environment variables
- Copy the
env-Demofile to.env - Fill in the required environment variables (see Environment Setup section)
- Copy the
-
Configure MongoDB
- Create a MongoDB Atlas cluster or use a local MongoDB instance
- Get your connection string
-
Set up Gmail OAuth2
- Enable 2-factor authentication on your Gmail account
- Generate an app password or set up OAuth2 credentials
- Configure the Google OAuth2 settings
Create a .env file in the root directory with the following variables:
MONGO_URI=mongodb+srv://<username>:<password>@cluster-url.mongodb.net/database-name
JWT_SECRET=your-super-secret-jwt-key-here
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret
GOOGLE_REFRESH_TOKEN=your-google-refresh-token
GOOGLE_USER=your-gmail-address@gmail.com- Go to MongoDB Atlas
- Create a new project and cluster
- Configure database access (add username & password)
- Set network access (add IP: 0.0.0.0 for development)
- Copy the connection string and replace
<username>,<password>, and<database-name>
- Go to Google Cloud Console
- Create a new project or select existing one
- Enable Gmail API
- Create OAuth2 credentials (Client ID and Client Secret)
- Generate a refresh token for your application
- Add your Gmail address to the
GOOGLE_USERvariable
-
Development mode
npm run dev
-
Production mode
npm start
The server will start on port 3000 by default.
All routes are prefixed with /api/auth
| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
| POST | /register |
Register a new user | No |
| POST | /login |
User login | No |
| GET | /get-me |
Get current user info | Yes (Access Token) |
| GET | /refresh-token |
Refresh access token | Yes (Refresh Token Cookie) |
| GET | /logout |
Logout from current device | Yes (Refresh Token Cookie) |
| GET | /logout-all |
Logout from all devices | Yes (Refresh Token Cookie) |
| GET | /verify-email |
Verify email with OTP | No |
POST /api/auth/register
Content-Type: application/json
{
"username": "johndoe",
"email": "john@example.com",
"password": "securepassword123"
}Response:
{
"message": "User registered successfully",
"user": {
"username": "johndoe",
"email": "john@example.com",
"verified": false
}
}POST /api/auth/login
Content-Type: application/json
{
"email": "john@example.com",
"password": "securepassword123"
}Response:
{
"message": "Logged in successfully",
"user": {
"username": "johndoe",
"email": "john@example.com"
},
"accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}GET /api/auth/verify-email
Content-Type: application/json
{
"email": "john@example.com",
"otp": "123456"
}Response:
{
"message": "Email verified successfully"
}{
username: String (required, unique),
email: String (required, unique),
password: String (required, hashed),
verified: Boolean (default: false)
}{
user: ObjectId (ref: users),
refreshTokenHash: String,
ip: String,
userAgent: String,
revoked: Boolean (default: false),
createdAt: Date,
updatedAt: Date
}{
email: String,
user: ObjectId (ref: users),
otpHash: String,
createdAt: Date,
updatedAt: Date
}- Password Hashing: SHA-256 encryption for passwords
- JWT Tokens: Secure access and refresh token implementation
- Session Tracking: IP and User-Agent logging for security
- Token Revocation: Ability to invalidate sessions
- OTP Verification: Time-sensitive email verification
- HTTP-Only Cookies: Secure refresh token storage
- CORS Protection: Configured for secure cross-origin requests
Backend-Authentication-System/
├── src/
│ ├── config/
│ │ ├── config.js # Environment configuration
│ │ └── db.js # Database connection
│ ├── controllers/
│ │ └── auth.controller.js # Authentication logic
│ ├── models/
│ │ ├── user.model.js # User schema
│ │ ├── session.model.js # Session schema
│ │ └── otp.model.js # OTP schema
│ ├── routes/
│ │ └── auth.routes.js # Authentication routes
│ ├── services/
│ │ └── email.service.js # Email sending service
│ ├── utils/
│ │ └── utils.js # Utility functions
│ └── app.js # Express app setup
├── server.js # Server entry point
├── package.json # Dependencies and scripts
├── .env # Environment variables
├── env-Demo # Environment template
└── README.md # Project documentation
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
This project is licensed under the ISC License.
For questions or issues, please open an issue in the GitHub repository.