<commit_before>import querystring from 'querystring';

import { HmisApiRegistry } from './apiRegistry';

const OAUTH_BASE_URL = 'https://www.hmislynk.com/hmis-authorization-service/rest';

export class HmisClient {
  constructor(userId, serviceConfig, registry, usersCollection) {
    this.userId = userId;
    this.serviceConfig = serviceConfig;
    this.registry = registry;
    this.usersCollection = usersCollection;
    this.authData = undefined;
  }

  api(name) {
    const Cls = this.registry.getApi(name);
    if (!this.hasValidAccessToken()) {
      this.renewAccessToken();
    }
    return new Cls(this.serviceConfig.appId, this.getAccessToken());
  }

  getAccessToken() {
    if (!this.authData) {
      this.loadAuthData();
    }
    return this.authData.accessToken;
  }

  hasValidAccessToken() {
    if (!this.authData) {
      this.loadAuthData();
    }

    const currentTimestamp = new Date().getTime();

    return this.authData.expiresAt > currentTimestamp;
  }

  renewAccessToken() {
    this.loadAuthData();

    let responseContent = '';
    try {
      // Request an access token
      const { appId, appSecret } = this.serviceConfig;

      const urlPath = `${OAUTH_BASE_URL}/token/`;
      const queryParams = {
        grant_type: 'refresh_token',
        refresh_token: this.authData.refreshToken,
        redirect_uri: OAuth._redirectUri('HMIS', this.serviceConfig),
      };
      const url = `${urlPath}?${querystring.stringify(queryParams)}`;

      const authorization = new Buffer(`${appId}:${appSecret}` || '');

      responseContent = HTTP.post(url, {
        headers: {
          'X-HMIS-TrustedApp-Id': appId,
          Authorization: authorization.toString('base64'),
          Accept: 'application/json',
          'Content-Type': 'application/json',
        },
      }).content;
    } catch (err) {
      throw _.extend(
        new Error(`Failed to complete OAuth handshake with HMIS. ${err.message}`),
        { response: err.response }
      );
    }

    const parsedResponse = JSON.parse(responseContent);
    const { accessToken, expiresIn, refreshToken } = parsedResponse.oAuthAuthorization;

    this.authData.accessToken = accessToken;
    this.authData.refreshToken = refreshToken;
    this.authData.expiresAt = new Date().getTime() + expiresIn * 1000;

    this.saveAuthData();

    return expiresIn * 1000;
  }

  loadAuthData() {
    const user = this.usersCollection.findOne({ _id: this.userId });
    if (!user) {
      throw new Meteor.Error('hmis.api', `User ${this.userId} not found`);<commit_msg>add temp logging to hmis auth token expiry<commit_after>import querystring from 'querystring';

import { HmisApiRegistry } from './apiRegistry';

const OAUTH_BASE_URL = 'https://www.hmislynk.com/hmis-authorization-service/rest';

export class HmisClient {
  constructor(userId, serviceConfig, registry, usersCollection) {
    this.userId = userId;
    this.serviceConfig = serviceConfig;
    this.registry = registry;
    this.usersCollection = usersCollection;
    this.authData = undefined;
  }

  api(name) {
    const Cls = this.registry.getApi(name);
    if (!this.hasValidAccessToken()) {
      this.renewAccessToken();
    }
    return new Cls(this.serviceConfig.appId, this.getAccessToken());
  }

  getAccessToken() {
    if (!this.authData) {
      this.loadAuthData();
    }
    return this.authData.accessToken;
  }

  hasValidAccessToken() {
    if (!this.authData) {
      this.loadAuthData();
    }

    const currentTimestamp = new Date().getTime();

    console.log('token expire left', this.authData.expiresAt - currentTimestamp);

    return this.authData.expiresAt > currentTimestamp;
  }

  renewAccessToken() {
    console.log('renewing access token');
    this.loadAuthData();

    let responseContent = '';
    try {
      // Request an access token
      const { appId, appSecret } = this.serviceConfig;

      const urlPath = `${OAUTH_BASE_URL}/token/`;
      const queryParams = {
        grant_type: 'refresh_token',
        refresh_token: this.authData.refreshToken,
        redirect_uri: OAuth._redirectUri('HMIS', this.serviceConfig),
      };
      const url = `${urlPath}?${querystring.stringify(queryParams)}`;

      const authorization = new Buffer(`${appId}:${appSecret}` || '');

      responseContent = HTTP.post(url, {
        headers: {
          'X-HMIS-TrustedApp-Id': appId,
          Authorization: authorization.toString('base64'),
          Accept: 'application/json',
          'Content-Type': 'application/json',
        },
      }).content;
    } catch (err) {
      throw _.extend(
        new Error(`Failed to complete OAuth handshake with HMIS. ${err.message}`),
        { response: err.response }
      );
    }

    const parsedResponse = JSON.parse(responseContent);
    const { accessToken, expiresIn, refreshToken } = parsedResponse.oAuthAuthorization;

    console.log('renewed', parsedResponse);

    this.authData.accessToken = accessToken;
    this.authData.refreshToken = refreshToken;
    this.authData.expiresAt = new Date().getTime() + expiresIn * 1000;

    this.saveAuthData();

    return expiresIn * 1000;
  }

  loadAuthData() {
    const user = this.usersCollection.findOne({ _id: this.userId });
    if (!user) {
      throw new Meteor.Error('hmis.api', `User ${this.userId} not found`);
{'fraction_non_alphanumeric': 0.13023867694042474, 'fraction_numerical': 0.003758691975192633, 'mean_word_length': 3.071920428462127, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4311921', 'n_tokens_mistral': 1642, 'n_tokens_neox': 1576, 'n_words': 318}