-
Notifications
You must be signed in to change notification settings - Fork 0
/
authenticator-github.js
80 lines (70 loc) · 2.49 KB
/
authenticator-github.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
const createError = require('http-errors');
const logger = require('./logger');
const installationManager = require('./manager-installation');
const installationInfoManager = require('./manager-installation-info');
const tokenManager = require('./manager-token');
const {
propEq,
find,
curry,
isNil,
} = require('ramda');
const { env: { NODE_ENV: environment = 'production', CLIENT_ID: appClientId } } = process;
const development = environment === 'development';
const throwErrorIf = curry((condition, message, input) => {
if (condition(input)) {
throw new Error(message);
}
return input;
});
const throwErrorIfNil = throwErrorIf(isNil);
const authenticator = (req, res, next) => {
if (development) {
req.user = {
username: 'username',
permissions: {
isAdmin: true,
},
};
return next();
}
const authHeader = req.get('authorization');
if (!authHeader || authHeader.indexOf('token ') !== 0) {
return next(createError.Unauthorized('Unauthorized'));
}
const token = authHeader.replace('token ', '');
const { params: { owner, repository } } = req;
tokenManager.getTokenInfo(token)
.then(({ client_id: clientId, login: username }) => {
if (clientId === appClientId) {
req.user = { username };
} else {
throw new Error('Wrong client id');
}
})
.then(() => installationManager.getInstallationId(owner))
.then(throwErrorIfNil('No installation id'))
.then(installationId => installationInfoManager.getInstallationInfo(token, installationId))
.then(throwErrorIfNil('No installation found'))
.then(({ repositories }) => find(propEq('full_name', `${owner}/${repository}`), repositories))
.then(throwErrorIfNil('Repository not found'))
.then(({ permissions: { push: canPush = false, pull: canPull = false, admin: isAdmin = false } }) => {
req.user = {
permissions: {
canPush,
canPull,
isAdmin,
},
...req.user,
};
if (!canPush || !canPull) {
throw new Error('Repository not accessible');
}
})
.then(next)
.catch(error => {
logger.error(error);
next(createError.Unauthorized('Unauthorized'));
});
};
module.exports = authenticator;