Code coverage report for lib\user-realm.js

Statements: 98.81% (83 / 84)      Branches: 91.67% (11 / 12)      Functions: 92.86% (13 / 14)      Lines: 98.81% (83 / 84)      Ignored: none     

All files » lib/ » user-realm.js
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 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268                                            1 1 1 1   1 1 1   1 1   1                   1 25 25 25 25 25 25 25 25 25                   1                         1   13                     1   33                     1   27                     1   24                 1 17 17 17   17       17   17   17                         1 19 1   18 18   18                 1 16                 1 3             1 13 13 13 13 13                 1 17   17 17 17   1 1     16 16 2 2     14   14 3   3 1 1     2 2 2     13 13                           1 17 17                 17 17 17   17         1
/*
 * @copyright
 * Copyright © Microsoft Open Technologies, Inc.
 *
 * All Rights Reserved
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http: *www.apache.org/licenses/LICENSE-2.0
 *
 * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
 * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
 * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A
 * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
 *
 * See the Apache License, Version 2.0 for the specific language
 * governing permissions and limitations under the License.
 */
'use strict';
 
var querystring = require('querystring');
var request = require('request');
var _ = require('underscore');
var url = require('url');
 
var constants = require('./constants');
var Logger = require('./log').Logger;
var util = require('./util');
 
var AccountType = constants.UserRealm.AccountType;
var FederationProtocolType = constants.UserRealm.FederationProtocolType;
 
var USER_REALM_PATH_TEMPLATE = 'common/UserRealm/<user>';
 
/**
 * Create a new UserRealm object
 * @private
 * @constructor
 * @param {object} callContext Contains any context information that applies to the request.
 * @param {string} userPrinciple   The username for which a realm needs to be discovered.
 * @param {string} authority       The string url of the authority that owns the userPrinciple.
 */
function UserRealm(callContext, userPrinciple, authority) {
  this._log = new Logger('UserRealm', callContext._logContext);
  this._callContext = callContext;
  this._apiVersion = '1.0';
  this._federationProtocol = null;
  this._accountType = null;
  this._federationMetadataUrl = null;
  this._federationActiveAuthUrl = null;
  this._userPrinciple = userPrinciple;
  this._authority = authority;
}
 
/**
* The API version requested by UserRealm.
* @type {string}
* @instance
* @memberOf UserRealm
* @name apiVersion
*/
Object.defineProperty(UserRealm.prototype, 'apiVersion', {
  get : function() {
    return this._apiVersion;
  }
});
 
/**
* The federation protocol used by the users realm.
* @type {string}
* @instance
* @memberOf UserRealm
* @name federationProtocol
*/
Object.defineProperty(UserRealm.prototype, 'federationProtocol', {
  get : function() {
    return this._federationProtocol;
  }
});
 
/**
* The Type of account.  Either managed or federated.
* @type {string}
* @instance
* @memberOf UserRealm
* @name accountType
*/
Object.defineProperty(UserRealm.prototype, 'accountType', {
  get : function() {
    return this._accountType;
  }
});
 
/**
* If this is a federated account then this property will contain the mex url.
* @type {string}
* @instance
* @memberOf UserRealm
* @name federationsMetadataUrl
*/
Object.defineProperty(UserRealm.prototype, 'federationMetadataUrl', {
  get : function() {
    return this._federationMetadataUrl;
  }
});
 
/**
* If the account is federated this will contain the authentication endpoint.
* @type {string}
* @instance
* @memberOf UserRealm
* @name federationActiveAuthUrl
*/
Object.defineProperty(UserRealm.prototype, 'federationActiveAuthUrl', {
  get : function() {
    return this._federationActiveAuthUrl;
  }
});
 
/**
* Given the authority url this method constructs a full user realm discovery url.
* @private
* @returns A full user realm discovery url including path and query string.
*/
UserRealm.prototype._getUserRealmUrl = function() {
  var userRealmUrl = util.copyUrl(this._authority);
  var urlEncodedUser = encodeURIComponent(this._userPrinciple);
  userRealmUrl.pathname = USER_REALM_PATH_TEMPLATE.replace('<user>', urlEncodedUser);
 
  var userRealmQuery = {
    'api-version' : this._apiVersion
  };
 
  userRealmUrl.search = querystring.stringify(userRealmQuery);
 
  userRealmUrl = util.copyUrl(userRealmUrl);
 
  return userRealmUrl;
};
 
/**
* Given a constants object and a value, validates that the value is a key in the constants object.
* @private
* @param {object} constants   An object containing constant key value pairs.
* @param {string}  value       A value to check against the constants
* @param {bool}   caseSensitive  set to true if comparisons should be made as case sensitive.  Defaults to false.
* @returns {bool|string}  If value passed in matches one of the constants then the return value is the matched constant.
*                         If a non case sensitive match was done, then the value returned may be different than the value
*                         passed in.  If there is no match then the method returns false.
*/
UserRealm.prototype._validateConstantValue = function(constants, value, caseSensitive) {
  if (!value) {
    return false;
  }
  Eif (!caseSensitive) {
    value = value.toLowerCase();
  }
  return _.contains(_.values(constants), value) ? value : false;
};
 
/**
* Checks whether an account type string is valid.
* @private
* @param {string} type  An account type string.
* @returns {bool}
*/
UserRealm.prototype._validateAccountType = function(type) {
  return this._validateConstantValue(AccountType, type);
};
 
/**
* Checks whether a federation protocol string is valid.
* @private
* @param {string} protocol  A federation protocol string.
* @returns {bool}
*/
UserRealm.prototype._validateFederationProtocol = function(protocol) {
  return this._validateConstantValue(FederationProtocolType, protocol);
};
 
/**
* Logs the values parsed as part of user realm discovery.
* @private
*/
UserRealm.prototype._logParsedResponse = function() {
  this._log.verbose('UserRealm response:');
  this._log.verbose(' AccountType:             ' + this.accountType);
  this._log.verbose(' FederationProtocol:      ' + this.federationProtocol);
  this._log.verbose(' FederationMetatdataUrl:  ' + this.federationMetadataUrl);
  this._log.verbose(' FederationActiveAuthUrl: ' + this.federationActiveAuthUrl);
};
 
/**
* Parses the response from a user realm discovery request.
* @private
* @param {string} body    The body returned as part of the http user realm discovery request.
* @param {UserRealm.DiscoverCallback} callback  Called when parsing is complete.
*/
UserRealm.prototype._parseDiscoveryResponse = function(body, callback) {
  this._log.verbose('Discovery response:\n' + body);
 
  var response;
  try {
    response = JSON.parse(body);
  } catch (err) {
    callback(this._log.createError('Parsing realm discovery respone JSON failed: ' + body));
    return;
  }
 
  var accountType = this._validateAccountType(response['account_type']);
  if (!accountType) {
    callback(this._log.createError('Cannot parse account_type: ' + accountType));
    return;
  }
 
  this._accountType = accountType;
 
  if (this._accountType === AccountType.Federated) {
    var protocol = this._validateFederationProtocol(response['federation_protocol']);
 
    if (!protocol) {
      callback(this._log.createError('Cannot parse federation protocol: ' + protocol));
      return;
    }
 
    this._federationProtocol = protocol;
    this._federationMetadataUrl = response['federation_metadata_url'];
    this._federationActiveAuthUrl = response['federation_active_auth_url'];
  }
 
  this._logParsedResponse();
  callback();
};
 
/**
* @callback DiscoverCallback
* @memberOf UserRealm
* @param {Error} error   If an error occurs during discovery then this parameter will be used to return the error.
*/
 
/**
* Performs user realm discovery and fills in the properties on this object.
* @private
* @param {UserRealm.DiscoverCallback} callback  Called when discovery is complete.
*/
UserRealm.prototype.discover = function(callback) {
  var self = this;
  var options = util.createRequestOptions(
    this,
    {
      headers : {
        Accept : 'application/json'
      }
    }
  );
 
  var userRealmUrl = this._getUserRealmUrl();
  this._log.verbose('Performing user realm discovery at: ' + url.format(userRealmUrl));
  request.get(userRealmUrl, options, util.createRequestHandler('User Realm Discovery', this._log, callback,
    function(response, body) {
      self._parseDiscoveryResponse(body, callback);
    })
  );
};
 
module.exports = UserRealm;