@@ -29,32 +29,43 @@ module.exports = (app) => {
29
29
next ( )
30
30
} )
31
31
32
+ let access = [ ]
32
33
// add Authenticator check if route has auth
33
34
if ( def . auth ) {
35
+ // default access roles
36
+ access = def . access || [ ]
34
37
actions . push ( ( req , res , next ) => {
35
38
authenticator ( _ . pick ( config , [ 'AUTH_SECRET' , 'VALID_ISSUERS' ] ) ) ( req , res , next )
36
39
} )
37
-
38
40
actions . push ( ( req , res , next ) => {
39
- if ( req . authUser . isMachine ) {
40
- // M2M
41
- if ( ! req . authUser . scopes || ! helper . checkIfExists ( def . scopes , req . authUser . scopes ) ) {
42
- next ( new errors . ForbiddenError ( 'You are not allowed to perform this action!' ) )
41
+ if ( ! req . authUser ) {
42
+ return next ( new errors . UnauthorizedError ( 'Action is not allowed for invalid token' ) )
43
+ }
44
+ req . authUser . userId = String ( req . authUser . userId )
45
+ req . auth = req . authUser
46
+ req . auth . sub = req . auth . userId
47
+ if ( req . authUser . roles ) {
48
+ // all access are allowed
49
+ if ( _ . isEmpty ( access ) ) {
50
+ next ( )
51
+ } else if ( ! helper . checkIfExists ( access , req . authUser . roles ) ) {
52
+ res . forbidden = true
53
+ next ( new errors . ForbiddenError ( 'You are not allowed to perform this action' ) )
43
54
} else {
44
55
next ( )
45
56
}
46
- } else {
47
- req . authUser . userId = String ( req . authUser . userId )
48
- // User
49
- if ( req . authUser . roles ) {
50
- if ( ! helper . checkIfExists ( def . access , req . authUser . roles ) ) {
51
- next ( new errors . ForbiddenError ( 'You are not allowed to perform this action!' ) )
52
- } else {
53
- next ( )
54
- }
57
+ } else if ( req . authUser . scopes ) {
58
+ if ( _ . isNil ( def . scopes ) || _ . isEmpty ( def . scopes ) ) {
59
+ next ( )
60
+ } else if ( ! helper . checkIfExists ( def . scopes , req . authUser . scopes ) ) {
61
+ next ( new errors . ForbiddenError ( 'You are not allowed to perform this action!' ) )
55
62
} else {
56
- next ( new errors . ForbiddenError ( 'You are not authorized to perform this action' ) )
63
+ next ( )
57
64
}
65
+ } else if ( ( _ . isArray ( def . access ) && def . access . length > 0 ) || ( _ . isArray ( def . scopes ) && def . scopes . length > 0 ) ) {
66
+ next ( new errors . UnauthorizedError ( 'You are not authorized to perform this action' ) )
67
+ } else {
68
+ next ( )
58
69
}
59
70
} )
60
71
}
0 commit comments