All files / src/auth/resolvers/ondemand OnDemand.ts

90.91% Statements 70/77
75% Branches 27/36
100% Functions 9/9
90.79% Lines 69/76
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 1511x 1x 1x 1x 1x 1x 1x         1x 1x                 1x 1x 6x   6x 6x             6x   6x   6x   6x 4x             2x     2x   2x 2x 2x 3x 3x 1x       2x 1x       2x   2x 3x     2x 2x   2x               2x 2x 3x 2x       2x       1x 1x 1x 1x 1x 1x 1x   1x 1x   1x 1x   1x 4x 4x 3x 3x 1x     1x 1x 1x 1x                   1x       1x 1x     1x       6x 6x   6x     6x      
import * as Promise from 'bluebird';
import * as childProcess from 'child_process';
import * as path from 'path';
import * as fs from 'fs';
import * as _ from 'lodash';
import { Cpass } from 'cpass';
import * as url from 'url';
 
import { IAuthResolver } from '../../IAuthResolver';
import { IAuthResponse } from '../../IAuthResponse';
import { IOnDemandCredentials } from '../../IAuthOptions';
import { Cache } from './../../../utils/Cache';
import { FilesHelper } from '../../../utils/FilesHelper';
 
export interface ICookie {
  httpOnly: boolean;
  name: string;
  value: string;
  expirationDate?: number;
}
 
export class OnDemand implements IAuthResolver {
  private static CookieCache: Cache = new Cache();
  private _cpass = new Cpass();
 
  constructor(private _siteUrl: string, private _authOptions: IOnDemandCredentials) {
    _.defaults(this._authOptions, {
      force: false,
      persist: true
    });
  }
 
  public getAuth(): Promise<IAuthResponse> {
    let dataFilePath = this.getDataFilePath();
    let cookies: ICookie[];
    let cacheKey: string = FilesHelper.resolveFileName(this._siteUrl);
 
    let cachedCookie: string = OnDemand.CookieCache.get<string>(cacheKey);
 
    if (cachedCookie) {
      return Promise.resolve({
        headers: {
          'Cookie': cachedCookie
        }
      });
    }
 
    Iif (!fs.existsSync(dataFilePath) || this._authOptions.force) {
      cookies = this.saveAuthData(dataFilePath);
    } else {
      console.log(`[node-sp-auth]: reading auth data from ${dataFilePath}`);
 
      cookies = JSON.parse(this._cpass.decode(fs.readFileSync(dataFilePath).toString()));
      let expired = false;
      cookies.forEach((cookie) => {
        let now = new Date();
        if (cookie.expirationDate && new Date(cookie.expirationDate * 1000) < now) {
          expired = true;
        }
      });
 
      if (expired) {
        cookies = this.saveAuthData(dataFilePath);
      }
    }
 
    let authCookie = '';
 
    cookies.forEach((cookie) => {
      authCookie += `${cookie.name}=${cookie.value};`;
    });
 
    authCookie = authCookie.slice(0, -1);
    OnDemand.CookieCache.set(cacheKey, authCookie, this.getMaxExpiration(cookies));
 
    return Promise.resolve({
      headers: {
        'Cookie': authCookie
      }
    });
  }
 
  private getMaxExpiration(cookies: ICookie[]): Date {
    let expiration = 0;
    cookies.forEach(cookie => {
      if (cookie.expirationDate > expiration) {
        expiration = cookie.expirationDate * 1000;
      }
    });
 
    return new Date(expiration)
  }
 
  private saveAuthData(dataPath: string): ICookie[] {
    let isWindows = (process.platform.lastIndexOf('win') === 0);
    let host = url.parse(this._siteUrl).hostname;
    let isOnPrem = host.indexOf('.sharepoint.com') === -1 && host.indexOf('.sharepoint.cn') === -1;
    let command = isWindows ? 'cmd.exe' : 'sh';
    let electronExecutable = this._authOptions.electron || 'electron';
    let args = `${electronExecutable} ${path.join(__dirname, 'electron/main.js')} ${this._siteUrl} ${this._authOptions.force}`;
    const output = childProcess.execFileSync(command, [isWindows ? '/c' : '-c', args]).toString();
 
    let cookieRegex = /#\{([\s\S]+?)\}#/gm;
    let cookieData = cookieRegex.exec(output);
 
    let cookiesJson = cookieData[1].split(';#;');
    let cookies: ICookie[] = [];
 
    cookiesJson.forEach((cookie) => {
      let data: string = cookie.replace(/(\n|\r)+/g, '').replace(/^["]+|["]+$/g, '');
      if (data) {
        let cookieData = JSON.parse(data) as ICookie;
        if (cookieData.httpOnly) {
          cookies.push(cookieData);
 
          // explicitly set 1 hour expiration for on-premise
          Eif (isOnPrem) {
            let expiration = new Date();
            expiration.setMinutes(expiration.getMinutes() + 55);
            cookieData.expirationDate = expiration.getTime() / 1000;
          } else if (!cookieData.expirationDate) { // 24 hours for online if no expiration date on cookie
            let expiration = new Date();
            expiration.setMinutes(expiration.getMinutes() + 1435);
            cookieData.expirationDate = expiration.getTime() / 1000;
          }
        }
      }
    });
 
    Iif (cookies.length === 0) {
      throw new Error('Cookie array is empty');
    }
 
    Eif (this._authOptions.persist) {
      fs.writeFileSync(dataPath, this._cpass.encode(JSON.stringify(cookies)));
    }
 
    return cookies;
  }
 
  private getDataFilePath(): string {
    let userDataFolder = FilesHelper.getUserDataFolder();
    let ondemandFolder = path.join(userDataFolder, 'ondemand');
 
    Iif (!fs.existsSync(ondemandFolder)) {
      fs.mkdirSync(ondemandFolder);
    }
    return path.join(ondemandFolder, `${FilesHelper.resolveFileName(this._siteUrl)}.data`);
  }
}