gagan-auth-kit
v1.0.0
Published
A lightweight, reusable authentication module for Express.js with JWT, bcryptjs password hashing, and MongoDB support
Maintainers
Readme
🔐 Gagan Auth Kit
A lightweight, reusable authentication module for Express.js applications with JWT-based authentication, password hashing with bcryptjs, and MongoDB support.
✨ Features
- User Registration & Login - Pre-built routes for user authentication
- JWT Token Management - Secure token generation and validation
- Password Hashing - Bcryptjs integration for secure password storage
- Route Protection Middleware - Protect routes with
protectRoutemiddleware - Mongoose Integration - Works seamlessly with MongoDB via Mongoose
- Easy Integration - Simple initialization with minimal configuration
📦 Installation
npm install gagan-auth-kit🚀 Quick Start
1. Initialize the Auth Module
const express = require('express');
const InitializeAuth = require('gagan-auth-kit');
const mongoose = require('mongoose');
const { userSchema } = require('./models/User'); // Your User model
const app = express();
app.use(express.json());
// Define your User model
const User = mongoose.model('User', userSchema);
// Initialize the auth kit
const { authRouter, protectRoute } = InitializeAuth({
UserModel: User,
jwtSecret: process.env.JWT_SECRET || 'your-secret-key'
});
// Use the auth router
app.use('/auth', authRouter);
// Example: Protect a route
app.get('/profile', protectRoute, (req, res) => {
res.json({ message: 'This is a protected route', user: req.user });
});
app.listen(3000, () => console.log('Server running on port 3000'));2. User Model Example
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
createdAt: {
type: Date,
default: Date.now
}
});
module.exports = mongoose.model('User', userSchema);📚 API Reference
InitializeAuth(options)
Initializes the authentication module with your configuration.
Parameters:
options.UserModel(required): Your Mongoose User modeloptions.jwtSecret(required): Secret key for JWT signing
Returns:
{
authRouter: Express.Router, // Router with /register and /login routes
protectRoute: Function // Middleware to protect routes
}Routes
POST /register
Create a new user account.
Request Body:
{
"name": "John Doe",
"email": "[email protected]",
"password": "securepassword123"
}Response:
{
"message": "User registered successfully",
"user": {
"_id": "...",
"name": "John Doe",
"email": "[email protected]"
}
}POST /login
Authenticate user and receive JWT token.
Request Body:
{
"email": "[email protected]",
"password": "securepassword123"
}Response:
{
"message": "Login successful",
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"user": {
"_id": "...",
"name": "John Doe",
"email": "[email protected]"
}
}Middleware: protectRoute
Protects routes by requiring a valid JWT token in the Authorization header.
Usage:
app.get('/protected-endpoint', protectRoute, (req, res) => {
console.log(req.user); // Decoded JWT payload
res.json({ message: 'Access granted', user: req.user });
});Authorization Header Format:
Authorization: Bearer <your_jwt_token>🔧 Environment Variables
Create a .env file in your project:
JWT_SECRET=your_very_secret_key_here
MONGODB_URI=mongodb://localhost:27017/your-db
NODE_ENV=development📋 Dependencies
- express - Web framework
- mongoose - MongoDB object modeling
- jsonwebtoken - JWT token generation and validation
- bcryptjs - Password hashing
- dotenv - Environment variable management
🤝 Error Handling
The module returns standard HTTP status codes:
200- Success201- User created400- Invalid input or user already exists401- Unauthorized (invalid credentials or token)500- Server error
🔐 Security Best Practices
- Never hardcode secrets - Always use environment variables
- Use HTTPS in production - Ensure secure token transmission
- Implement rate limiting - Prevent brute force attacks
- Set appropriate JWT expiration - Balance security and user experience
- Store tokens securely - Use httpOnly cookies on the client-side
📝 License
ISC
👨💻 Author
Gagan
🤝 Contributing
Feel free to fork and submit pull requests for any improvements.
📞 Support
For issues and questions, please open an issue on GitHub.
