sms-extension-1777783872/server/routes/platformPublic.js
2026-03-31 18:08:45 +05:30

104 lines
2.4 KiB
JavaScript

const express = require('express');
const { SESSION_COOKIE_NAME } = require('@gofynd/fdk-extension-javascript/express/constants');
const SessionStorage = require('@gofynd/fdk-extension-javascript/express/session/session_storage');
const { isFdkConfigured } = require('../fdk');
const router = express.Router();
function normalizeText(value) {
return typeof value === 'string' ? value.trim() : '';
}
function getCompanyId(req) {
return normalizeText(
req.get('x-company-id')
|| req.query.company_id
|| req.query.companyId
|| ''
);
}
function getSessionCookieName(companyId) {
return `${SESSION_COOKIE_NAME}_${companyId}`;
}
function clearSessionCookie(res, companyId) {
res.clearCookie(getSessionCookieName(companyId), {
path: '/',
httpOnly: true,
secure: true,
sameSite: 'None',
partitioned: true,
});
}
router.get('/session-status', async (req, res) => {
const companyId = getCompanyId(req);
if (!isFdkConfigured) {
return res.json({
configured: false,
authenticated: false,
companyId,
needsBootstrap: false,
reason: 'fdk_not_configured',
});
}
if (!companyId) {
return res.status(400).json({
configured: true,
authenticated: false,
companyId: '',
needsBootstrap: false,
reason: 'missing_company_id',
});
}
const sessionCookieName = getSessionCookieName(companyId);
const sessionId = normalizeText(req.signedCookies?.[sessionCookieName] || '');
if (!sessionId) {
return res.json({
configured: true,
authenticated: false,
companyId,
needsBootstrap: true,
reason: 'missing_session_cookie',
});
}
try {
const session = await SessionStorage.getSession(sessionId);
const authenticated = Boolean(
session
&& normalizeText(String(session.company_id || '')) === companyId
&& normalizeText(session.access_token || '')
);
if (!authenticated) {
clearSessionCookie(res, companyId);
}
return res.json({
configured: true,
authenticated,
companyId,
needsBootstrap: !authenticated,
reason: authenticated ? 'ok' : 'missing_or_invalid_session',
});
} catch (error) {
return res.status(503).json({
configured: true,
authenticated: false,
companyId,
needsBootstrap: false,
reason: 'session_status_error',
error: error.message || 'Failed to inspect FDK session',
});
}
});
module.exports = router;