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

universal_authentication

v1.0.4

Published

Seamless and Secure Authentication for Modern Web Applications: Easily integrate OTP-based email verification, Google OAuth, GitHub, Microsoft, and Okta login into your Node.js app. Modular, flexible, and database-agnostic, this package simplifies user au

Readme

Auth with otp and OAuth Package (Google, GitHub, Microsoft and Okta)

All you need is given in this single Readme.md and you will find your code successfully working if you follow it step by step.

This package provides an easy-to-integrate solution for authentication with otp in the user's email, Google OAuth, GitHub, Microsoft and Okta OAuth OAuth login. It allows developers to handle user authentication seamlessly while keeping the logic modular and database-agnostic.

Features

  • Signup and Login Handlers: Pre-configured handlers for signup and login with password hashing and validation.
  • Google, GitHub, Microsoft and Okta OAuth Integration: Easy integration with OAuth 2.0.
  • Modular Design: Configurable for different database setups, allowing you to integrate your own database logic.
  • Functional Approach: Written in a functional style to ensure ease of use and flexibility.
  • OTP-based Login Verification: Stored in Memory, No Database Required
  • Modular Email: Sending using nodemailer

Installation

To use this package, install it via npm:

npm install your-package-name

Setup

1. Custom Configuration:

Create a file called ./config/authConfigs.ts in your project:

Authentication Config (For Signup/Login)

const authConfig: AuthConfig = {
  hashAlgorithm: "crypto",
  generateSecureKey: () => "yourCustomKey",
  checkUserExist: async (email: string) => {
    const user = await User.findOne({ email });
    return user !== null;
  },
  createUser: async (userData: any) => {
    const newUser = new User(userData);
    await newUser.save();
    return newUser;
  },
  createAuthRecord: async (authData: any) => {
    const newAuth = new Auth(authData);
    await newAuth.save();
    console.log("Auth record created:", newAuth);
  },
  getUserByEmail: async (email: string) => {
    return await User.findOne({ email });
  },
  getAuthRecord: async (id: string) => {
    return await Auth.findOne({ userId: id });
  },
  sendEmail: sendEmail,
};

Google OAuth Config

export const googleOAuthConfig: IOAuthConfig = {
  clientId: process.env.GOOGLE_CLIENT_ID,
  clientSecret: process.env.GOOGLE_CLIENT_SECRET,
  redirectUri: "http://localhost:3000/auth/google/callback",
  createUser: async (userData: any) => {
    return await User.create(userData);
  },
  findUserById: async (googleId: string) => {
    return await User.findOne({ googleId });
  },
};

GitHub OAuth Config

export const githubOAuthConfig: IOAuthConfig = {
  clientId: process.env.GITHUB_CLIENT_ID,
  clientSecret: process.env.GITHUB_CLIENT_SECRET,
  redirectUri: "http://localhost:3000/auth/github/callback",
  createUser: async (userData: any) => {
    return await User.create(userData);
  },
  findUserById: async (githubId: string) => {
    return await User.findOne({ githubId });
  },
};

Microsoft OAuth Config

export const microsoftOAuthConfig: IOAuthConfig = {
  clientId: process.env.MICROSOFT_CLIENT_ID,
  clientSecret: process.env.MICROSOFT_CLIENT_SECRET,
  redirectUri: "http://localhost:3000/auth/microsoft/callback",
  createUser: async (userData: any) => {
    return await User.create(userData);
  },
  findUserById: async (microsoftId: string) => {
    return await User.findOne({ microsoftId });
  },
};

Okta OAuth Config

export const oktaOAuthConfig: IOAuthConfig = {
  clientId: process.env.OKTA_CLIENT_ID,
  clientSecret: process.env.OKTA_CLIENT_SECRET,
  redirectUri: "http://localhost:3000/auth/okta/callback",
  createUser: async (userData: any) => {
    return await User.create(userData);
  },
  findUserById: async (oktaId: string) => {
    return await User.findOne({ oktaId });
  },
};

2. Main File (index.ts):

Create a file called index.ts in your project:

import express from "express";
import {
  authConfig,
  googleOAuthConfig,
  githubOAuthConfig,
  microsoftOAuthConfig,
  oktaOAuthConfig,
} from "your-auth-config-path";
import {
  signupHandler,
  loginHandler,
  initiateLogin,
  handleOAuthCallback,
  AuthConfig,
  IOAuthConfig,
  sendEmail,
  verifyOtpHandler,
} from "your-package-name";

const app = express();
const port = process.env.PORT || 3000;
app.use(express.json());

// Signup Route
app.post("/signup", async (req, res) => {
  const { email, password, name } = req.body;
  const result = await signupHandler(email, password, name, authConfig);
  res.status(result.status).json(result);
});

// Login Route (Generates OTP)
app.post("/login", async (req: Request, res: Response) => {
  const { email, password } = req.body;
  const result = await loginHandler(email, password, authConfig);
  res.status(result.status).json(result);
});

// OTP Verification Route
app.post("/verify-otp", async (req: Request, res: Response) => {
  const { email, otp } = req.body;
  const result = await verifyOtpHandler(email, otp);
  res.status(result.status).json(result);
});

// Google OAuth Routes
app.get("/auth/google", (req: Request, res: Response) => {
  const googleLoginUrl = initiateLogin(
    "google",
    googleOAuthConfig.clientId,
    googleOAuthConfig.redirectUri
  );
  res.redirect(googleLoginUrl);
});

app.get("/auth/google/callback", async (req: Request, res: Response) => {
  const { code } = req.query;
  const result = await handleOAuthCallback(
    code as string,
    "google",
    googleOAuthConfig
  );
  res.status(result.status).json(result);
});

// GitHub OAuth Routes
app.get("/auth/github", (req: Request, res: Response) => {
  const githubLoginUrl = initiateLogin(
    "github",
    githubOAuthConfig.clientId,
    githubOAuthConfig.redirectUri
  );
  res.redirect(githubLoginUrl);
});

app.get("/auth/github/callback", async (req: Request, res: Response) => {
  const { code } = req.query;
  const result = await handleOAuthCallback(
    code as string,
    "github",
    githubOAuthConfig
  );
  res.status(result.status).json(result);
});

// Microsoft OAuth Routes
app.get("/auth/microsoft", (req: Request, res: Response) => {
  const microsoftLoginUrl = initiateLogin(
    "microsoft",
    microsoftOAuthConfig.clientId,
    microsoftOAuthConfig.redirectUri
  );
  res.redirect(microsoftLoginUrl);
});

app.get("/auth/microsoft/callback", async (req: Request, res: Response) => {
  const { code } = req.query;
  const result = await handleOAuthCallback(
    code as string,
    "microsoft",
    microsoftOAuthConfig
  );
  res.status(result.status).json(result);
});

// Okta OAuth Routes
app.get("/auth/okta", (req: Request, res: Response) => {
  const oktaLoginUrl = initiateLogin(
    "okta",
    oktaOAuthConfig.clientId,
    oktaOAuthConfig.redirectUri
  );
  res.redirect(oktaLoginUrl);
});

app.get("/auth/okta/callback", async (req: Request, res: Response) => {
  const { code } = req.query;
  const result = await handleOAuthCallback(
    code as string,
    "okta",
    oktaOAuthConfig
  );
  res.status(result.status).json(result);
});

app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});
  1. Make the model files:

Create a file called ./models/User.models.ts in your project:

import mongoose, { Document, Schema } from "mongoose";

export interface IUser extends Document {
  email?: string;
  providerId?: string;
  provider?: "google" | "github" | "microsoft" | "okta";
  username?: string;
  name?: string;
  profile?: string;
  isVerified?: boolean;
}

const UserSchema: Schema = new Schema(
  {
    email: { type: String, required: false },
    providerId: { type: String, required: false, unique: true },
    provider: { type: String, required: false },
    username: { type: String, required: false },
    name: { type: String, required: false },
    profile: { type: Object },
    isVerified: { type: Boolean, default: false },
  },
  { timestamps: true }
);

const User = mongoose.model<IUser>("User", UserSchema);
export default User;

Create a file called ./models/Auth.models.ts in your project:

import mongoose, { Document, Schema } from "mongoose";
import { IUser } from "./User.model";

interface IAuth extends Document {
  userId: IUser["_id"];
  ipAddress: string;
  lastLogin: Date;
  password: string;
  secureKey: string;
}

const AuthSchema: Schema = new Schema({
  userId: { type: Schema.Types.ObjectId, ref: "User", required: true },
  ipAddress: { type: String, required: true },
  lastLogin: { type: Date, default: Date.now },
  password: { type: String, required: true },
  secureKey: { type: String, required: true },
});

const Auth = mongoose.model<IAuth>("Auth", AuthSchema);
export default Auth;
  1. Don't forget to Create the database connection file and below is the example to create one:

Create a file called ./config/database.ts in your project:

import mongoose from "mongoose";
import dotenv from "dotenv";
dotenv.config();

const mongoURI: string = process.env.MONGODB_URI as string;

const connectDB = async () => {
  try {
    await mongoose.connect(mongoURI);
    console.log("MongoDB connected successfully");
  } catch (error) {
    console.error("Error connecting to MongoDB:", error);
    process.exit(1);
  }
};

export default connectDB;

Environment Variables

Make sure to set up the following environment variables in your .env file:

GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret
GITHUB_CLIENT_ID=your-github-client-id
GITHUB_CLIENT_SECRET=your-github-client-secret
MICROSOFT_CLIENT_ID=your-microsoft-client-id
MICROSOFT_CLIENT_SECRET=your-microsoft-client-secret
OKTA_CLIENT_ID=your-okta-client-id
OKTA_CLIENT_SECRET=your-okta-client-secret
REDIRECT_URI=your-callback-uri
[email protected]
EMAIL_PASSWORD=your-app-password

Customizing the Package

You can customize the logic for creating users, authentication records, and finding users by OAuth ID by implementing your own database logic. In the config file, provide your own functions for createUser and findUserByOAuthId.

License

This package is licensed under the MIT License. See the LICENSE file for more details.

Author

Rehan Shah