UNPKG

@sap/xssec

Version:

XS Advanced Container Security API for node.js

123 lines (102 loc) 3.12 kB
const { CORRELATIONID_HEADERS, FORWARDED_CLIENTCERTIFICATE_HEADER } = require('../util/constants'); const { extractPemFromClientCertHeader } = require('../util/certs'); /** * @typedef {import('../service/Service')} Service * @typedef {import('../token/Token')} Token * @typedef {import('../util/Types').SecurityContextConfig} SecurityContextConfig */ /** * @template {Service} S - The type of the service. * @template {Token} T - The type of the token. */ class SecurityContext { /** @type {S} */ #service; /** @type {T} */ #token; /** @type {SecurityContextConfig} */ config; /** * @param {S} service - The service instance. * @param {T} token - The token instance. * @param {SecurityContextConfig} contextConfig - The security context configuration. */ constructor(service, token, contextConfig) { this.#service = service; this.#token = token; this.config = contextConfig; } /** * The Service instance on which this SecurityContext has been created. * @returns {S} service */ get service() { return this.#service; } /** * @param {S} service */ set service(service) { this.#service = service; } /** * The Token instance from which this SecurityContext has ben created. * @returns {T} token */ get token() { return this.#token; } /** * @param {T} token */ set token(token) { this.#token = token; } // Methods for backwards-compatibility getAppToken() { return this.token.jwt; } getEmail() { return this.getUserInfo().email; } getExpirationDate() { return this.token.expirationDate; } getFamilyName() { return this.getUserInfo().familyName; } getGivenName() { return this.getUserInfo().givenName; } getGrantType() { return this.token.grantType; } getLogonName() { return this.getUserInfo().logonName } getUserInfo() { return { email: this.token.email, familyName: this.token.familyName, givenName: this.token.givenName, logonName: this.token.payload.user_name } } getTokenInfo() { return this.token; } /** * Tries to fill up missing properties of the security context configuration from the req object in the configuration. * @param {SecurityContextConfig} contextConfig */ static buildContextConfig(contextConfig) { let { req } = contextConfig; for (let i = 0; contextConfig.correlationId == null && i < CORRELATIONID_HEADERS.length; i++) { contextConfig.correlationId = req?.headers?.[CORRELATIONID_HEADERS[i]]; } contextConfig.clientCertificatePem ??= extractPemFromClientCertHeader(req?.headers?.[FORWARDED_CLIENTCERTIFICATE_HEADER]); contextConfig.jwt ??= req?.headers?.authorization?.split(' ')[1]; contextConfig.skipValidation ??= false; } } module.exports = SecurityContext;