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

88.06% Statements 59/67
62.5% Branches 20/32
100% Functions 8/8
87.88% Lines 58/66
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 1421x 1x 1x 1x 1x 1x         1x 1x               1x 1x 1x 6x   6x 6x             6x   6x   6x   6x 4x             2x 2x           2x   2x 3x     2x 2x   2x               2x   2x 2x 2x 2x   2x 2x   2x 2x   2x 9x 9x 7x 7x 3x         2x       2x 2x     2x       6x 6x     6x       6x     6x 6x     6x         6x       6x       6x       12x 12x      
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 { IAuthResolver } from '../../IAuthResolver';
import { IAuthResponse } from '../../IAuthResponse';
import { IOnDemandCredentials } from '../../IAuthOptions';
import { UrlHelper } from '../../../utils/UrlHelper';
import { Cache } from './../../../utils/Cache';
 
export interface ICookie {
  httpOnly: boolean;
  name: string;
  value: string;
}
 
export class OnDemand implements IAuthResolver {
  private static CookieCache: Cache = new Cache();
  private static Expiration = 24 * 60 * 60;
  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 = this.resolveFileName();
 
    let cachedCookie: string = OnDemand.CookieCache.get<string>(cacheKey);
 
    if (cachedCookie) {
      return Promise.resolve({
        headers: {
          'Cookie': cachedCookie
        }
      });
    }
 
    Eif (!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 authCookie = '';
 
    cookies.forEach((cookie) => {
      authCookie += `${cookie.name}=${cookie.value};`;
    });
 
    authCookie = authCookie.slice(0, -1);
    OnDemand.CookieCache.set(cacheKey, authCookie, OnDemand.Expiration);
 
    return Promise.resolve({
      headers: {
        'Cookie': authCookie
      }
    });
  }
 
  private saveAuthData(dataPath: string): ICookie[] {
    let isWindows = (process.platform.lastIndexOf('win') === 0);
 
    let command = isWindows ? 'cmd.exe' : 'sh';
    let electronExecutable = this._authOptions.electron || 'electron';
    let args = `${electronExecutable} ${path.join(__dirname, 'main.js')} ${this._siteUrl}`;
    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);
        }
      }
    });
 
    Iif (cookies.length === 0) {
      throw new Error('Cookie array is empy');
    }
 
    Eif (this._authOptions.persist) {
      fs.writeFileSync(dataPath, this._cpass.encode(JSON.stringify(cookies)));
    }
 
    return cookies;
  }
 
  private getDataFilePath(): string {
    let userDataFolder = this.getUserDataFolder();
    Iif (!fs.existsSync(userDataFolder)) {
      fs.mkdirSync(userDataFolder);
    }
    return path.join(userDataFolder, `${this.resolveFileName()}_ondemand.data`);
  }
 
  private getUserDataFolder(): string {
    let platform = process.platform;
    let homepath: string;
 
    Eif (platform.lastIndexOf('win') === 0) {
      homepath = process.env.APPDATA || process.env.LOCALAPPDATA;
    }
 
    Iif (platform === 'darwin') {
      homepath = process.env.homepath;
      homepath = path.join(homepath, 'Library', 'Application Support');
    }
 
    Iif (platform === 'linux') {
      homepath = process.env.homepath;
    }
 
    Iif (!homepath) {
      throw new Error('Couldn\'t find the base application data folder');
    }
 
    return path.join(homepath, 'spauth');
  }
 
  private resolveFileName(): string {
    let url = UrlHelper.removeTrailingSlash(this._siteUrl);
    return url.replace(/[\:/\s]/g, '_');
  }
}