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 🙏

© 2024 – Pkg Stats / Ryan Hefner

@dheerajshrivastva-dev/d-auth

v1.0.2

Published

express js middleware for authentication using passportjs

Downloads

255

Readme

Logo D-Auth an Express Middleware

An all-in-one authentication middleware for Express.js applications that supports JWT-based authentication, OAuth with Google, email-password login, refresh tokens, 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.

Features

  • Local and Google OAuth login: Seamless integration of traditional login and social login using Google.
  • JWT-based authentication: Secure short-lived and long-lived tokens for session handling.
  • One user, one session: Ensures users only have one active session at a time.
  • Device tracking: Track devices, IP addresses, and session data.
  • Rate limiting: Protect against abuse with predefined rate limits based on IP and device fingerprints.
  • CAPTCHA protection: Coming soon - CAPTCHA verification triggered after too many failed login attempts.
  • Secure session management: Persistent session management with refresh tokens.
  • MongoDB integration: MongoDB is required to store user sessions and authentication data.

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, {
  mongoDbUri: process.env.MONGO_URI!,
  sessionSecret: process.env.SESSION_SECRET!,
  enableGoogleLogin: true,
  enableFacebookLogin: true,
  googleClientId: process.env.GOOGLE_CLIENT_ID! || "",
  googleClientSecret: process.env.GOOGLE_CLIENT_SECRET! || "",
  googleCallbackURL: process.env.GOOGLE_CALLBACK_URL! || "",
  facebookAppId: process.env.FACEBOOK_APP_ID! || "",
  facebookAppSecret: process.env.FACEBOOK_APP_SECRET! || "",
  facebookCallbackURL: process.env.FACEBOOK_CALLBACK_URL! || "",
});

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

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

// 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, {
  jwtSecret: 'your-jwt-secret',
  mongoUri: 'mongodb-connection-uri',
  googleClientId: 'your-google-client-id',
  googleClientSecret: 'your-google-client-secret',
  enableGoogleLogin: true,
  enableFacebookLogin: false,  // Enable/disable social login providers
});

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. | | googleClientId | string | Google OAuth client ID for social login. | | googleClientSecret | string | Google OAuth client secret. | | 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. |

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,
});

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('/');
  });

JWT Refresh Token

app.post('/refresh-token', (req, res) => {
  const { refreshToken } = req.body;
  const newTokens = generateTokens(refreshToken);
  res.json(newTokens);
});

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.