Code coverage report for passport-fellowshipone/strategy.js

Statements: 50.65% (78 / 154)      Branches: 32.11% (35 / 109)      Functions: 65% (13 / 20)      Lines: 51.06% (72 / 141)      Ignored: none     

All files » passport-fellowshipone/ » strategy.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 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350      1                                                                                                 1 15 15 15 15 15 15   15 15 15       15     15           1   1 60         1   2 2 2         2   2   1 1 1 1 1     1   1             1                                                                                                                                                                                                                                                                             1 1           1 10 10       7 1 1   6 1 1 1 1     5   4           1 5   2 1   1 1 1 1 1 1   1   1 1 1         1     1 1 1 1   1   1                                   1 7   5               5 5             1  
/**
 * Module dependencies.
 */
var util = require('util'),
   OAuthStrategy = require('passport-oauth').OAuthStrategy,
   InternalOAuthError = require('passport-oauth').InternalOAuthError,
   querystring = require('querystring'),
   URL = require('url'),
   URI = require('URIjs'),
   URITemplate = require('URIjs/src/URITemplate'),
   async = require('async'),
   request = require('request');
 
/**
 * `Strategy` constructor.
 *
 * The FellowshipOne authentication strategy authenticates requests by delegating
 * to Fellowship One using the OAuth 1.0a protocol.
 *
 * Applications must supply a `verify` callback which accepts a `token`,
 * `tokenSecret` and service-specific `profile`, and then calls the `done`
 * callback supplying a `user`, which should be set to `false` if the
 * credentials are not valid.  If an exception occured, `err` should be set.
 *
 * Options:
 *   - `churchCode`      Your Fellowship One church code
 *   - `staging`         Whether we're using staging or production
 *   - `consumerKey`     Fellowship One Developer Key
 *   - `consumerSecret`  Fellowship One Secret Key
 *   - `callbackURL`     URL to which Fellowship One will redirect the user after obtaining authorization
 *
 * Examples:
 *
 *     passport.use(new F1Strategy({
 *         churchCode: 'MYCHURCH',
 *         staging: true,
 *         consumerKey: '123',
 *         consumerSecret: 'xxx'
 *         callbackURL: 'https://www.example.net/auth/fellowshipone/callback'
 *       },
 *       function(token, tokenSecret, profile, done) {
 *         User.findOrCreate(..., function (err, user) {
 *           done(err, user);
 *         });
 *       }
 *     ));
 *
 * @param {Object} options
 * @param {Function} verify
 * @api public
 */
 
function Strategy(options, verify) {
   options = options || {}
   options.churchCode = options.churchCode
   options.apiURL = expand(options.apiURL || 'https://{churchCode}.fellowshiponeapi.com/v1', options)
   options.requestTokenURL = expand(options.requestTokenURL || options.apiURL + '/Tokens/RequestToken', options)
   options.accessTokenURL = expand(options.accessTokenURL || options.apiURL + '/Tokens/AccessToken', options)
   options.userAuthorizationURL = expand(options.userAuthorizationURL || options.apiURL + '/PortalUser/Login', options)
 
   OAuthStrategy.call(this, options, verify)
   this.options = options
   this.name = 'fellowshipone'
 
   // Override oauth.getOAuthAccessToken so that we can get the user profile from the
   // response headers.
   this._oauth.getOAuthAccessToken = this._getOAuthAccessToken.bind(this._oauth)
 
   // Override oauth._performSecureRequest to account for https://github.com/ciaranj/node-oauth/issues/182
   this._oauth._performSecureRequest = this._performSecureRequest.bind(this._oauth)
}
 
/**
 * Inherit from `OAuthStrategy`.
 */
util.inherits(Strategy, OAuthStrategy);
 
var expand = function(uri, options) {
   return URI.expand(uri, options).normalize().toString()
}
 
// Override oauth.getOAuthAccessToken so that we can get the user profile from the
// response headers.
Strategy.prototype._getOAuthAccessToken = function(oauth_token, oauth_token_secret, oauth_verifier, callback) {
   /* jshint sub: true */
   var extraParams = {};
   Eif (typeof oauth_verifier == "function") {
      callback = oauth_verifier;
   } else {
      extraParams.oauth_verifier = oauth_verifier;
   }
 
   this._performSecureRequest(oauth_token, oauth_token_secret, this._clientOptions.accessTokenHttpMethod, this._accessUrl, extraParams, null, null,
     function(error, data, response) {
      if (error) callback(error);
      else {
         var results = querystring.parse(data);
         var oauth_access_token = results["oauth_token"];
         delete results["oauth_token"];
         var oauth_access_token_secret = results["oauth_token_secret"];
         delete results["oauth_token_secret"];
 
         // this is the only customization really
         results.userURL = response.headers['content-location']
 
         callback(null, oauth_access_token, oauth_access_token_secret, results);
      }
   })
   /* jshint sub: false */
}
 
// Override oauth._performSecureRequest to account for https://github.com/ciaranj/node-oauth/issues/182
Strategy.prototype._performSecureRequest = function(oauth_token, oauth_token_secret, method, url, extra_params, post_body, post_content_type, callback) {
   /* jshint shadow: true, sub: true, eqnull: true */
   var orderedParameters = this._prepareParameters(oauth_token, oauth_token_secret, method, url, extra_params);
 
   if (!post_content_type) {
      post_content_type = "application/x-www-form-urlencoded";
   }
   var parsedUrl = URL.parse(url, false);
   if (parsedUrl.protocol == "http:" && !parsedUrl.port) parsedUrl.port = 80;
   if (parsedUrl.protocol == "https:" && !parsedUrl.port) parsedUrl.port = 443;
 
   var headers = {};
   var authorization = this._buildAuthorizationHeaders(orderedParameters);
   if (this._isEcho) {
      headers["X-Verify-Credentials-Authorization"] = authorization;
   } else {
      headers["Authorization"] = authorization;
   }
 
   headers["Host"] = parsedUrl.host
 
   for (var key in this._headers) {
      if (this._headers.hasOwnProperty(key)) {
         headers[key] = this._headers[key];
      }
   }
 
   // Filter out any passed extra_params that are really to do with OAuth
   for (var key in extra_params) {
      if (this._isParameterNameAnOAuthParameter(key)) {
         delete extra_params[key];
      }
   }
 
   if ((method == "POST" || method == "PUT") && (post_body == null && extra_params != null)) {
      // Fix the mismatch between the output of querystring.stringify() and this._encodeData()
      post_body = querystring.stringify(extra_params)
         .replace(/\!/g, "%21")
         .replace(/\'/g, "%27")
         .replace(/\(/g, "%28")
         .replace(/\)/g, "%29")
         .replace(/\*/g, "%2A");
   }
 
   if (post_body) {
      if (Buffer.isBuffer(post_body)) {
         headers["Content-length"] = post_body.length;
      } else {
         headers["Content-length"] = Buffer.byteLength(post_body);
      }
      headers["Content-Type"] = post_content_type;
   } else {
      headers["Content-length"] = 0;
   }
 
   var path;
   if (!parsedUrl.pathname || parsedUrl.pathname === "") parsedUrl.pathname = "/";
   if (parsedUrl.query) path = parsedUrl.pathname + "?" + parsedUrl.query;
   else path = parsedUrl.pathname;
 
   var request;
   if (parsedUrl.protocol == "https:") {
      request = this._createClient(parsedUrl.port, parsedUrl.hostname, method, path, headers, true);
   } else {
      request = this._createClient(parsedUrl.port, parsedUrl.hostname, method, path, headers);
   }
 
   var clientOptions = this._clientOptions;
   if (callback) {
      var data = "";
      var self = this;
 
      // Some hosts *cough* google appear to close the connection early / send no content-length header
      // allow this behaviour.
      var allowEarlyClose = false; //OAuthUtils.isAnEarlyCloseHost(parsedUrl.hostname);
      var callbackCalled = false;
      var passBackControl = function(response) {
         if (!callbackCalled) {
            callbackCalled = true;
            if (response.statusCode >= 200 && response.statusCode <= 299) {
               callback(null, data, response);
            } else {
               // Follow 301 or 302 redirects with Location HTTP header
               if ((response.statusCode == 301 || response.statusCode == 302) && clientOptions.followRedirects && response.headers && response.headers.location) {
                  self._performSecureRequest(oauth_token, oauth_token_secret, method, response.headers.location, extra_params, post_body, post_content_type, callback);
               } else {
                  callback({
                     statusCode: response.statusCode,
                     data: data
                  }, data, response);
               }
            }
         }
      }
 
      request.on('response', function(response) {
         response.setEncoding('utf8');
         response.on('data', function(chunk) {
            data += chunk;
         });
         response.on('end', function() {
            passBackControl(response);
         });
         response.on('close', function() {
            if (allowEarlyClose) {
               passBackControl(response);
            }
         });
      });
 
      request.on("error", function(err) {
         if (!callbackCalled) {
            callbackCalled = true;
            callback(err)
         }
      });
 
      if ((method === "POST" || method === "PUT") && post_body != null && post_body !== "") {
         request.write(post_body);
      }
      request.end();
   } else {
      if ((method === "POST" || method === "PUT") && post_body != null && post_body !== "") {
         request.write(post_body);
      }
      return request;
   }
   /* jshint shadow: false, sub: false, eqnull: false */
   return;
}
 
/**
 * Implement this so that we can send the callback... This doesn't seem to be
 * working right for the oauth module...
 */
Strategy.prototype.userAuthorizationParams = function(options) {
   return {
      oauth_callback: this._callbackURL
   }
}
 
// retrieve a profile-related object asynchronously and yield its body
Strategy.prototype._retrieve = function(oauth, url, callback) {
   process.nextTick(function() {
      request.get(url, {
         oauth: oauth,
         json: true
      }, function(err, res, body) {
         if (err) {
            console.error(err)
            return callback(new InternalOAuthError('failed to fetch user profile', err))
         }
         if (res.statusCode > 299) {
            err = new InternalOAuthError('error ' + res.statusCode + ' while fetching user profile: ' + body)
            err.statusCode = res.statusCode
            console.error('failed to fetch user profile: %j', err)
            return callback(err)
         }
 
         if (!body) return callback(new InternalOAuthError('Fellowship One returned invalid reply object %s', body))
 
         callback(null, body)
      })
   })
}
 
// transform an array of [ {person:...}, {communications:...}] into a profile
Strategy.prototype.transform = function(err, items, done) {
   if (err) return done(err)
 
   if (!items[0].person) return done(new InternalOAuthError('Fellowship One returned invalid reply object %s', items[0]))
   Iif (!items[1].communications) return done(new InternalOAuthError('Fellowship One returned invalid reply object %s', items[1]))
 
   var user = items[0].person
   var profile = {}
   profile.id = Number(user['@id'])
   profile.uri = user['@uri']
   profile.displayName = user.goesByName ? user.goesByName : user.firstName
   profile.fullName = profile.displayName + ' ' + user.lastName
 
   var communication = items[1].communications.communication || []
 
   var emails = communication.reduce(function(memo, comm) {
      Eif (comm.communicationGeneralType === 'Email')
         memo.push({
            value: comm.communicationValue,
            type: comm.communicationType.name,
            preferred: comm.preferred === "true"
         })
      return memo
   }, [])
 
   var email = emails.reduce(function(memo, email) {
      Iif (email.preferred) return email
      else Iif (memo) return memo
      else return email
   }, undefined)
   Eif (email && email.value) profile.email = email.value
 
   done(null, profile)
}
 
/**
 * Retrieve user profile from Fellowship One.
 *
 * This function constructs a normalized profile, with the following properties:
 *
 *   - `id`
 *   - `displayName`
 *   - `email`
 *
 * @param {String} token
 * @param {String} tokenSecret
 * @param {Object} params - this should have a userURL property, injected by the _oauth.getOAuthAccessToken call
 * @param {Function} done
 * @api protected
 */
Strategy.prototype.userProfile = function(token, tokenSecret, params, done) {
   if (!params || !params.userURL) return done(null, {})
 
   var oauth = {
      consumer_key: this.options.consumerKey,
      consumer_secret: this.options.consumerSecret,
      token: token,
      token_secret: tokenSecret
   }
 
   // turn the person and communications record into a profile
   async.map([params.userURL, params.userURL + '/Communications'], this._retrieve.bind(this, oauth), (function(err, items) {
      this.transform(err, items, done)
   }).bind(this))
}
 
/**
 * Expose `Strategy`.
 */
module.exports = Strategy;