UNPKG

@mridang/nestjs-auth

Version:

A comprehensive Auth.js integration for NestJS applications with TypeScript support, framework-agnostic HTTP adapters, and role-based access control

93 lines 3.11 kB
/** * Concrete runtime object that implements the public `Session` shape. * It encapsulates mapping from the underlying core session into the * public surface while preserving any app-augmented fields placed on * the core session by callbacks. */ export class AuthSession { /** The authenticated user, or null/undefined when absent. */ user; /** ISO-8601 timestamp indicating when the session expires. */ expires; /** * Factory: build from a core session. Returns null when no session. */ static fromCore(core) { return core ? new AuthSession(core) : null; } /** * Construct from a core session or a partial public session. Copies * base fields and safely preserves any extra fields present on the * source object (e.g., tokens added by app callbacks). */ constructor(src) { const srcAsRec = toRecord(src); const srcUser = toRecord(srcAsRec?.user); if (srcUser) { const mergedUser = {}; // copy base fields if present if ('name' in srcUser) mergedUser.name = srcUser.name; if ('email' in srcUser) mergedUser.email = srcUser.email; if ('image' in srcUser) mergedUser.image = srcUser.image; // copy any app-augmented user fields copyExtraProps(srcUser, mergedUser, new Set(['name', 'email', 'image'])); this.user = mergedUser; } else { this.user = null; } // expires if (srcAsRec && 'expires' in srcAsRec && typeof srcAsRec.expires === 'string') { this.expires = srcAsRec.expires; } // copy any app-augmented session fields (tokens, errors, etc.) if (srcAsRec) { copyExtraProps(srcAsRec, this, new Set(['user', 'expires'])); } } /** * Return a plain JSON object conforming to the public `Session`. */ toJSON() { const out = {}; if (typeof this.user !== 'undefined') out.user = this.user; if (typeof this.expires !== 'undefined') out.expires = this.expires; copyExtraProps(this, out, new Set(['user', 'expires'])); return out; } /** * Shallow merge in additional fields and return `this`. */ with(patch) { const patchRec = toRecord(patch); if (patchRec) { copyExtraProps(patchRec, this, new Set([])); } return this; } } /* helpers (no `any`) */ function isObjectRecord(value) { return typeof value === 'object' && value !== null; } function toRecord(value) { return isObjectRecord(value) ? value : null; } function copyExtraProps(source, target, exclude) { const sDesc = Object.getOwnPropertyDescriptors(source); for (const key of Reflect.ownKeys(sDesc)) { if (exclude.has(key)) continue; const desc = sDesc[key]; if (desc) Object.defineProperty(target, key, desc); } } //# sourceMappingURL=auth.session.js.map