Gitter migration: Setup redirects (rollout pt. 3)
[gitter.git] / server / web / middlewares / logout-destroy-tokens.js
blob29df5b121bf5f54707a7a75ca04331c1e3ea13c8
1 'use strict';
3 var env = require('gitter-web-env');
4 var logger = env.logger;
5 var stats = env.stats;
6 var StatusError = require('statuserror');
8 var logout = require('./logout');
9 var oauthService = require('gitter-web-oauth');
10 var userService = require('gitter-web-users');
12 module.exports = function(req, res, next) {
13 var user = req.user;
14 var userId = user && user.id;
15 var username = user && user.username;
17 logger.warn('logout-destroy-tokens: performing logout', {
18 userId: userId,
19 username: username
20 });
22 stats.event('logout_destroy_user_tokens', { userId: userId, username: username });
24 if (req.session) {
25 logout(req, res, postLogout);
26 } else {
27 postLogout();
30 function send() {
31 // Are we dealing with an API client? Tell em in HTTP
32 if (req.accepts(['json', 'html']) === 'json') {
33 logger.error('User no longer has a token');
34 res.status(401).send({ success: false, loginRequired: true });
35 return;
38 /* Not a web client? Give them the message straightup */
39 if (req.headers.authorization) {
40 return next(new StatusError(401));
43 return res.relativeRedirect('/');
46 function postLogout(err) {
47 if (err) logger.warn('Unable to log user out');
49 if (!user) return send(req, res, next);
50 var userId = user._id;
52 userService
53 .destroyTokensForUserId(userId)
54 .catch(function(err) {
55 logger.error('Unable to destroy tokens for user: ' + err, { exception: err });
57 .then(function() {
58 return oauthService.removeAllAccessTokensForUser(userId);
60 .catch(function(err) {
61 logger.error('Unable to remove access tokens: ' + err, { exception: err });
63 .then(function() {
64 send(req, res, next);
65 return null;
66 });