2.0.1 • Published 8 months ago

@dheerajshrivastva-dev/d-auth v2.0.1

Weekly downloads
-
License
MIT
Repository
github
Last release
8 months ago

D-Auth an Express Middleware

An all-in-one authentication middleware for Express.js applications that supports Username password, OAuth with Google, rate limiting, session management, and more. Designed to be flexible and secure, this middleware can be integrated into any Express app by simply passing the server instance at start.

Features

  • Local and Google OAuth login: Seamless integration of traditional login and social login using Google.
  • Rate limiting: Protect against abuse with predefined rate limits based on IP and device fingerprints.
  • Secure session management: Persistent session management with mongodb connect.
  • MongoDB integration: MongoDB is required to store user sessions and authentication data.
  • Users query: It export user management routes that can be used to do simple user based modificatiom
  • Admin user role: It has admin user role that can create, update and dekete users. User has to be verified admin to perform this. Use authenticate middleware from d-auth to authenticate user queries.
  • Forget password: User can forget password with otp, otp send using nodeMailer

Table of Contents

  1. Installation
  2. Usage
  3. Configuration
  4. Parameters
  5. Examples
  6. Route Structure

Installation

You can install the middleware via npm:

npm i @dheerajshrivastva-dev/d-auth

Note: MongoDB is required to store user data and session information. Make sure you have a MongoDB instance running and available.

Usage

Basic Usage

Here's how to integrate the middleware into your Express app:

import express, { Express, Request, Response } from "express";
import { AuthenticatedRequest, authenticateApiMiddleware, dAuthMiddleware } from "./middleware/authMiddleware";
import dotenv from "dotenv";
import path from 'path';

dotenv.config();

const app: Express = express();
const port = process.env.PORT || 3000;

dAuthMiddleware(app, {
  enableFacebookLogin: false,
  enableGoogleLogin: true,
  mongoDbUri: process.env.MONGO_URI!,
  sessionSecret: process.env.SESSION_SECRET!,
  authRouteinitials: "/auth"
});

app.get("/", (req: Request, res: Response) => {
  res.send("Express + TypeScript Server");
});

app.use('/api', authenticateApiMiddleware);

// Optional
app.use('/api', userRouter);

// Define routes
app.get('/api/public/data', (req: Request, res: Response) => {
  res.send('This is a public route');
});

app.get('/api/private/data', (req: AuthenticatedRequest, res: Response) => {
  // Only authenticated users will reach here
  res.send(`Hello, ${req.user.email}`);
});

app.get('/auth/privacy-policy', (req: express.Request, res: express.Response) => {
  res.sendFile(path.join(__dirname, 'public', 'privacy-policy.html'));
});

app.get('/auth/terms-of-service', (req: express.Request, res: express.Response) => {
  res.sendFile(path.join(__dirname, 'public', 'terms-of-service.html'));
});

app.listen(port, () => {
  console.log(`[server]: Server is running at http://localhost:${port}`);
});

Do not forget to export env "JWT_SECRET"

Middleware Configuration

Pass a configuration object to the middleware to control behavior:

dAuthMiddleware(app, {
  enableFacebookLogin: false,
  enableGoogleLogin: true,
  mongoDbUri: process.env.MONGO_URI!,
  sessionSecret: process.env.SESSION_SECRET!,
  authRouteinitials: "/auth",
  companyDetails: {
    name: "D-Auth Tester",
    website: "https://d-auth.com",
    contact: "https://d-auth.com/contact",
    privacyPolicy: "https://d-auth.com/privacy-policy",
    termsOfService: "https://d-auth.com/terms-of-service",
    support: "https://d-auth.com/support",
    address: "123 Main Street, USA"
  },
  nodeMailerConfig: {
    auth: {
      user: process.env.EMAIL_USERNAME!,
      pass: process.env.EMAIL_PASSWORD!,
    },
    service: 'gmail',
    host: 'smtp.gmail.com',
    port: 587,
    secure: true
  }
});

Configuration

You can customize the behavior of the middleware by providing the following configuration options:

ParameterTypeDescription
jwtSecretstringSecret used for signing JWT tokens.
mongoUristringMongoDB connection URI to store session and user data.
googleLoginDetailsobjectgoogleClientId, googleClientSecret, googleCallbackURL
facebookLoginDetailsobjectfacebookClientId, facebookClientSecret, facebookCallbackURL
enableGoogleLoginbooleanEnable or disable Google social login.
enableFacebookLoginbooleanEnable or disable Facebook social login.
deviceTrackingbooleanTrack device and IP information for each login session.
cookieOptionsobjectAdd cookies configuratins
nodeMailerConfigobjectNodemailer options to setup emails
companyDetailsobjectAdd company details

Examples

Local Login with JWT Authentication

import express from 'express';
import { dAuthMiddleware, authenticateMiddleware } from '@your-username/express-middleware';

const app = express();

dAuthMiddleware(app, {
  jwtSecret: 'your-jwt-secret',
  mongoUri: 'mongodb://localhost:27017/myapp',
  enableGoogleLogin: false,
  cookieOptions: {
    httpOnly: true,
    secure: true,
    sameSite: 'none',
    path: '/',
    maxAge: 24 * 60 * 60 * 1000,
  },
  companyDetails: {
    name: "D-Auth Tester",
    website: "https://d-auth.com",
    contact: "https://d-auth.com/contact",
    privacyPolicy: "https://d-auth.com/privacy-policy",
    termsOfService: "https://d-auth.com/terms-of-service",
    support: "https://d-auth.com/support",
    address: "123 Main Street, USA"
  },
  nodeMailerConfig: {
    auth: {
      user: process.env.EMAIL_USERNAME!,
      pass: process.env.EMAIL_PASSWORD!,
    },
    service: 'gmail',
    host: 'smtp.gmail.com',
    port: 587,
    secure: true
  }
});

app.post('/login', authenticateMiddleware, (req, res) => {
  const user = req.user;
  res.json({ message: 'Login successful', user });
});

app.listen(3000, () => {
  console.log('Server is running');
});

Google OAuth Login

app.get('/auth/google', passport.authenticate('google', { scope: ['profile', 'email'] }));

app.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/' }),
  function(req, res) {
    // Successful authentication
    res.redirect('/');
  });

Route Structure

To properly utilize the middleware, ensure that you leave the following routes empty:

  • /auth/*: These routes are used for handling authentication requests and should be implemented according to your application's needs.

By leaving them empty, you allow the middleware to manage authentication flows without conflicts.

2.0.1

8 months ago

1.0.4

10 months ago

2.0.0

10 months ago

1.0.3

1 year ago

1.0.2

1 year ago

1.0.1

1 year ago

1.0.0

1 year ago

0.0.2

1 year ago

0.0.1

1 year ago