-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathApiKeyValidators.ts
46 lines (37 loc) · 1.21 KB
/
ApiKeyValidators.ts
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
import {Request} from 'express'
import {ApiKeyAttrs, ApiKeys} from '../db/models'
export function checkValidApiKey (req: Request): Promise<boolean> {
return new Promise((resolve, reject) => {
let apiKey = req.header('Authorization')
apiKey = apiKey && apiKey.split('Bearer ')[1]
if (!apiKey) {
reject(new Error('No API Key in request'))
}
ApiKeys.findOne({
where: {
key: apiKey
}
}).then((apiKey: ApiKeyAttrs) => {
if (apiKey.whitelist_domains && apiKey.whitelist_domains.length > 0) {
if (apiKey.whitelist_domains[0] === '*') {
return resolve()
}
if (apiKey.whitelist_domains.indexOf('Referer')) {
return resolve()
}
}
if (apiKey.whitelist_ips && apiKey.whitelist_ips.length > 0) {
if (apiKey.whitelist_ips[0] === '*') {
return resolve()
}
const clientIp = req.header('x-forwarded-for') || req.connection.remoteAddress
if (apiKey.whitelist_ips.indexOf(clientIp) !== -1) {
return resolve()
}
}
return reject(new Error('IP or Domain not in whitelist'))
}).catch((err) => {
reject(new Error('Invalid API Key'))
})
})
}