/**
Copyright: 2024 Contrast Security, Inc
  Contact: support@contrastsecurity.com
  License: Commercial

  NOTICE: This Software and the patented inventions embodied within may only be
  used as part of Contrast Security’s commercial offerings. Even though it is
  made available through public repositories, use of this Software is subject to
  the applicable End User Licensing Agreement found at
  https://www.contrastsecurity.com/enduser-terms-0317a or as otherwise agreed
  between Contrast Security and the End User. The Software may not be reverse
  engineered, modified, repackaged, sold, redistributed or otherwise used in a
  way not consistent with the End User License Agreement.
*/
/**
 * @module
 */
'use strict';

/** Identifying attacker information */
class Source {
  constructor(req) {
    this.ip = getIp(req);
    this.xForwardedFor = req.headers ? req.headers['x-forwarded-for'] : null;
    this.user = {
      // TODO
      authenticatedId: null
    };
  }

  /**
   * Compare two sources
   * @param {Source}
   */
  equals(source) {
    if (!(source instanceof Source)) {
      return false;
    }

    if (this === source) {
      return true;
    }

    if (this.ip === source.ip) {
      if (this.xForwardedFor === source.xForwardedFor) {
        // FIXME(ehden): this is unused until user-attribution
        //if (this.user === source.user) {
        return true;
        //}
      }
    }

    return false;
  }

  /**
   * Render the object so that it can be stringified and consumed by TeamServer
   */
  toSerializable() {
    return {
      ip: this.ip,
      xForwardedFor: this.xForwardedFor,
      user: this.user
    };
  }
}

function getIp(req) {
  let { ip } = req;

  // couldn't find the ip, so return default local ip
  if (!ip) {
    ip = '::ffff:127.0.0.1';
  }

  return ip;
}

module.exports = Source;
