All files / src/auth/resolvers OnpremiseUserCredentials.ts

100% Statements 19/19
50% Branches 1/2
100% Functions 3/3
100% Lines 18/18
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  1x 1x 1x   1x 1x   1x           1x   6x       6x 6x 6x   6x   6x   6x     6x                           6x 6x   6x                        
import * as Promise from 'bluebird';
import * as _ from 'lodash';
import * as url from 'url';
import * as request from 'request-promise';
import { IncomingMessage } from 'http';
import * as http from 'http';
import * as https from 'https';
 
let ntlm: any = require('httpntlm').ntlm;
 
import { IAuthResolver } from './../IAuthResolver';
import { IOnpremiseUserCredentials } from './../IAuthOptions';
import { IAuthResponse } from './../IAuthResponse';
 
export class OnpremiseUserCredentials implements IAuthResolver {
 
  constructor(private _siteUrl: string, private _authOptions: IOnpremiseUserCredentials) { }
 
  public getAuth(): Promise<IAuthResponse> {
 
    _.defaults(this._authOptions, { domain: '', workstation: '' });
    let ntlmOptions: any = _.assign({}, this._authOptions);
    ntlmOptions.url = this._siteUrl;
 
    let type1msg: any = ntlm.createType1Message(ntlmOptions);
 
    let isHttps: boolean = url.parse(this._siteUrl).protocol === 'https:';
 
    let keepaliveAgent: any = isHttps ? new https.Agent({ keepAlive: true, rejectUnauthorized: false }) :
      new http.Agent({ keepAlive: true });
 
    return request({
      url: this._siteUrl,
      method: 'GET',
      headers: {
        'Connection': 'keep-alive',
        'Authorization': type1msg,
        'Accept': 'application/json;odata=verbose'
      },
      agent: keepaliveAgent,
      resolveWithFullResponse: true,
      simple: false,
      strictSSL: false
    } as any)
      .then((response: IncomingMessage) => {
        let type2msg: any = ntlm.parseType2Message(response.headers['www-authenticate']);
        let type3msg: any = ntlm.createType3Message(type2msg, ntlmOptions);
 
        return {
          headers: {
            'Connection': 'Close',
            'Authorization': type3msg
          },
          options: {
            agent: keepaliveAgent
          }
        };
      }) as Promise<IAuthResponse>;
  };
}