<commit_before>const { accounts } = require('./database');
const config = require('../../config');
const keys = require('./keys');
const Promise = require('bluebird');
const simpleOauth2 = require('simple-oauth2');
const request = require('request-promise');

function Auth() {
  //
  // properties
  //
  this.oauthClient = simpleOauth2.create({
    client: {
      id: config.oauthClientId,
      secret: config.oauthClientSecret,
    },
    auth: {
      tokenHost: 'https://api.planningcenteronline.com',
    },
  });

  this.authorizationUrl = this.oauthClient.authorizationCode.authorizeURL({
    redirect_uri: 'servizi://oauth/callback',
    scope: 'services',
  });

  //
  // public methods
  //

  this.checkIfShouldRefreshToken = function shouldRefreshToken(_tokenRecord) {
    const tokenRecord = _tokenRecord;
    return new Promise((resolve) => {
      if (tokenRecord === null) {
        resolve(null);
        return;
      }

      const timeDifference = Math.floor(Date.now() / 1000) - tokenRecord.token.created_at;
      if (timeDifference >= tokenRecord.token.expires_in) {
        tokenRecord.should_refresh = true;
      } else {
        tokenRecord.should_refresh = false;
      }
      resolve(tokenRecord);
    });
  };

  this.shouldRefreshToken = function shouldRefreshToken(token) {
    if (!token) {
      return true;
    }

    const timeDifference = Math.floor(Date.now() / 1000) - token.created_at;
    if (timeDifference >= token.expires_in - 300) {
      return true;
    }

    return false;
  };

  this.refreshSelectedAccountTokenIfNecessary = (tokenRecord) => {
    return new Promise((resolve, reject) => {
      accounts.findOne({ selected: true }, (err, existingTokenResult) => {
        if (!existingTokenResult) {
          reject();
        } else if (err) {
          reject(err);
        }

        if (this.shouldRefreshToken(existingTokenResult.tokenInfo.token)) {
          const oauthToken = this.oauthClient.accessToken.create(existingTokenResult.tokenInfo.token);
          oauthToken.refresh()
            .then((tokenResponse) => {
              const newTokenInfo = {
                redirect_uri: existingTokenResult.tokenInfo.redirect_uri,
                token: tokenResponse,
              };
              accounts.update(
                { _id: existingTokenResult._id },
                { $set: { tokenInfo: newTokenInfo } },
                { upsert: true },
                () => {
                  resolve();
                }
              );
            })
            .catch(reject);
        } else {
          resolve();
        }
      });
      // if (tokenRecord === null) {
      //   resolve(null);
      //   return;
      // }

      // const tokenObject = {
      //   access_token: tokenRecord.token.access_token,
      //   refresh_token: tokenRecord.token.refresh_token,
      //   expires_in: tokenRecord.token.expires_in,
      // };
      
      // token.refresh()<commit_msg>Small tweak to the oauth token refreshing.<commit_after>const { accounts } = require('./database');
const config = require('../../config');
const keys = require('./keys');
const Promise = require('bluebird');
const simpleOauth2 = require('simple-oauth2');
const request = require('request-promise');

function Auth() {
  //
  // properties
  //
  this.oauthClient = simpleOauth2.create({
    client: {
      id: config.oauthClientId,
      secret: config.oauthClientSecret,
    },
    auth: {
      tokenHost: 'https://api.planningcenteronline.com',
    },
  });

  this.authorizationUrl = this.oauthClient.authorizationCode.authorizeURL({
    redirect_uri: 'servizi://oauth/callback',
    scope: 'services',
  });

  //
  // public methods
  //

  this.checkIfShouldRefreshToken = function shouldRefreshToken(_tokenRecord) {
    const tokenRecord = _tokenRecord;
    return new Promise((resolve) => {
      if (tokenRecord === null) {
        resolve(null);
        return;
      }

      const timeDifference = Math.floor(Date.now() / 1000) - tokenRecord.token.created_at;
      if (timeDifference >= tokenRecord.token.expires_in) {
        tokenRecord.should_refresh = true;
      } else {
        tokenRecord.should_refresh = false;
      }
      resolve(tokenRecord);
    });
  };

  this.shouldRefreshToken = function shouldRefreshToken(token) {
    if (!token) {
      return true;
    }

    const timeDifference = Math.floor(Date.now() / 1000) - token.created_at;
    if (timeDifference >= token.expires_in - 300) {
      return true;
    }

    return false;
  };

  this.refreshSelectedAccountTokenIfNecessary = (tokenRecord) => {
    return new Promise((resolve, reject) => {
      accounts.findOne({ selected: true }, (err, existingTokenResult) => {
        if (!existingTokenResult) {
          reject();
        } else if (err) {
          reject(err);
        }

        if (this.shouldRefreshToken(existingTokenResult.tokenInfo.token)) {
          const oauthToken = this.oauthClient.accessToken.create(existingTokenResult.tokenInfo.token);
          oauthToken.refresh()
            .then((tokenResponse) => {
              const newTokenInfo = {
                redirect_uri: existingTokenResult.tokenInfo.redirect_uri,
                token: tokenResponse.token,
              };
              accounts.update(
                { _id: existingTokenResult._id },
                { $set: { tokenInfo: newTokenInfo } },
                { upsert: true },
                () => {
                  resolve();
                }
              );
            })
            .catch(reject);
        } else {
          resolve();
        }
      });
      // if (tokenRecord === null) {
      //   resolve(null);
      //   return;
      // }

      // const tokenObject = {
      //   access_token: tokenRecord.token.access_token,
      //   refresh_token: tokenRecord.token.refresh_token,
      //   expires_in: tokenRecord.token.expires_in,
      // };
      
      // token.refresh()
{'fraction_non_alphanumeric': 0.13060265234178278, 'fraction_numerical': 0.004700352526439483, 'mean_word_length': 2.0538185545873913, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 19, 'https://': 2, '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': '6911483', 'n_tokens_mistral': 1720, 'n_tokens_neox': 1661, 'n_words': 293}