Gitter migration: Setup redirects (rollout pt. 3)
[gitter.git] / server / web / middlewares / passport-callback-for-strategy.js
blob6d3b1d93a2851984a82e5f5249932f9c277e7d76
1 'use strict';
3 var env = require('gitter-web-env');
4 var stats = env.stats;
5 var errorReporter = env.errorReporter;
7 var passport = require('passport');
8 var client = require('gitter-web-utils/lib/redis').getClient();
9 var lock = require('redis-lock')(client);
10 var validatedMessage = require('../validated-message');
12 module.exports = function passportCallbackForStrategy(strategy, options) {
13 var handler = passport.authorize(strategy, options);
14 return function(req, res, next) {
15 var code = req.query.code;
16 lock('oalock:' + code, function(done) {
17 handler(req, res, function(err) {
18 done(function() {
19 if (err) {
20 stats.event('login_failure');
22 var errorOptions = {
23 additionalErrorInfo: err.toString(), // passportjs.InternalOAuthError will return additional information in it's toString
24 username: req.user && req.user.username,
25 url: req.url,
26 userHasSession: !!req.session
28 errorOptions[strategy + 'CallbackFailed'] = 'failed';
29 errorReporter(err, errorOptions, { module: 'login-handler' });
31 if (strategy.indexOf('upgrade') >= 0) {
32 res.redirect('/login/upgrade-failed');
33 } else {
34 /* For some reason, the user is now logged in, just continue as normal */
35 var user = req.user;
36 if (user) {
37 if (req.session && req.session.returnTo) {
38 res.redirect(req.session.returnTo);
39 } else {
40 res.redirect('/' + user.username);
42 return;
45 if (err.message) {
46 var check = validatedMessage.getCheck(err.message);
47 res.redirect(
48 '/login/failed?message=' +
49 encodeURIComponent(err.message) +
50 '&check=' +
51 encodeURIComponent(check)
53 } else {
54 res.redirect('/login/failed');
57 } else {
58 next();
60 });
61 });
62 });