9d3d431416
- Added account types and privileged account types constants. - Created admin user controller for updating user security fields. - Developed role assignment controller for managing user roles. - Implemented validation middleware for request schemas. - Defined user role and auth session models for database interactions. - Created services for authentication, email notifications, and OTP handling. - Developed OAuth service for Google and Apple authentication. - Added JWT utility functions for token generation and verification. - Implemented comprehensive tests for authentication, session management, and password policies. - Created migration for updating user schema and adding new tables for auth sessions and user identities.
27 lines
1.7 KiB
JavaScript
27 lines
1.7 KiB
JavaScript
const { verifyToken } = require("../utils/jwt.util");
|
|
const { getEffectivePermissions } = require("../services/permission.service");
|
|
const db = require("../models");
|
|
|
|
const authenticate = async (req, res, next) => {
|
|
try {
|
|
const token = req.cookies?.access_token || (req.headers.authorization?.startsWith("Bearer ") ? req.headers.authorization.slice(7) : null);
|
|
if (!token) return res.status(401).json({ success: false, error: { code: "UNAUTHORIZED", message: "Authentication required" } });
|
|
const decoded = verifyToken(token);
|
|
if (!decoded.sub || !decoded.sid || !Number.isInteger(decoded.tokenVersion)) throw new Error("Required claims missing");
|
|
const [user, session] = await Promise.all([
|
|
db.User.findByPk(decoded.sub),
|
|
db.AuthSession.findByPk(decoded.sid),
|
|
]);
|
|
if (!user || user.accountStatus !== "ACTIVE" || user.tokenVersion !== decoded.tokenVersion || !session || session.user_id !== user.id || session.revoked_at || session.expires_at <= new Date() || session.token_version !== user.tokenVersion) {
|
|
return res.status(401).json({ success: false, error: { code: "SESSION_INVALID", message: "Session is no longer valid" } });
|
|
}
|
|
req.user = { id: user.id, sessionId: session.id, firstName: user.firstName, lastName: user.lastName, email: user.email, accountType: user.accountType, accountStatus: user.accountStatus, permissions: await getEffectivePermissions(user.id) };
|
|
next();
|
|
} catch (error) {
|
|
res.clearCookie("access_token");
|
|
return res.status(401).json({ success: false, error: { code: "UNAUTHORIZED", message: "Invalid or expired access token" } });
|
|
}
|
|
};
|
|
|
|
module.exports = { authenticate, requireAuth: authenticate };
|