all files / express-stormpath/lib/controllers/ register.js

92.38% Statements 97/105
85.19% Branches 46/54
100% Functions 27/27
92.38% Lines 97/105
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                                                                                                                                        30×   30×     30×                         37× 37× 37× 37×   30×   30×     27×     21×   21×     15×     37× 37×       37×   15×       14×   14× 13×     12× 12×     10× 10× 10×       10×                                         14×             21×   21×                   16×             16× 16×     16× 16×       16× 16×     13×         13× 13× 13×   11× 11× 11×           13×         11×                                 16×                  
'use strict';
 
var async = require('async');
var url = require('url');
 
var helpers = require('../helpers');
 
/**
 * Delivers the default response for registration attempts that accept an HTML
 * content type, where the new account is in an unverified state. In this
 * situation we redirect to the login page with a query parameter that
 * indidcates that the account is unverified
 *
 * @function
 *
 * @param {Object} req - The http request.
 * @param {Object} res - The http response.
 */
function defaultUnverifiedHtmlResponse(req, res) {
  var config = req.app.get('stormpathConfig');
  res.redirect(302, config.web.login.uri + '?status=unverified');
}
 
/**
 * Delivers the default response for registration attempts that accept an HTML
 * content type, where the new account is in a verified state. In this
 * situation we redirect to the login page with a query parameter that
 * indidcates that the account has been created (and is ready for a login
 * attempt)
 *
 * @function
 *
 * @param {Object} req - The http request.
 * @param {Object} res - The http response.
 */
function defaultCreatedHtmlResponse(req, res) {
  var config = req.app.get('stormpathConfig');
  res.redirect(302, config.web.login.uri + '?status=created');
}
 
/**
 * Delivers the default response for registration attempts that accept an HTML
 * content type, where the new account is in a verified state and the config
 * has requested that we automatically log in the user. In this situation we
 * redirect to the next URI that is in the url, or the nextUri that is defined
 * on the registration configuration
 *
 * @function
 *
 * @param {Object} req - The http request.
 * @param {Object} res - The http response.
 */
function defaultAutoAuthorizeHtmlResponse(req, res) {
  var config = req.app.get('stormpathConfig');
  res.redirect(302, url.parse(req.query.next || '').path || config.web.register.nextUri);
}
 
/**
 * Delivers the default response for registration attempts that accept a JSON
 * content type. In this situation we simply return the new account object as
 * JSON
 *
 * @function
 *
 * @param {Object} req - The http request.
 * @param {Object} res - The http response.
 */
function defaultJsonResponse(req, res) {
  helpers.strippedAccountResponse(req.user, res);
}
 
/**
 * The Stormpath API requires the `givenName` and `surname` fields to be
 * provided, but as a convenience our framework integrations allow you to
 * omit this data and fill those fields with the string `UNKNOWN` - but only
 * if the field is not explicitly required.
 *
 * @function
 *
 * @param {Object} stormpathConfig - The express-stormpath configuration object
 * @param {Object} req - The http request.
 */
function applyDefaultAccountFields(stormpathConfig, req) {
  var registerFields = stormpathConfig.web.register.form.fields;
 
  if ((!registerFields.givenName || !registerFields.givenName.required || !registerFields.givenName.enabled) && !req.body.givenName) {
    req.body.givenName = 'UNKNOWN';
  }
 
  if ((!registerFields.surname || !registerFields.surname.required || !registerFields.surname.enabled) && !req.body.surname) {
    req.body.surname = 'UNKNOWN';
  }
}
 
/**
 * Register a new user -- either via a JSON API, or via a browser.
 *
 * @method
 *
 * @param {Object} req - The http request.
 * @param {Object} res - The http response.
 * @param {function} next - The next callback.
 */
module.exports = function (req, res, next) {
  var application = req.app.get('stormpathApplication');
  var config = req.app.get('stormpathConfig');
  var logger = req.app.get('stormpathLogger');
  var view = config.web.register.view;
 
  function handlePreRegistration(formData, callback) {
    var preRegistrationHandler = config.preRegistrationHandler;
 
    if (preRegistrationHandler) {
      return preRegistrationHandler(formData, req, res, callback);
    }
 
    callback();
  }
 
  function handleResponse(account, responseHandler) {
    var postRegistrationHandler = config.postRegistrationHandler;
 
    if (postRegistrationHandler) {
      return postRegistrationHandler(account, req, res, responseHandler.bind(null, req, res));
    }
 
    responseHandler(req, res);
  }
 
  helpers.getFormViewModel('register', config, function (err, viewModel) {
    Iif (err) {
      return helpers.writeJsonError(res, err);
    }
 
    helpers.handleAcceptRequest(req, res, {
      'application/json': function () {
        switch (req.method) {
          case 'GET':
            res.status(200).json(viewModel);
            break;
 
          case 'POST':
            applyDefaultAccountFields(config, req);
 
            handlePreRegistration(req.body, function (err) {
              if (err) {
                return helpers.writeJsonError(res, err);
              }
 
              helpers.validateAccount(req.body, config, function (errors) {
                if (errors) {
                  return helpers.writeJsonError(res, errors[0]);
                }
 
                helpers.prepAccountData(req.body, config, function (accountData) {
                  application.createAccount(accountData, function (err, account) {
                    Iif (err) {
                      return helpers.writeJsonError(res, err);
                    }
 
                    if (config.web.register.autoLogin) {
                      var options = {
                        username: req.body.email,
                        password: req.body.password
                      };
 
                      return helpers.authenticate(options, req, res, function (err, account, authResult) {
                        Iif (err) {
                          return helpers.writeJsonError(res, err);
                        }
 
                        helpers.createSession(authResult, account, req, res);
 
                        handleResponse(account, defaultJsonResponse);
                      });
                    }
 
                    helpers.expandAccount(account, config.expand, logger, function (err, expandedAccount) {
                      Iif (err) {
                        return helpers.writeJsonError(res, err);
                      }
 
                      req.user = expandedAccount;
 
                      handleResponse(expandedAccount, defaultJsonResponse);
                    });
                  });
                });
              });
            });
            break;
 
          default:
            next();
        }
      },
      'text/html': function () {
        var writeFormError = helpers.writeFormError.bind(null, req, res, view, viewModel);
 
        switch (req.method) {
          // We should render the registration template.
          case 'GET':
            helpers.render(req, res, view, {
              form: helpers.sanitizeFormData(req.body),
              formModel: viewModel.form
            });
            break;
 
          // The user is submitting a registration request, so we should attempt
          // to validate the user's data and create their account.
          case 'POST':
            async.waterfall([
              // What we'll do here is simply set default values for `givenName` and
              // `surname`, because these value are annoying to set if you don't
              // care about them.  Eventually Stormpath is going to remove these
              // required fields, but for now this is a decent workaround to ensure
              // people don't have to deal with that stuff.
              function (callback) {
                applyDefaultAccountFields(config, req);
                callback();
              },
              function (callback) {
                handlePreRegistration(req.body, function (err) {
                  Iif (err) {
                    return writeFormError(err);
                  }
 
                  helpers.validateAccount(req.body, config, function (errors) {
                    if (errors) {
                      return writeFormError(errors[0]);
                    }
 
                    callback();
                  });
                });
              },
              function (callback) {
                helpers.prepAccountData(req.body, config, function (accountData) {
                  application.createAccount(accountData, function (err, account) {
                    if (err) {
                      logger.info('A user tried to create a new account, but this operation failed with an error message: ' + err.developerMessage);
                      callback(err);
                    } else {
                      res.locals.user = account;
                      req.user = account;
                      callback(null, account);
                    }
                  });
                });
              }
            ], function (err, account) {
              if (err) {
                return writeFormError(err);
              }
 
              //console.log('Register account status!', account.status);
 
              if (account.status === 'UNVERIFIED') {
                return handleResponse(account, defaultUnverifiedHtmlResponse);
              }
 
              if (config.web.register.autoLogin) {
                var options = {
                  username: req.body.email,
                  password: req.body.password
                };
 
                return helpers.authenticate(options, req, res, function (err, expandedAccount, authResult) {
                  Iif (err) {
                    return writeFormError(err);
                  }
 
                  helpers.createSession(authResult, expandedAccount, req, res);
 
                  handleResponse(expandedAccount, defaultAutoAuthorizeHtmlResponse);
                });
              }
 
              helpers.expandAccount(account, config.expand, logger, function (err, expandedAccount) {
                req.user = expandedAccount;
 
                handleResponse(expandedAccount, defaultCreatedHtmlResponse);
              });
            });
            break;
 
          default:
            next();
        }
      }
    }, next);
  });
};