-
Notifications
You must be signed in to change notification settings - Fork 75
/
Copy pathauthorisation.js
96 lines (84 loc) · 2.44 KB
/
authorisation.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
'use strict'
import atna from 'atna-audit'
import logger from 'winston'
import os from 'os'
import * as auditing from '../auditing'
import {config} from '../config'
import {promisify} from 'util'
config.authentication = config.get('authentication')
const himSourceID = config.get('auditing').auditEvents.auditSourceID
function genAuthAudit(remoteAddress) {
let audit = atna.construct.nodeAuthentication(
remoteAddress,
himSourceID,
os.hostname(),
atna.constants.OUTCOME_MINOR_FAILURE
)
audit = atna.construct.wrapInSyslog(audit)
return audit
}
function authoriseClient(channel, ctx) {
if (ctx.authenticated != null && channel.allow != null) {
if (ctx.authenticated.roles != null) {
for (const role of Array.from(channel.allow)) {
if (Array.from(ctx.authenticated.roles).includes(role)) {
return true
}
}
}
if (Array.from(channel.allow).includes(ctx.authenticated.clientID)) {
return true
}
}
return false
}
function authoriseIP(channel, ctx) {
if ((channel.whitelist != null ? channel.whitelist.length : undefined) > 0) {
return Array.from(channel.whitelist).includes(ctx.ip)
} else {
return false
}
}
export async function authorise(ctx, done) {
const channel = ctx.matchingChannel
if (
channel != null &&
(channel.authType === 'public' ||
authoriseClient(channel, ctx) ||
authoriseIP(channel, ctx))
) {
// authorisation succeeded
ctx.authorisedChannel = channel
logger.info(
`The request, '${ctx.request.path}' is authorised to access ${ctx.authorisedChannel.name}`
)
} else if (!channel) {
// Channel not found
ctx.response.status = 404
} else {
// authorisation failed
ctx.response.status = 401
if (config.authentication.enableBasicAuthentication) {
ctx.set('WWW-Authenticate', 'Basic')
}
logger.info(
`The request, '${ctx.request.path}', is not authorised to access any channels.`
)
auditing.sendAuditEvent(genAuthAudit(ctx.ip), () =>
logger.debug('Processed nodeAuthentication audit')
)
}
return done()
}
export async function koaMiddleware(ctx, next) {
const _authorise = promisify(authorise)
await _authorise(ctx)
if (ctx.authorisedChannel != null) {
await next()
}
}
// export private functions for unit testing
// note: you cant spy on these method because of this :(
if (process.env.NODE_ENV === 'test') {
exports.genAuthAudit = genAuthAudit
}