All files / src/utils AdfsHelper.ts

95.45% Statements 21/22
50% Branches 1/2
100% Functions 2/2
95.45% Lines 21/22
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  1x 1x 1x 1x 1x 1x         1x   2x 2x 2x   2x             2x                   2x   2x 2x       2x 2x 2x 2x 2x   2x                
import * as Promise from 'bluebird';
import * as request from 'request-promise';
import * as url from 'url';
import * as _ from 'lodash';
import * as fs from 'fs';
import * as path from 'path';
let xmldoc: any = require('xmldoc');
 
import { IAdfsUserCredentials } from './../auth/IAuthOptions';
import { SamlAssertion } from './SamlAssertion';
 
export class AdfsHelper {
  public static getSamlAssertion(siteUrl: string, credentials: IAdfsUserCredentials): Promise<SamlAssertion> {
    let adfsHost: string = url.parse(credentials.adfsUrl).host;
    let usernameMixedUrl = `https://${adfsHost}/adfs/services/trust/13/usernamemixed`;
    let samlTemplate: Buffer = fs.readFileSync(path.join(__dirname, '..', '..', 'templates', 'adfs_saml_wsfed.tmpl'));
 
    let samlBody: string = _.template(samlTemplate.toString())({
      to: usernameMixedUrl,
      username: credentials.username,
      password: credentials.password,
      relyingParty: credentials.relyingParty
    });
 
    return request.post(usernameMixedUrl, {
      body: samlBody,
      strictSSL: false,
      simple: false,
      headers: {
        'Content-Length': samlBody.length,
        'Content-Type': 'application/soap+xml; charset=utf-8'
      }
    })
      .then(xmlResponse => {
        let doc: any = new xmldoc.XmlDocument(xmlResponse);
 
        let tokenResponseCollection: any = doc.childNamed('s:Body').firstChild;
        Iif (tokenResponseCollection.name.indexOf('Fault') !== -1) {
          throw new Error(tokenResponseCollection.toString());
        }
 
        let responseNamespace: string = tokenResponseCollection.name.split(':')[0];
        let securityTokenResponse: any = doc.childNamed('s:Body').firstChild.firstChild;
        let samlAssertion: any = securityTokenResponse.childNamed(responseNamespace + ':RequestedSecurityToken').firstChild;
        let notBefore: string = samlAssertion.firstChild.attr['NotBefore'];
        let notAfter: string = samlAssertion.firstChild.attr['NotOnOrAfter'];
 
        return {
          value: samlAssertion.toString({ compressed: true }),
          notAfter: notAfter,
          notBefore: notBefore
        } as SamlAssertion;
      });
  }
}