1
- import { DefaultContext , DefaultState , Middleware } from 'koa'
1
+ import { Middleware } from 'koa'
2
+ import { get } from 'lodash'
2
3
import { Parser } from 'n3'
3
4
import { vcard } from 'rdf-namespaces'
4
5
5
- export const authorizeGroups =
6
- ( groups : string [ ] ) : Middleware < { user : string } > =>
7
- async ( ctx , next ) => {
8
- // if array of groups are empty, we allow everybody (default)
9
- if ( groups . length === 0 ) return await next ( )
10
-
11
- const user = ctx . state . user
12
-
13
- const isAllowed = await isSomeGroupMember ( user , groups )
14
-
15
- if ( ! isAllowed ) {
16
- return ctx . throw (
17
- 403 ,
18
- 'Authenticated user is not a member of any allowed group' ,
19
- )
20
- }
21
-
22
- await next ( )
23
- }
6
+ export const authorizeGroups = (
7
+ groups : string [ ] ,
8
+ ) : Middleware < { user : string } > =>
9
+ checkGroupMembership (
10
+ groups ,
11
+ 'state.user' ,
12
+ 403 ,
13
+ 'Authenticated user is not a member of any allowed group' ,
14
+ )
24
15
25
16
const isSomeGroupMember = async ( user : string , groups : string [ ] ) => {
26
17
const memberships = await Promise . allSettled (
@@ -37,29 +28,24 @@ const isSomeGroupMember = async (user: string, groups: string[]) => {
37
28
/**
38
29
* Check whether a user specified in param is member of any of the given groups
39
30
*/
40
- export const checkParamGroupMembership =
41
- < T extends string > (
31
+ export const checkGroupMembership =
32
+ (
42
33
groups : string [ ] ,
43
- param : T ,
44
- ) : Middleware <
45
- DefaultState ,
46
- DefaultContext & { params : { [ K in T ] : string } }
47
- > =>
34
+ path : string ,
35
+ status : number ,
36
+ error = 'Person is not a member of any allowed group' ,
37
+ ) : Middleware =>
48
38
async ( ctx , next ) => {
49
39
// if array of groups are empty, we allow everybody (default)
50
40
if ( groups . length === 0 ) return await next ( )
51
- const webId = ctx . params [ param ]
41
+ const webId = get ( ctx , path )
42
+ if ( typeof webId !== 'string' )
43
+ throw new Error ( 'Expected string, got ' + typeof webId )
52
44
const isAllowed = await isSomeGroupMember ( webId , groups )
53
45
54
46
if ( ! isAllowed ) {
55
- return ctx . throw ( 400 , {
56
- error : 'Person is not a member of any allowed group' ,
57
- person : webId ,
58
- groups,
59
- } )
60
- }
61
-
62
- await next ( )
47
+ return ctx . throw ( status , error )
48
+ } else await next ( )
63
49
}
64
50
65
51
const isGroupMember = async ( user : string , group : string ) => {
0 commit comments