|
| 1 | +const GitHubApi = require('github') |
| 2 | +const headers = {'user-agent': 'authorizedkeys-github-server'} |
| 3 | +const timeout = 5000 |
| 4 | + |
| 5 | +module.exports = function (opts) { |
| 6 | + const token = opts.token |
| 7 | + opts = Object.assign({timeout, headers}, opts) |
| 8 | + opts.token = undefined |
| 9 | + |
| 10 | + const client = new GitHubApi(opts) |
| 11 | + client.authenticate({type: 'token', token}) |
| 12 | + |
| 13 | + return { |
| 14 | + get: function (query) { |
| 15 | + return getMembers(client, query).then(getKeysOfUsers.bind(null, client)) |
| 16 | + } |
| 17 | + } |
| 18 | +} |
| 19 | + |
| 20 | +function getMembers (client, {teamId, org, teamName}) { |
| 21 | + let q |
| 22 | + if (teamId) return getTeamMembers(client, teamId) |
| 23 | + |
| 24 | + if (!org) throw new Error('The option `org` is required.') |
| 25 | + if (!teamName) throw new Error('The option `teamName` is required.') |
| 26 | + return client.orgs.getTeams({org}).then(getMembersByTeamArray(client, teamName)) |
| 27 | +} |
| 28 | + |
| 29 | +function getMembersByTeamArray (client, teamName) { |
| 30 | + return function (res) { |
| 31 | + const team = res.data.find((t) => t.name === teamName) |
| 32 | + if (!team) throw new Error(`No team found with the name '${teamName}'`) |
| 33 | + return getTeamMembers(client, team.id) |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +function getTeamMembers (client, id) { |
| 38 | + return client.orgs.getTeamMembers({id}).then((res) => res.data.filter((m) => m.type === 'User')) |
| 39 | +} |
| 40 | + |
| 41 | +function getKeysOfUsers (client, users) { |
| 42 | + const getKey = getKeyOfUser.bind(null, client) |
| 43 | + return Promise.all(users.map(getKey)).then(function (keyz) { |
| 44 | + return users.map(function (user, i) { |
| 45 | + return { |
| 46 | + id: user.id, |
| 47 | + login: user.login, |
| 48 | + avatar_url: user.avatar_url, |
| 49 | + keys: keyz[i] |
| 50 | + } |
| 51 | + }) |
| 52 | + }) |
| 53 | +} |
| 54 | + |
| 55 | +function getKeyOfUser (client, user) { |
| 56 | + return client.users.getKeysForUser({username: user.login}).then((res) => res.data.map((k) => k.key)) |
| 57 | +} |
0 commit comments