<commit_before>/**
 * Created by mgoria on 11/6/15.
 */

/* eslint-disable no-unused-vars */

'use strict';

import AWS from 'aws-sdk';
import CognitoSyncManager from 'amazon-cognito-js';
import {CreateCognitoDatasetException} from './Exception/CreateCognitoDatasetException';
import {PutCognitoRecordException} from './Exception/PutCognitoRecordException';
import {SynchronizeCognitoDatasetException} from './Exception/SynchronizeCognitoDatasetException';

export class TokenManager {
  /**
   * @returns {String}
   */
  static get DATASET_NAME() {
    return 'deep_session';
  }

  /**
   * @returns {String}
   */
  static get RECORD_NAME() {
    return 'session_creds';
  }

  /**
   * @param {String} identityPoolId
   * @param {Object|null} cognitoSyncClient
   */
  constructor(identityPoolId, cognitoSyncClient = null) {
    this._identityPoolId = identityPoolId;
    this._cognitoSyncClient = cognitoSyncClient;
    this._lastSyncedEntry = null;
    this._syncInProgress = false;
  }

  /**
   * @returns {Object}
   */
  get cognitoSyncClient() {
    if (!this._cognitoSyncClient) {
      this._cognitoSyncClient = new AWS.CognitoSyncManager();
    }

    return this._cognitoSyncClient;
  }

  /**
   * @param {Token} token
   * @returns {Promise}
   */
  saveToken(token) {
    return new Promise(
      (resolve, reject) => {
        this._createOrGetDataset((error, dataset) => {
          if (error) {
            return reject(error);
          }

          let encodedToken = this._encodeToken(token);

          if (this._lastSyncedEntry === encodedToken || this._syncInProgress) {
            return resolve();
          }

          this._syncInProgress = true;
          this._lastSyncedEntry = encodedToken;

          dataset.put(TokenManager.RECORD_NAME, this._encodeToken(token), (error/*, record*/) => {
            if (error) {
              return reject(new PutCognitoRecordException(
                TokenManager.DATASET_NAME, TokenManager.RECORD_NAME, error
              ));
            }

            this._synchronizeDataset(dataset, (error, savedRecords) => {
              this._syncInProgress = false;
              
              if (error) {
                return reject(new SynchronizeCognitoDatasetException(dataset, error));
              }

              resolve(savedRecords);
            });
          });
        });
      }
    );
  }

  /**
   * @param {String} identityId
   * @returns {Promise}
   */
  loadBackendToken(identityId) {
    let cognitosync = new AWS.CognitoSync();
    let params = {
      DatasetName: TokenManager.DATASET_NAME,
      IdentityId: identityId,
      IdentityPoolId: this._identityPoolId,
    };

    return cognitosync
      .listRecords(params)
      .promise()
      .then(data => {
        let token = null;

        data.Records.forEach(record => {
          if (record.Key === TokenManager.RECORD_NAME) {
            token = this._decodeToken(record.Value);
            return token;
          }
        });

        return token;
      });
  }

  /**
   * @returns {Promise}<commit_msg># Fix null response from lambda when token expires<commit_after>/**
 * Created by mgoria on 11/6/15.
 */

/* eslint-disable no-unused-vars */

'use strict';

import AWS from 'aws-sdk';
import CognitoSyncManager from 'amazon-cognito-js';
import {CreateCognitoDatasetException} from './Exception/CreateCognitoDatasetException';
import {PutCognitoRecordException} from './Exception/PutCognitoRecordException';
import {SynchronizeCognitoDatasetException} from './Exception/SynchronizeCognitoDatasetException';

export class TokenManager {
  /**
   * @returns {String}
   */
  static get DATASET_NAME() {
    return 'deep_session';
  }

  /**
   * @returns {String}
   */
  static get RECORD_NAME() {
    return 'session_creds';
  }

  /**
   * @param {String} identityPoolId
   * @param {Object|null} cognitoSyncClient
   */
  constructor(identityPoolId, cognitoSyncClient = null) {
    this._identityPoolId = identityPoolId;
    this._cognitoSyncClient = cognitoSyncClient;
    this._lastSyncedEntry = null;
    this._syncInProgress = false;
  }

  /**
   * @returns {Object}
   */
  get cognitoSyncClient() {
    if (!this._cognitoSyncClient) {
      this._cognitoSyncClient = new AWS.CognitoSyncManager();
    }

    return this._cognitoSyncClient;
  }

  /**
   * @param {Token} token
   * @returns {Promise}
   */
  saveToken(token) {
    return new Promise(
      (resolve, reject) => {
        this._createOrGetDataset((error, dataset) => {
          if (error) {
            return reject(error);
          }

          let encodedToken = this._encodeToken(token);

          if (this._lastSyncedEntry === encodedToken || this._syncInProgress) {
            return resolve();
          }

          this._syncInProgress = true;
          this._lastSyncedEntry = encodedToken;

          dataset.put(TokenManager.RECORD_NAME, this._encodeToken(token), (error/*, record*/) => {
            if (error) {
              return reject(new PutCognitoRecordException(
                TokenManager.DATASET_NAME, TokenManager.RECORD_NAME, error
              ));
            }

            this._synchronizeDataset(dataset, (error, savedRecords) => {
              this._syncInProgress = false;
              
              if (error) {
                return reject(new SynchronizeCognitoDatasetException(dataset, error));
              }

              resolve(savedRecords);
            });
          });
        });
      }
    );
  }

  /**
   * @param {String} identityId
   * @returns {Promise}
   */
  loadBackendToken(identityId) {
    let cognitosync = new AWS.CognitoSync({
      credentials: AWS.config.systemCredentials,
    });

    let params = {
      DatasetName: TokenManager.DATASET_NAME,
      IdentityId: identityId,
      IdentityPoolId: this._identityPoolId,
    };

    return cognitosync
      .listRecords(params)
      .promise()
      .then(data => {
        let token = null;

        data.Records.forEach(record => {
          if (record.Key === TokenManager.RECORD_NAME) {
            token = this._decodeToken(record.Value);
            return token;
          }
        });

        return token;
      });
  }

  /**
   * @returns {Promise}
{'fraction_non_alphanumeric': 0.11710990067286126, 'fraction_numerical': 0.0016020506247997437, 'mean_word_length': 2.277165354330709, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '7542132', 'n_tokens_mistral': 1853, 'n_tokens_neox': 1825, 'n_words': 343}