import { RequestHandler , RouteMethod } from 'src/core/server' ; import { AuthenticatedUser } from '../../../../security/server' ; import { ReportingCore } from '../../core' ; import { getUser } from './get_user' ; import type { ReportingRequestHandlerContext } from '../../types' ; const superuserRole = 'superuser' ; type ReportingRequestUser = AuthenticatedUser | false ; export type RequestHandlerUser < P , Q , B > = RequestHandler < P , Q , B , ReportingRequestHandlerContext > extends ( ... a : infer U ) => infer R ? ( user : ReportingRequestUser , ... a : U ) => R : never ; export const authorizedUserPreRouting = < P , Q , B > ( reporting , handler ) : RequestHandler < P , Q , B , ReportingRequestHandlerContext , RouteMethod > => { const { logger , security } = reporting . getPluginSetupDeps ( ) ; return ( context , req , res ) => { try { let user = false ; if ( security && security . license . isEnabled ( ) ) { user = getUser ( req , security ) ; if ( ! user ) { return res . unauthorized ( { body : `Sorry, you aren't authenticated` } ) ; } } const deprecatedAllowedRoles = reporting . getDeprecatedAllowedRoles ( ) ; if ( user && deprecatedAllowedRoles !== false ) { const allowedRoles = deprecatedAllowedRoles || [ ] ; const authorizedRoles = [ superuserRole , ... allowedRoles ] ; if ( ! user . roles . find ( ( role ) => authorizedRoles . includes ( role ) ) ) { return res . forbidden ( { body : `Sorry, you don't have access to Reporting` } ) ; } } return handler ( user , context , req , res ) ; } catch ( err ) { logger . error ( err ) ; return res . custom ( { statusCode : 500 } ) ; } } ; } ;