
Security News
Node.js TSC Declines to Endorse Feature Bounty Program
The Node.js TSC opted not to endorse a feature bounty program, citing concerns about incentives, governance, and project neutrality.
universal_authentication
Advanced tools
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
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.
To use this package, install it via npm:
npm install your-package-name
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 });
},
};
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}`);
});
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;
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;
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_USER=your-email@gmail.com
EMAIL_PASSWORD=your-app-password
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
.
This package is licensed under the MIT License. See the LICENSE file for more details.
Rehan Shah
FAQs
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
The npm package universal_authentication receives a total of 7 weekly downloads. As such, universal_authentication popularity was classified as not popular.
We found that universal_authentication demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
The Node.js TSC opted not to endorse a feature bounty program, citing concerns about incentives, governance, and project neutrality.
Research
Security News
A look at the top trends in how threat actors are weaponizing open source packages to deliver malware and persist across the software supply chain.
Security News
ESLint now supports HTML linting with 48 new rules, expanding its language plugin system to cover more of the modern web development stack.