Merge branch 'hotfix/21.56.9' into master
[gitter.git] / server / api / private / check-invite.js
blobbf7a2a1edf2bac3b35ed9da428b2414394e6556f
1 'use strict';
3 var Promise = require('bluebird');
4 var StatusError = require('statuserror');
5 var isValidEmail = require('email-validator').validate;
6 var inviteValidation = require('gitter-web-invites/lib/invite-validation');
7 var invitesService = require('gitter-web-invites/lib/invites-service');
8 var BackendMuxer = require('gitter-web-backend-muxer');
9 var avatars = require('gitter-web-avatars');
10 var restSerializer = require('../../serializers/rest-serializer');
12 function getAvatar(userToInvite, type, externalId, emailAddress) {
13 if (userToInvite) {
14 return avatars.getForUser(userToInvite);
15 } else {
16 return inviteValidation.getAvatar(type, externalId, emailAddress);
20 function _findEmailAddress(invitingUser, userToInvite, type, externalId, emailAddress) {
21 if (emailAddress) {
22 if (!isValidEmail(emailAddress)) {
23 throw new StatusError(400);
26 return emailAddress;
29 if (userToInvite) {
30 var backendMuxer = new BackendMuxer(userToInvite);
31 return backendMuxer.getEmailAddress();
32 } else {
33 return invitesService.resolveEmailAddress(invitingUser, type, externalId);
37 var findEmailAddress = Promise.method(_findEmailAddress);
39 function findInvitationInfo(invitingUser, type, externalId, emailAddress) {
40 var userToInvite;
41 return invitesService
42 .findExistingUser(type, externalId)
43 .then(function(_userToInvite) {
44 userToInvite = _userToInvite;
45 return findEmailAddress(invitingUser, userToInvite, type, externalId, emailAddress);
47 .then(function(resolvedEmailAddress) {
48 if (!resolvedEmailAddress) throw new StatusError(428);
50 return {
51 user: userToInvite, // can be null/undefined
52 displayName: (userToInvite && userToInvite.displayName) || externalId,
53 emailAddress: resolvedEmailAddress,
54 avatarUrl: getAvatar(invitingUser, type, externalId, resolvedEmailAddress)
56 });
59 function checkInvite(req, res, next) {
60 var input = inviteValidation.parseAndValidateInput(req.query);
61 return findInvitationInfo(req.user, input.type, input.externalId, input.emailAddress)
62 .then(function(result) {
63 if (!result.user) {
64 return {
65 displayName: result.displayName,
66 avatarUrl: result.avatarUrl
70 var strategy = new restSerializer.UserStrategy();
71 return restSerializer.serializeObject(result.user, strategy).then(function(serializedUser) {
72 return {
73 user: serializedUser,
74 displayName: result.displayName,
75 avatarUrl: result.avatarUrl
77 });
79 .then(function(response) {
80 res.send(response);
82 .catch(next);
85 module.exports = checkInvite;