auth-express-mongo
v1.1.0
Published
Reusable Auth library for Express + MongoDB with JWT, refresh tokens, and password reset
Maintainers
Readme
@codes-sharan/auth-express-mongo
A complete authentication library for Express.js with MongoDB, featuring JWT tokens, email verification, password reset, and secure middleware protection.
Features
- 🔐 JWT Authentication - Access & refresh tokens
- 📧 Email Verification - OTP-based verification with Gmail integration
- 🔒 Password Security - bcrypt password hashing
- 🛡️ Security Features - Account locking, rate limiting protection
- 📬 Password Reset - Secure token-based password reset
- 🔄 Token Refresh - Seamless token refresh mechanism
- 🎯 Middleware Protection - Easy route protection
- 🚀 MongoDB Integration - Built with Mongoose ODM
- 📧 Email Templates - Professional HTML email templates
Installation
npm install @codes-sharan/auth-express-mongoQuick Start
1. Basic Setup
import express from 'express';
import { createAuth } from '@codes-sharan/auth-express-mongo';
const app = express();
app.use(express.json());
const auth = createAuth({
mongoUri: 'mongodb://localhost:27017/your-db',
jwtSecret: 'your-jwt-secret-key',
refreshSecret: 'your-refresh-secret-key'
});
app.use('/auth', auth.router);
app.listen(5000, () => {
console.log('Server running on port 5000');
});2. With Email Verification (Recommended)
import express from 'express';
import { createAuth } from '@codes-sharan/auth-express-mongo';
const app = express();
app.use(express.json());
const auth = createAuth({
mongoUri: process.env.MONGODB_URI,
jwtSecret: process.env.JWT_SECRET,
refreshSecret: process.env.REFRESH_SECRET,
emailConfig: {
gmailUser: process.env.SMTP_USER,
gmailAppPassword: process.env.SMTP_PASSWORD,
fromEmail: process.env.SMTP_FROM
}
});
app.use('/auth', auth.router);
// Protected route example
app.get('/profile', auth.middleware.authenticate, (req, res) => {
res.json({ user: req.user });
});
app.listen(5000, () => {
console.log('Server running on port 5000');
});Environment Variables
Create a .env file:
MONGODB_URI=mongodb://localhost:27017/your-database
JWT_SECRET=your-super-secret-jwt-key
REFRESH_SECRET=your-super-secret-refresh-key
[email protected]
SMTP_PASSWORD=your-gmail-app-password
[email protected]API Reference
Authentication Endpoints
| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | /auth/register | Register new user (sends OTP email) |
| POST | /auth/verify-email | Verify email with OTP |
| POST | /auth/resend-verification | Resend verification OTP |
| POST | /auth/login | Login user (requires verified email) |
| POST | /auth/refresh | Refresh access token |
| POST | /auth/forgot-password | Request password reset |
| POST | /auth/reset-password | Reset password with token |
| POST | /auth/verify | Verify JWT token validity |
Request Examples
Register User
curl -X POST http://localhost:5000/auth/register \
-H "Content-Type: application/json" \
-d '{"email": "[email protected]", "password": "password123"}'Verify Email
curl -X POST http://localhost:5000/auth/verify-email \
-H "Content-Type: application/json" \
-d '{"email": "[email protected]", "otp": "123456"}'Login
curl -X POST http://localhost:5000/auth/login \
-H "Content-Type: application/json" \
-d '{"email": "[email protected]", "password": "password123"}'Access Protected Route
curl -X GET http://localhost:5000/protected \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN"Middleware Usage
Route Protection
import { createAuth } from '@codes-sharan/auth-express-mongo';
const auth = createAuth({ /* config */ });
// Basic protection
app.get('/protected', auth.middleware.authenticate, (req, res) => {
res.json({ message: 'Protected data', user: req.user });
});
// Optional authentication (user attached if token exists)
app.get('/public', auth.middleware.optionalAuth, (req, res) => {
const userInfo = req.user ? { user: req.user } : {};
res.json({ message: 'Public route', ...userInfo });
});Configuration Options
const auth = createAuth({
// Required
mongoUri: 'mongodb://localhost:27017/your-db',
jwtSecret: 'your-jwt-secret',
refreshSecret: 'your-refresh-secret',
// Optional
jwtExpiresIn: '15m', // Default: 15 minutes
refreshExpiresIn: '7d', // Default: 7 days
// Email configuration (optional)
emailConfig: {
gmailUser: '[email protected]',
gmailAppPassword: 'your-app-password',
fromEmail: '[email protected]'
},
// Custom email function (alternative to emailConfig)
sendResetEmail: async (email, token) => {
// Your custom email logic
console.log(`Reset token for ${email}: ${token}`);
}
});Complete Example
import express from 'express';
import dotenv from 'dotenv';
import { createAuth } from '@codes-sharan/auth-express-mongo';
dotenv.config();
const app = express();
app.use(express.json());
// Initialize authentication
const auth = createAuth({
mongoUri: process.env.MONGODB_URI,
jwtSecret: process.env.JWT_SECRET,
refreshSecret: process.env.REFRESH_SECRET,
emailConfig: {
gmailUser: process.env.SMTP_USER,
gmailAppPassword: process.env.SMTP_PASSWORD,
fromEmail: process.env.SMTP_FROM
}
});
// Auth routes
app.use('/auth', auth.router);
// Protected routes
app.get('/profile', auth.middleware.authenticate, (req, res) => {
res.json({
message: 'User profile',
user: {
id: req.user._id,
email: req.user.email
}
});
});
// Public route
app.get('/', (req, res) => {
res.json({
message: 'Welcome to Auth Express MongoDB!',
endpoints: {
auth: '/auth/*',
protected: '/profile'
}
});
});
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`🚀 Server running on http://localhost:${PORT}`);
});Response Formats
Success Response
{
"success": true,
"message": "Operation successful",
"data": { /* response data */ }
}Error Response
{
"error": "ErrorType",
"message": "Human readable error message"
}Security Features
- Password Hashing: Uses bcrypt with salt rounds 10
- JWT Tokens: Secure token-based authentication
- Account Locking: Automatic lock after 5 failed attempts
- Email Verification: Required before login
- Token Expiration: Configurable token lifetimes
- Input Validation: Comprehensive request validation
Gmail Setup
- Enable 2-factor authentication on your Gmail account
- Generate an App Password:
- Go to Google Account → Security → 2-Step Verification → App passwords
- Select "Mail" and "Other (Custom name)"
- Name it "Auth Express Mongo"
- Use the 16-character password in your
.envfile
Error Handling
The package includes comprehensive error handling for:
- Validation errors (email format, password strength)
- Authentication errors (invalid credentials, expired tokens)
- Database errors (duplicate emails, connection issues)
- Email errors (sending failures)
Migration from v1 to v2
If upgrading from previous versions:
- The main export now returns an object with
routerandmiddleware - Email verification is now enabled by default when email config is provided
- Improved error handling with structured error responses
License
ISC
Support
For issues and feature requests, please visit the GitHub repository.
Contributing
Contributions are welcome! Please feel free to submit pull requests or open issues for discussion.
Built with ❤️ by Sharan
