3 const debug = require('debug')('gitter:app:gitlab:group-service');
4 const { Groups, GroupMembers } = require('gitlab');
5 const { secureWrapFunction } = require('gitter-web-cache-wrapper');
6 const getGitlabAccessTokenFromUser = require('./get-gitlab-access-token-from-user');
7 const getPublicTokenFromPool = require('./get-public-token-from-pool');
9 function cacheFunction(name, obj) {
10 return secureWrapFunction(`GitLabGroupService:${name}`, obj, async gitLabGroupService => {
11 const accessToken = await gitLabGroupService.getAccessTokenPromise;
16 // API reference: https://docs.gitlab.com/ee/api/groups.html
17 function standardizeGroupResponse(group) {
18 debug('standardizeGroupResponse', group);
22 name: group.full_name,
23 avatar_url: group.avatar_url,
25 absoluteUri: group.web_url
29 function GitLabGroupService(user) {
31 this.getAccessTokenPromise = getGitlabAccessTokenFromUser(user);
34 GitLabGroupService.prototype._getGitlabOpts = async function() {
35 const accessToken = await this.getAccessTokenPromise;
37 oauthToken: accessToken,
38 token: getPublicTokenFromPool()
42 GitLabGroupService.prototype.getGroups = cacheFunction('getGroups', async function(params) {
43 const resource = new Groups(await this._getGitlabOpts());
44 const res = await resource.all(params);
46 return (res || []).map(standardizeGroupResponse);
49 GitLabGroupService.prototype.getGroup = cacheFunction('getGroup', async function(id) {
50 const resource = new Groups(await this._getGitlabOpts());
51 const group = await resource.show(id);
53 return standardizeGroupResponse(group);
56 GitLabGroupService.prototype._getGroupMember = async function(groupId, gitlabUserId) {
57 const gitlabLibOpts = await this._getGitlabOpts();
58 const groupMembers = new GroupMembers(gitlabLibOpts);
61 const groupMember = await groupMembers.show(groupId, gitlabUserId, {
62 includeInherited: true
64 debug('isMember groupMember response =>', groupMember);
67 debug('isMember error =>', err);
68 if (err && err.response && err.response.status === 404) {
76 GitLabGroupService.prototype.getMembership = cacheFunction('getMembership', async function(
80 const groupMember = await this._getGroupMember(groupId, gitlabUserId);
83 accessLevel = groupMember.access_level;
86 // https://docs.gitlab.com/ee/api/access_requests.html
89 isMember: [10, 20, 30, 40, 50].some(level => level === accessLevel),
90 isMaintainer: [40, 50].some(level => level === accessLevel),
91 isOwner: accessLevel === 50
95 module.exports = GitLabGroupService;