const { getSessionId, getUserId, getProfileId } = require('../utils/sessionUtils'); const { client_logger } = require('../utils/analyticsLogger'); const { cookiesOptions } = require('../config/cookiesOptions'); const MongoDB = require("../mongoDB.js"); const { ObjectId } = require("mongodb"); 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 res.redirect('/login'); } if (!ObjectId.isValid(session_id) || !ObjectId.isValid(user_sid)) { return res.redirect('/login'); } 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 res.redirect('/login'); } res.cookie('profile_id', latestProfile._id, cookiesOptions); profile_id = latestProfile._id; } req.profileInfo = { _id: profile_id }; if (!userInfo) return res.redirect('/login'); client_logger.capture({ distinctId: user_sid, event: 'server@' + req.method + '@' + req.originalUrl, }); next(); } catch (error) { console.error("Session checker error", error); return res.redirect('/login'); } }; module.exports = sessionChecker;