3 var env
= require('gitter-web-env');
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
) {
11 req
.session
['accessToken_' + (userId
? userId
: '')] = accessToken
;
14 req
.accessToken
= accessToken
;
17 function getSessionAccessToken(req
, userId
) {
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() {
28 debug('csrf: Using web token');
29 stats
.eventHF('token.authenticated.web');
32 .findOrGenerateWebToken(req
.user
.id
)
33 .spread(function(serverToken
/*, client */) {
34 setAccessToken(req
, userId
, serverToken
);
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
);
49 return validateUserAgentFromReq(req
)
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
);
60 var sessionAccessToken
= getSessionAccessToken(req
, userId
);
61 if (sessionAccessToken
) {
63 .validateAccessTokenAndClient(sessionAccessToken
)
64 .then(function(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
) {
77 debug('csrf: OAuth access token validation failed: %j', err
);
78 // Refresh anonymous tokens
79 return generateAccessToken();
83 return generateAccessToken();