diff --git a/lib/helpers/login-with-oauth-provider.js b/lib/helpers/login-with-oauth-provider.js index 06ba9fe6..a6cdd7fd 100644 --- a/lib/helpers/login-with-oauth-provider.js +++ b/lib/helpers/login-with-oauth-provider.js @@ -1,9 +1,8 @@ 'use strict'; -var exchangeStormpathToken = require('./exchange-stormpath-token'); -var loginResponder = require('./login-responder'); var oauth = require('../oauth'); -var writeJsonError = require('./write-json-error'); +var loginResponder = require('./login-responder'); +var exchangeStormpathToken = require('./exchange-stormpath-token'); /** * loginWithOAuthProvider takes provider data, such as an access token, @@ -16,7 +15,12 @@ var writeJsonError = require('./write-json-error'); * @param {Object} res - The http response. */ module.exports = function loginWithOAuthProvider(options, req, res) { + var config = req.app.get('stormpathConfig'); var application = req.app.get('stormpathApplication'); + var preLoginHandler = config.preLoginHandler; + var postLoginHandler = config.postLoginHandler; + var preRegistrationHandler = config.preRegistrationHandler; + var postRegistrationHandler = config.postRegistrationHandler; application.getAccount(options, function (err, providerAccountResult) { if (err) { @@ -25,12 +29,44 @@ module.exports = function loginWithOAuthProvider(options, req, res) { var account = providerAccountResult.account; - exchangeStormpathToken(req, account, function (err, authenticationResult) { - if (err) { - return writeJsonError(res, err); - } + function continueWithTokenExchange() { + exchangeStormpathToken(req, account, function (err, authenticationResult) { + if (err) { + return oauth.errorResponder(req, res, err); + } + + loginResponder(authenticationResult, account, req, res); + }); + } + + function continueWithHandlers(preHandler, postHandler) { + preHandler(options, req, res, function (err) { + if (err) { + return oauth.errorResponder(req, res, err); + } + + if (postHandler) { + return postHandler(account, req, res, function (err) { + if (err) { + return oauth.errorResponder(req, res, err); + } + + continueWithTokenExchange(); + }); + } + + continueWithTokenExchange(); + }); + } + + if (preRegistrationHandler && providerAccountResult.created) { + return continueWithHandlers(preRegistrationHandler, postRegistrationHandler); + } + + if (preLoginHandler && !providerAccountResult.created) { + return continueWithHandlers(preLoginHandler, postLoginHandler); + } - loginResponder(authenticationResult, account, req, res); - }); + continueWithTokenExchange(); }); };