3 const debug = require('debug')('gitter:app:gitlab:group-service');
4 const { Users } = 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(`GitLabUserService:${name}`, obj, function(GitLabUserService) {
11 return GitLabUserService.getAccessTokenPromise;
15 function GitLabUserService(user) {
17 this.getAccessTokenPromise = getGitlabAccessTokenFromUser(user);
20 GitLabUserService.prototype._getGitlabOpts = async function() {
21 const accessToken = await this.getAccessTokenPromise;
23 oauthToken: accessToken,
24 token: getPublicTokenFromPool()
28 GitLabUserService.prototype._getUserResource = async function() {
29 if (this._groupsResource) {
30 return this._groupsResource;
33 const gitlabLibOpts = await this._getGitlabOpts();
34 this._groupsResource = new Users(gitlabLibOpts);
36 return this._groupsResource;
38 GitLabUserService.prototype.getUserById = cacheFunction('getUserById', async function(id) {
39 const resource = await this._getUserResource();
40 const user = await resource.show(id);
43 GitLabUserService.prototype.getUserByUsername = cacheFunction('getUserByUsername', async function(
46 const resource = await this._getUserResource();
47 const users = await resource.search(username);
48 const user = users.find(user => {
49 return user.username.toLowerCase() === username.toLowerCase();
51 debug(`getUserByUsername(${username}) found ${users.length} users -> ${user && user.username} `);
53 throw new Error(`Unable to find GitLab user with username: ${username}`);
59 module.exports = GitLabUserService;