Merge branch 'hotfix/21.56.9' into master
[gitter.git] / server / web / middlewares / configure-csrf.js
blobe10d5d7be604b857a8d0e644a1749563b3996e89
1 'use strict';
3 var env = require('gitter-web-env');
4 var stats = env.stats;
5 var debug = require('debug')('gitter:infra:configure-csrf');
6 var oauthService = require('gitter-web-oauth');
7 var validateUserAgentFromReq = require('../validate-user-agent-from-req');
9 function setAccessToken(req, userId, accessToken) {
10 if (req.session) {
11 req.session['accessToken_' + (userId ? userId : '')] = accessToken;
14 req.accessToken = accessToken;
17 function getSessionAccessToken(req, userId) {
18 if (req.session) {
19 return req.session['accessToken_' + (userId ? userId : '')];
23 module.exports = function(req, res, next) {
24 var userId = req.user && req.user.id;
26 function generateAccessToken() {
27 if (req.user) {
28 debug('csrf: Using web token');
29 stats.eventHF('token.authenticated.web');
31 return oauthService
32 .findOrGenerateWebToken(req.user.id)
33 .spread(function(serverToken /*, client */) {
34 setAccessToken(req, userId, serverToken);
35 return null;
36 });
39 debug('csrf: Generating new anonymous token');
40 stats.eventHF('token.anonymous.generate');
42 /* Generate an anonymous token */
43 return oauthService.generateAnonWebToken().spread(function(token /*, client */) {
44 setAccessToken(req, null, token);
45 return null;
46 });
49 return validateUserAgentFromReq(req)
50 .then(() => {
51 /* OAuth clients have req.authInfo. Propagate their access token to their entire session
52 * so that all related web-requests are made by the same client
54 if (req.authInfo && req.authInfo.accessToken) {
55 debug('csrf: Using OAuth access token');
56 setAccessToken(req, userId, req.authInfo.accessToken);
57 return;
60 var sessionAccessToken = getSessionAccessToken(req, userId);
61 if (sessionAccessToken) {
62 return oauthService
63 .validateAccessTokenAndClient(sessionAccessToken)
64 .then(function(tokenInfo) {
65 if (!tokenInfo) {
66 return generateAccessToken();
69 req.accessToken = sessionAccessToken;
71 .catch(function(err) {
72 // We shouldn't try to regenerate something that was revoked
73 if (err.clientRevoked) {
74 throw err;
77 debug('csrf: OAuth access token validation failed: %j', err);
78 // Refresh anonymous tokens
79 return generateAccessToken();
80 });
83 return generateAccessToken();
85 .asCallback(next);