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