-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
52 lines (40 loc) · 1.52 KB
/
index.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
const createError = require('http-errors')
module.exports = (opts) => {
const defaults = {
allowedRoles: []
}
const options = Object.assign({}, defaults, opts)
/**
* allowedRoles param can be a single role string (e.g. Role.User or 'User')
* or an array of roles (e.g. [Role.Admin, Role.User] or ['Admin', 'User'])
**/
if (typeof options.allowedRoles === 'string') {
options.allowedRoles = [options.allowedRoles]
}
return {
before: (handler, next) => {
const allowedRoles = options.allowedRoles
if (allowedRoles.length === 0) {
next()
}
const authorizer = 'authorizer' in handler.event.requestContext ? handler.event.requestContext.authorizer : null
if (authorizer === null) {
throw new createError.Unauthorized('Unauthorized')
}
let userGroups = 'cognito:groups' in authorizer.claims ? authorizer.claims['cognito:groups'] : []
if (typeof userGroups === 'string') {
userGroups = [userGroups]
}
if (userGroups === undefined || userGroups.length === 0) {
throw new createError.Forbidden('You don\'t have any role associated with your account')
}
// Checking if userGroups contains at least one item from allowedRoles
if (allowedRoles.length && !userGroups.some((val) => allowedRoles.includes(val))) {
// user's role is not authorized
throw new createError.Forbidden('You don\'t have the permission to access this resource')
}
// authorization successful
next()
}
}
}