const { getSessionId, getUserId, getProfileId } = require('../utils/sessionUtils'); const { client_logger } = require('../utils/analyticsLogger'); const { getCookiesOptions } = require('../config/cookiesOptions'); const MongoDB = require("../mongoDB.js"); const { ObjectId } = require("mongodb"); const shouldReturnJson = (req) => { const accept = String(req?.headers?.accept || "").toLowerCase(); const contentType = String(req?.headers?.["content-type"] || "").toLowerCase(); return !!req?.headers?.origin || accept.includes("application/json") || contentType.includes("application/json"); }; const rejectUnauthorized = (req, res) => { if (shouldReturnJson(req)) { return res.status(401).json({ status: "Unauthorized" }); } return res.redirect('/login'); }; const sessionChecker = async (req, res, next) => { try { const session_id = getSessionId(req); const user_sid = getUserId(req); let profile_id = getProfileId(req); if (!session_id || !user_sid) { return rejectUnauthorized(req, res); } if (!ObjectId.isValid(session_id) || !ObjectId.isValid(user_sid)) { return rejectUnauthorized(req, res); } const DB = await MongoDB.getDB; const userInfo = await DB.checkSessionOnDB(session_id, user_sid); req.userInfo = userInfo; if (!await DB.getProfileCache(profile_id)) { const latestProfile = await DB.latestProfile(user_sid); if (!latestProfile || !latestProfile._id) { return rejectUnauthorized(req, res); } res.cookie('profile_id', latestProfile._id, getCookiesOptions(req)); profile_id = latestProfile._id; } req.profileInfo = { _id: profile_id }; if (!userInfo) return rejectUnauthorized(req, res); client_logger.capture({ distinctId: user_sid, event: 'server@' + req.method + '@' + req.originalUrl, }); next(); } catch (error) { console.error("Session checker error", error); return rejectUnauthorized(req, res); } }; module.exports = sessionChecker;