npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@dheerajshrivastva-dev/d-auth

v2.0.1

Published

express js middleware for authentication using passportjs

Downloads

133

Readme

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:

| Parameter | Type | Description | |-------------------------|----------|-----------------------------------------------------------------------------| | jwtSecret | string | Secret used for signing JWT tokens. | | mongoUri | string | MongoDB connection URI to store session and user data. | | googleLoginDetails | object | googleClientId, googleClientSecret, googleCallbackURL | | facebookLoginDetails | object | facebookClientId, facebookClientSecret, facebookCallbackURL | | enableGoogleLogin | boolean| Enable or disable Google social login. | | enableFacebookLogin | boolean| Enable or disable Facebook social login. | | deviceTracking | boolean| Track device and IP information for each login session. | | cookieOptions | object | Add cookies configuratins | | nodeMailerConfig | object | Nodemailer options to setup emails | | companyDetails | object | Add 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.