@@ -3,8 +3,9 @@ import type { Request, Response } from 'express'
3
3
4
4
import authorisationMiddleware from './authorisationMiddleware'
5
5
6
- function createToken ( authorities : string [ ] ) {
6
+ function createToken ( authorities : string [ ] , sub : string = 'USER1' ) {
7
7
const payload = {
8
+ sub,
8
9
user_name : 'USER1' ,
9
10
scope : [ 'read' , 'write' ] ,
10
11
auth_source : 'nomis' ,
@@ -17,14 +18,16 @@ function createToken(authorities: string[]) {
17
18
}
18
19
19
20
describe ( 'authorisationMiddleware' , ( ) => {
20
- let req : Request
21
+ let req : Request = {
22
+ path : '/index' ,
23
+ } as unknown as jest . Mocked < Request >
21
24
const next = jest . fn ( )
22
25
23
- function createResWithToken ( { authorities } : { authorities : string [ ] } ) : Response {
26
+ function createResWithToken ( { authorities, sub = 'USER1' } : { authorities : string [ ] ; sub ?: string } ) : Response {
24
27
return {
25
28
locals : {
26
29
user : {
27
- token : createToken ( authorities ) ,
30
+ token : createToken ( authorities , sub ) ,
28
31
} ,
29
32
} ,
30
33
redirect : jest . fn ( ) ,
@@ -61,4 +64,28 @@ describe('authorisationMiddleware', () => {
61
64
expect ( next ) . toHaveBeenCalled ( )
62
65
expect ( res . redirect ) . not . toHaveBeenCalled ( )
63
66
} )
67
+
68
+ it ( 'should redirect when trying to access contact search' , async ( ) => {
69
+ const res = createResWithToken ( { authorities : [ 'SOME_REQUIRED_ROLE' ] , sub : 'OTHER_USER' } )
70
+ req = {
71
+ path : '/contacts/something' ,
72
+ } as unknown as jest . Mocked < Request >
73
+
74
+ await authorisationMiddleware ( [ 'SOME_REQUIRED_ROLE' ] ) ( req , res , next )
75
+
76
+ expect ( next ) . not . toHaveBeenCalled ( )
77
+ expect ( res . redirect ) . toHaveBeenCalled ( )
78
+ } )
79
+
80
+ it ( 'should return next when trying to access contact search as authorised username' , async ( ) => {
81
+ const res = createResWithToken ( { authorities : [ 'SOME_REQUIRED_ROLE' ] , sub : 'MARCUSASPIN' } )
82
+ req = {
83
+ path : '/contacts/something' ,
84
+ } as unknown as jest . Mocked < Request >
85
+
86
+ await authorisationMiddleware ( [ 'SOME_REQUIRED_ROLE' ] ) ( req , res , next )
87
+
88
+ expect ( next ) . toHaveBeenCalled ( )
89
+ expect ( res . redirect ) . not . toHaveBeenCalled ( )
90
+ } )
64
91
} )
0 commit comments