UNPKG

webssh2-server

Version:

A Websocket to SSH2 gateway using xterm.js, socket.io, ssh2

87 lines (86 loc) 2.62 kB
// app/middleware/sso.middleware.ts // Single Sign-On (SSO) authentication middleware import { DEFAULTS } from '../constants.js'; /** * Create SSO authentication middleware * @param config - Application configuration * @returns Express middleware handler */ export function createSSOAuthMiddleware(config) { return (req, _res, next) => { if (!isPost(req)) { next(); return; } if (containsSsoHeaders(req) || hasCredentialsInBody(req)) { next(); return; } if (shouldApplyDefaults(config)) { applyDefaultCredentials(req, config); } next(); }; } const isPost = (req) => req.method === 'POST'; const containsSsoHeaders = (req) => { const usernameHeader = req.headers[DEFAULTS.SSO_HEADERS.USERNAME]; const passwordHeader = req.headers[DEFAULTS.SSO_HEADERS.PASSWORD]; return usernameHeader != null && passwordHeader != null; }; const hasCredentialsInBody = (req) => { const body = normalizeBody(req.body); if (body === undefined) { return false; } const username = toFilledString(body['username']); const password = toFilledString(body['password']); return username !== undefined && password !== undefined; }; const shouldApplyDefaults = (config) => { if (!config.sso.enabled) { return false; } return toFilledString(config.user.name) !== undefined && toFilledString(config.user.password) !== undefined; }; const applyDefaultCredentials = (req, config) => { const enrichedRequest = req; const body = ensureMutableBody(enrichedRequest); const currentUsername = toFilledString(body['username']); const currentPassword = toFilledString(body['password']); if (currentUsername === undefined) { body['username'] = config.user.name; } if (currentPassword === undefined) { body['password'] = config.user.password; } }; const ensureMutableBody = (req) => { const normalized = normalizeBody(req.body); if (normalized !== undefined) { req.body = normalized; return normalized; } const newBody = {}; req.body = newBody; return newBody; }; const normalizeBody = (body) => { if (body === undefined || body === null) { return undefined; } if (typeof body === 'object' && !Array.isArray(body)) { return body; } return undefined; }; const toFilledString = (value) => { if (typeof value !== 'string') { return undefined; } if (value === '') { return undefined; } return value; };