Gitter migration: Setup redirects (rollout pt. 3)
[gitter.git] / server / services / accept-invite-service.js
blob987dd9c0fd96c5493e8d50fbd30a1cf3817be1ae
1 'use strict';
3 var env = require('gitter-web-env');
4 var logger = env.logger;
5 var stats = env.stats;
7 var RoomWithPolicyService = require('gitter-web-rooms/lib/room-with-policy-service');
8 var troupeService = require('gitter-web-rooms/lib/troupe-service');
9 var invitesService = require('gitter-web-invites/lib/invites-service');
10 var StatusError = require('statuserror');
11 var assert = require('assert');
12 var Promise = require('bluebird');
13 var addInvitePolicyFactory = require('gitter-web-permissions/lib/add-invite-policy-factory');
15 /**
16 * Accepts an invitation and return the room the user has just joined
18 function acceptInvite(user, secret, options) {
19 assert(user);
21 return invitesService
22 .accept(user._id, secret)
23 .bind({
24 invite: null,
25 room: null
27 .then(function(invite) {
28 if (!invite) throw new StatusError(404);
29 this.invite = invite;
30 var troupeId = invite.troupeId;
31 return troupeService.findById(troupeId);
33 .then(function(room) {
34 if (!room) throw new StatusError(404);
35 this.room = room;
37 return addInvitePolicyFactory.createPolicyForRoomInvite(user, room, secret);
39 .then(function(policy) {
40 var roomWithPolicyService = new RoomWithPolicyService(this.room, user, policy);
41 var joinRoomOptions = {
42 source: options && options.source
44 return roomWithPolicyService.joinRoom(joinRoomOptions);
46 .then(function() {
47 return invitesService.markInviteAccepted(this.invite._id, user._id).return(this.room);
49 .tap(function() {
50 // Success statistics
51 var room = this.room;
52 var invite = this.invite;
53 stats.event('invite_accepted', {
54 source: options && options.source,
55 userId: user && (user.id || user._id),
56 troupeId: room && (room.id || room._id),
57 type: invite.type,
58 uri: room && room.uri
59 });
61 .catch(StatusError, function(err) {
62 if (err.status >= 500) throw err;
64 logger.error('Invitation accept failed', { exception: err });
66 if (this.invite) {
67 return invitesService.markInviteRejected(this.invite._id, user._id).throw(err);
70 throw err;
72 .catch(function(e) {
73 // Failure statistics
74 var room = this.room;
75 var invite = this.invite;
77 stats.event('invite_rejected', {
78 userId: user && (user.id || user._id),
79 troupeId: room && (room.id || room._id),
80 type: invite && invite.type,
81 uri: room && room.uri
82 });
84 throw e;
85 });
88 module.exports = {
89 acceptInvite: Promise.method(acceptInvite)