Config-driven authentication system for Express
npm install @mohanmaali/express-auth-corebash
npm install @mohanmaali/express-auth-core
`
Setup
`javascript
import express from "express";
import cookieParser from "cookie-parser";
import { createAuthSystem } from "@mohanmaali/express-auth-core";
const app = express();
app.use(express.json());
app.use(cookieParser());
// Create auth system
const { router, requireAuth } = createAuthSystem({
jwt: {
accessSecret: "your-secret",
refreshSecret: "your-refresh-secret",
accessExpiresIn: "15m",
refreshExpiresIn: "7d",
},
tokenStorage: "cookie", // or "header"
adapters: {
createUser: async function (userData) {
// Save user to database and return user object
return {
id: 1,
email: userData.email,
password: userData.password,
name: userData.name,
};
},
getUserByEmail: async function (email) {
// Fetch user by email from database
return {
id: 1,
email: email,
name: "John Doe",
password: "hashed_password",
};
},
getUserById: async function (id) {
// Fetch user by id from database
return {
id: id,
email: "user@example.com",
name: "John Doe",
password: "hashed_password",
};
},
verifyPassword: async function (user, password) {
// Verify password (use bcrypt)
// const bcrypt = require('bcrypt');
// return await bcrypt.compare(password, user.password);
return true;
},
},
});
// Mount auth routes
app.use("/auth", router);
// Protect routes with middleware
app.get("/profile", requireAuth, (req, res) => {
res.json({ user: req.user });
});
app.listen(3000);
`
Auth Routes
POST /auth/register - Register new user
`json
{ "email": "user@example.com", "password": "pass" }
`
POST /auth/login - Login user
`json
{ "email": "user@example.com", "password": "pass" }
`
GET /auth/me - Get current user profile
Middleware
Use requireAuth to protect routes:
`javascript
app.get("/protected", requireAuth, (req, res) => {
console.log(req.user); // { id: 1, email: "..." }
res.json({ message: "Protected route" });
});
``