Merge branch 'hotfix/21.56.9' into master
[gitter.git] / server / api / v1 / user / groups.js
bloba7b03c7e5dea3e2f2e3f43f6d28e2b3b9ba482c5
1 'use strict';
3 var Promise = require('bluebird');
4 var mongoUtils = require('gitter-web-persistence-utils/lib/mongo-utils');
5 var StatusError = require('statuserror');
6 var policyFactory = require('gitter-web-permissions/lib/policy-factory');
7 var restful = require('../../../services/restful');
8 var restSerializer = require('../../../serializers/rest-serializer');
10 var groupService = require('gitter-web-groups/lib/group-service');
12 function performUpdateToUserGroup(req) {
13 var user = req.user;
14 if (!user) throw new StatusError(401);
16 var userId = user._id;
17 var groupId = req.params.userGroup;
18 var updatedGroup = req.body;
20 var promises = [];
22 if ('favourite' in updatedGroup) {
23 var fav = updatedGroup.favourite;
25 promises.push(groupService.updateFavourite(userId, groupId, fav));
28 return Promise.all(promises).then(function() {
29 if (req.accepts(['text', 'json']) === 'text') return;
31 var strategy = new restSerializer.GroupIdStrategy({
32 currentUserId: userId
33 });
35 return restSerializer.serializeObject(req.params.userGroup, strategy);
36 });
39 module.exports = {
40 id: 'userGroup',
42 index: function(req) {
43 if (!req.user) throw new StatusError(401);
45 var lean = (req.query.lean && parseInt(req.query.lean, 10)) || false;
47 if (req.query.type === 'admin') {
48 return restful.serializeAdminGroupsForUser(req.user, { lean: lean });
51 return restful.serializeGroupsForUserId(req.user._id, { lean: lean });
54 load: function(req, id) {
55 if (!mongoUtils.isLikeObjectId(id)) throw new StatusError(400);
57 return policyFactory
58 .createPolicyForGroupId(req.user, id)
59 .then(function(policy) {
60 // TODO: middleware?
61 req.userGroupPolicy = policy;
63 return req.method === 'GET' ? policy.canRead() : policy.canWrite();
65 .then(function(access) {
66 if (!access) return null;
68 return groupService.findById(id, { lean: true });
69 });
72 patch: function(req) {
73 return performUpdateToUserGroup(req);