3 var env = require('gitter-web-env');
4 var logger = env.logger;
5 var url = require('url');
6 var debug = require('debug')('gitter:infra:login-required-middleware');
8 var validAuthProviders = {
16 module.exports = function(req, res) {
17 // Are we dealing with an API client? Tell em in HTTP
18 // Windows Phone sends accept: */* for oauth logins. Reported by @RReverser
19 if (!req.nonApiRoute && req.accepts(['json', 'html']) === 'json') {
20 /* API client without access, shouldn't really happen :( */
21 logger.warn('User is not logged in, denying access');
23 return res.status(401).send({ success: false, loginRequired: true });
27 req.session.returnTo = req.originalUrl;
30 var authProvider = getAuthProviderIfValid(req);
33 // tracking data from the original request needs to be passed on to the
35 if (req.query.action) query.action = req.query.action;
36 if (req.query.source) query.source = req.query.source;
38 debug('User is not logged in, redirecting to %s login page', authProvider);
40 var redirect = url.format({ pathname: '/login/' + authProvider, query: query });
41 return res.relativeRedirect(redirect);
44 debug('User is not logged in, redirecting to login page');
45 // login page buttons provide their own tracking querystrings,
46 // so none are needed here
47 return res.relativeRedirect('/login');
50 function getAuthProviderIfValid(req) {
51 var authProvider = req.query.auth_provider;
53 if (!validAuthProviders[authProvider]) {
54 debug('invalid auth provider "%s", skipping', authProvider);