1.0.7 • Published 5 months ago
express-auth-magic-routes v1.0.7
Express Auth Magic Routes
A comprehensive authentication routes package for Express.js applications with support for Firebase authentication, Magic Link authentication, and MongoDB integration.
Features
- 🔥 Firebase Authentication
- ✨ Magic Link Authentication
- 🚀 Rate Limiting
- 🔒 Token Validation & Blacklisting
- 📧 Email Domain Validation
- 🎫 JWT Token Management
- 📊 MongoDB Integration
- 🎁 Referral System Support
- 📝 Swagger Documentation
Installation
npm install express-auth-magic-routes
Environment Variables
# MongoDB Configuration (Option 1: Using URI)
MONGO_URI=mongodb+srv://username:password@cluster.mongodb.net/database
# MongoDB Configuration (Option 2: Using separate parameters)
MONGO_USERNAME=your_username
MONGO_PASSWORD=your_password
MONGO_HOST=cluster.mongodb.net
MONGO_DATABASE=your_database
MONGO_PORT=27017 # Optional, defaults to 27017
# Firebase Configuration
FIREBASE_TYPE=service_account
FIREBASE_PROJECT_ID=your-project-id
FIREBASE_PRIVATE_KEY_ID=your-private-key-id
FIREBASE_PRIVATE_KEY="your-private-key" # Include quotes to handle newlines
FIREBASE_CLIENT_EMAIL=your-client-email
FIREBASE_CLIENT_ID=your-client-id
FIREBASE_AUTH_URI=https://accounts.google.com/o/oauth2/auth
FIREBASE_TOKEN_URI=https://oauth2.googleapis.com/token
FIREBASE_AUTH_CERT_URL=https://www.googleapis.com/oauth2/v1/certs
FIREBASE_CLIENT_CERT_URL=your-client-cert-url
# JWT Configuration
JWT_SECRET=your-jwt-secret
# Environment
NODE_ENV=development # or production
Usage
const express = require('express');
const { authRouter, initializeAuth } = require('express-auth-magic-routes');
const app = express();
// Initialize auth with your configuration
await initializeAuth({
jwtSecret: process.env.JWT_SECRET,
mongodb: {
options: {
useNewUrlParser: true,
useUnifiedTopology: true,
maxPoolSize: 10
}
},
firebaseConfig: {
type: process.env.FIREBASE_TYPE,
project_id: process.env.FIREBASE_PROJECT_ID,
private_key_id: process.env.FIREBASE_PRIVATE_KEY_ID,
private_key: process.env.FIREBASE_PRIVATE_KEY?.replace(/\\n/g, '\n'),
client_email: process.env.FIREBASE_CLIENT_EMAIL,
client_id: process.env.FIREBASE_CLIENT_ID,
auth_uri: process.env.FIREBASE_AUTH_URI,
token_uri: process.env.FIREBASE_TOKEN_URI,
auth_provider_x509_cert_url: process.env.FIREBASE_AUTH_CERT_URL,
client_x509_cert_url: process.env.FIREBASE_CLIENT_CERT_URL
},
mailService: {
sendMagicLinkEmail: async (email, token) => {
// Implement your email sending logic
}
}
});
// Use the auth routes
app.use('/auth', authRouter);
API Routes
Firebase Authentication
POST /auth
Content-Type: application/json
Request:
{
"idToken": "firebase-id-token",
"referralCode": "optional-referral-code"
}
Response:
{
"status": "success",
"data": {
"token": "jwt-token",
"user": {
"uid": "user-id",
"email": "user@example.com",
"name": "User Name",
"picture": "profile-picture-url",
"referralCode": "USER123"
}
}
}
Magic Link Authentication
Request Magic Link:
POST /auth/magic-link
Content-Type: application/json
Request:
{
"email": "user@example.com",
"referralCode": "optional-referral-code"
}
Response:
{
"status": "success",
"data": {
"message": "Magic link sent successfully"
}
}
Verify Magic Link:
POST /auth/verify-magic-link
Content-Type: application/json
Request:
{
"token": "magic-link-token"
}
Response:
{
"status": "success",
"data": {
"token": "jwt-token",
"user": {
"uid": "user-id",
"email": "user@example.com",
"name": "User Name",
"referralCode": "USER123"
}
}
}
Token Validation
GET /auth/validate
Authorization: Bearer jwt-token
Response:
{
"status": "success",
"data": {
"valid": true,
"user": {
"uid": "user-id",
"email": "user@example.com",
"name": "User Name"
}
}
}
Logout
POST /auth/logout
Authorization: Bearer jwt-token
Response:
{
"status": "success",
"message": "Successfully logged out"
}
Swagger Documentation
Add this to your Swagger configuration:
/**
* @swagger
* components:
* securitySchemes:
* BearerAuth:
* type: http
* scheme: bearer
* bearerFormat: JWT
* schemas:
* User:
* type: object
* properties:
* uid:
* type: string
* example: "user123"
* email:
* type: string
* format: email
* example: "user@example.com"
* name:
* type: string
* example: "John Doe"
* picture:
* type: string
* example: "https://example.com/profile.jpg"
* referralCode:
* type: string
* example: "USER123"
* Error:
* type: object
* properties:
* status:
* type: string
* example: "error"
* message:
* type: string
* code:
* type: string
*/
/**
* @swagger
* tags:
* name: Auth
* description: Authentication endpoints
*/
/**
* @swagger
* /auth:
* post:
* summary: Authenticate with Firebase
* tags: [Auth]
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required:
* - idToken
* properties:
* idToken:
* type: string
* referralCode:
* type: string
* responses:
* 200:
* description: Authentication successful
* content:
* application/json:
* schema:
* type: object
* properties:
* status:
* type: string
* example: success
* data:
* type: object
* properties:
* token:
* type: string
* user:
* $ref: '#/components/schemas/User'
*/
// ... More Swagger documentation for other routes
Configuration Options
initializeAuth({
jwtSecret: 'your-jwt-secret',
jwtExpiresIn: '30d',
magicLinkExpiryMinutes: 15,
rateLimiting: {
windowMs: 15 * 60 * 1000, // 15 minutes
max: 150 // limit each IP to 150 requests per windowMs
},
allowedEmailDomains: ['gmail.com', 'yahoo.com'],
mongodb: {
options: {
useNewUrlParser: true,
useUnifiedTopology: true,
maxPoolSize: 10,
serverSelectionTimeoutMS: 5000,
socketTimeoutMS: 45000
}
}
});
Error Handling
The package includes comprehensive error handling with these error codes:
AUTH_REQUIRED
: Authentication token is missingINVALID_TOKEN
: Invalid or expired tokenINVALID_TOKEN_FORMAT
: Malformed tokenTOKEN_REVOKED
: Token has been blacklistedAUTH_FAILED
: Firebase authentication failedINVALID_EMAIL
: Invalid email formatUNSUPPORTED_EMAIL_DOMAIN
: Email domain not allowedRATE_LIMIT_EXCEEDED
: Too many requestsINVALID_MAGIC_LINK
: Invalid or expired magic linkMONGO_CONNECTION_ERROR
: MongoDB connection failed
Security Features
- Rate limiting for magic link requests
- Token blacklisting for logout
- Email domain validation
- Secure cookie handling
- JWT token validation
- MongoDB connection pooling
- Request validation
- Error handling
- Logging
MongoDB Schemas
The package includes these MongoDB models:
- User
- MagicLink
- BlacklistedToken
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
ISC