import { AuthorizationContext , AuthorizationDecision , AuthorizationMetadata , } from '@loopback/authorization' ; import { securityId , UserProfile } from '@loopback/security' ; import _ from 'lodash' ; export async function basicAuthorization ( authorizationCtx , metadata ) { let currentUser ; if ( authorizationCtx . principals . length > 0 ) { const user = _ . pick ( authorizationCtx . principals [ 0 ] , [ 'id' , 'name' , 'roles' , ] ) ; currentUser = { [ securityId ] : user . id , name : user . name , roles : user . roles } ; } else { return AuthorizationDecision . DENY ; } if ( ! currentUser . roles ) { return AuthorizationDecision . DENY ; } if ( ! metadata . allowedRoles ) { return AuthorizationDecision . ALLOW ; } let roleIsAllowed = false ; for ( const role of currentUser . roles ) { if ( metadata . allowedRoles ! . includes ( role ) ) { roleIsAllowed = true ; break ; } } if ( ! roleIsAllowed ) { return AuthorizationDecision . DENY ; } if ( currentUser . roles . includes ( 'admin' ) || currentUser . roles . includes ( 'support' ) ) { return AuthorizationDecision . ALLOW ; } /**
     * Allow access only to model owners, using route as source of truth
     *
     * eg. @post('/users/{userId}/orders', ...) returns `userId` as args[0]
     */ if ( currentUser [ securityId ] === authorizationCtx . invocationContext . args [ 0 ] ) { return AuthorizationDecision . ALLOW ; } return AuthorizationDecision . DENY ; }