UNPKG

@4players/odin

Version:

A cross-platform SDK enabling developers to integrate real-time VoIP chat technology into their projects

91 lines (90 loc) 2.66 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.RoomToken = void 0; const json_1 = require("./json"); const odin_event_target_1 = require("./odin-event-target"); const odin_common_1 = require("@4players/odin-common"); /** * The RoomToken class represents a parsed and validated token with an expiration mechanism. * It is used to extract claims and manage token expiration events. */ class RoomToken extends odin_event_target_1.OdinEventTarget { constructor(base64, expiryOffset = 30000) { super(); this.base64 = base64; this.expiryOffset = expiryOffset; try { this._parsed = odin_common_1.TokenClaimsSchema.parse((0, json_1.parseJwt)(base64)); } catch (e) { console.error(e); throw new Error('Token Creation failed'); } if (this.exp) { const tokenLifeTime = this.exp * 1000 - Date.now(); // Prevents that the offset can be bigger then the expiry time. if (this.expiryOffset >= tokenLifeTime) { this.expiryOffset = tokenLifeTime - 10000; } const emitTime = tokenLifeTime - this.expiryOffset; setTimeout(() => { this.dispatchEvent(new odin_event_target_1.OdinEvent('TokenExpired', { token: this, })); }, emitTime); } } get parsed() { return this._parsed; } get address() { return this.parsed.adr; } get customerId() { return this.parsed.cid; } get exp() { return this.parsed.exp; } get userId() { return this.parsed.uid; } get rooms() { const roomId = this.parsed.rid; let rooms = []; if (typeof roomId === 'string') { rooms = [roomId]; } else { rooms = roomId; } return rooms; } get isMultiRoom() { return this.rooms.length > 1; } /** * Returns the audience. If the audience is undefined its unrestricted. * If the audience is an empty array, it has no audience. */ get audience() { if (!this._parsed.aud) { return []; } if (typeof this._parsed.aud === 'string') { return [this._parsed.aud]; } else { return this._parsed.aud; } } /** * Returns true when the token is expired */ isExpired() { if (!this.exp) return false; return Math.floor(Date.now() / 1000) >= this.exp; } } exports.RoomToken = RoomToken;