Gitter migration: Setup redirects (rollout pt. 3)
[gitter.git] / server / web / middlewares / authenticate-bearer.js
blob25dc74ba05240d5300acac83bbce50e2fa75f4ed
1 'use strict';
3 var StatusError = require('statuserror');
4 var oauthService = require('gitter-web-oauth');
5 var validateUserAgentFromReq = require('../validate-user-agent-from-req');
6 var checkAlreadyOnUnauthorizedUrl = require('../../utils/check-already-on-unauthorized-url');
7 const getAccessToken = require('../get-access-token-from-req');
8 const passportLogin = require('../passport-login');
10 /**
13 module.exports = function(req, res, next) {
14 /* No access token? Continue! */
15 var accessToken = getAccessToken(req);
17 // Avoid a redirect loop even when someone is forcing a token via
18 // `?access_token=xxxtoken` query parameter or `Authorization: bearer xxxtoken` header
19 var alreadyOnUnauthorizedUrl = checkAlreadyOnUnauthorizedUrl(req.url);
20 if (!accessToken || alreadyOnUnauthorizedUrl) return next();
22 validateUserAgentFromReq(req)
23 .then(() => oauthService.validateAccessTokenAndClient(accessToken))
24 .then(function(tokenInfo) {
25 // Token not found
26 if (!tokenInfo) return next(new StatusError(401, 'Token not found'));
28 // Anonymous tokens cannot be used for Bearer tokens
29 if (!tokenInfo.user)
30 return next(new StatusError(401, 'Anonymous tokens cannot be used for Bearer tokens'));
32 var user = tokenInfo.user;
33 var client = tokenInfo.client;
34 return passportLogin(req, user).then(() => {
35 req.authInfo = { client: client, accessToken: accessToken };
36 next();
37 });
39 .catch(next);