"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _utils = require("@rivalis/utils");

var _fastJwt = require("fast-jwt");

var _env = _interopRequireDefault(require("../utils/env"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

class AuthService {
  /** @private */

  /**
   * @private
   * @type {string}
   */

  /**
   * @private
   * @type {import('fast-jwt').SignerSync}
   */

  /**
   * @private
   * @type {import('fast-jwt').VerifierSync}
   */
  constructor() {
    _defineProperty(this, "logger", _utils.Logger.getLogger('auth'));

    _defineProperty(this, "rootPassword", (0, _env.default)('CONSOLE_API_ROOT_PASSWORD', 'admin'));

    _defineProperty(this, "signer", null);

    _defineProperty(this, "verifier", null);

    const variables = {
      JWT_PRIVATE_KEY: (0, _env.default)('CONSOLE_API_AUTH_RS256_PRIVATE_KEY', null),
      JWT_PUBLIC_KEY: (0, _env.default)('CONSOLE_API_AUTH_RS256_PUBLIC_KEY', null)
    };

    if (variables.JWT_PUBLIC_KEY === null) {
      this.logger.error('[CONSOLE_API_AUTH_RS256_PUBLIC_KEY] variable is missing');
      process.exit();
    }

    if (variables.JWT_PRIVATE_KEY === null) {
      this.logger.error('[CONSOLE_API_AUTH_RS256_PRIVATE_KEY] variable is missing');
      process.exit();
    }

    this.signer = (0, _fastJwt.createSigner)({
      algorithm: 'RS256',
      key: variables.JWT_PRIVATE_KEY
    });
    this.verifier = (0, _fastJwt.createVerifier)({
      key: variables.JWT_PUBLIC_KEY
    });
  }

  signIn(password) {
    if (password !== this.rootPassword) {
      throw new Error('invalid password');
    }

    return this.issueJwtToken({
      scope: []
    }, 60 * 120, 'admin');
  }

  extractJWT(authHeader) {
    if (typeof authHeader !== 'string') {
      return '';
    }

    let jwt = authHeader.split(' ')[1];
    return jwt || '';
  }

  verify(token, scope = []) {
    try {
      this.verifier(token);
    } catch (error) {
      return false;
    }

    return true;
  }

  signRoomToken(instanceId, roomId, payload = {}) {}
  /**
   * 
   * @param {Object<string,string>} payload 
   * @param {number} expiresIn 
   * @param {string} subject 
   * @param {string} audience 
   * @param {string} uid 
   * @param {string} issuer 
   * @returns {string}
   */


  issueJwtToken(payload = {}, expiresIn = 0, subject = null, audience = null, uid = null, issuer = null) {
    const tokenPayload = { ...payload
    };

    if (subject !== null) {
      tokenPayload['sub'] = subject;
    }

    if (audience !== null) {
      tokenPayload['aud'] = audience;
    }

    if (typeof expiresIn !== 'number') {
      expiresIn = 0;
    }

    tokenPayload['exp'] = Math.floor(new Date().getTime() / 1000) + expiresIn;
    tokenPayload['jti'] = uid !== null ? uid : (0, _utils.generateId)(16);
    tokenPayload['iss'] = issuer !== null ? issuer : '@rivalis/console';
    return this.signer(tokenPayload);
  }

}
/** @type {AuthService} */


let instance = null;

AuthService.getInstance = () => {
  if (instance === null) {
    instance = new AuthService();
  }

  return instance;
};

var _default = AuthService;
exports.default = _default;