11namespace Common ;
22
3-
43using Microsoft . Azure . Functions . Worker ;
54using Microsoft . Azure . Functions . Worker . Http ;
65using Microsoft . Azure . Functions . Worker . Middleware ;
76using Microsoft . Extensions . Logging ;
7+ using Microsoft . Extensions . Options ;
88
99public class PermissionsMiddleware : IFunctionsWorkerMiddleware
1010{
1111 private readonly ICreateResponse _createResponse ;
1212 private readonly IRoleManager _roleManager ;
1313 private readonly ILogger < PermissionsMiddleware > _logger ;
14+ private readonly AuthConfig _authConfig ;
1415
15- public PermissionsMiddleware ( ICreateResponse createResponse , IRoleManager roleManager , ILogger < PermissionsMiddleware > logger )
16+ public PermissionsMiddleware ( ICreateResponse createResponse , IRoleManager roleManager , ILogger < PermissionsMiddleware > logger , IOptions < AuthConfig > authConfig )
1617 {
1718 _createResponse = createResponse ;
1819 _roleManager = roleManager ;
1920 _logger = logger ;
21+ _authConfig = authConfig . Value ;
2022 }
2123
2224 public async Task Invoke ( FunctionContext context , FunctionExecutionDelegate next )
2325 {
26+ if ( _authConfig . ByPassAuthentication )
27+ {
28+ _logger . LogInformation ( "Authentication is bypassed, skipping permissions check." ) ;
29+ await next ( context ) ;
30+ return ;
31+ }
32+
2433 if ( ! context . RequiresAuthentication ( ) )
2534 {
35+ _logger . LogInformation ( "No authentication required for this endpoint, skipping permissions check." ) ;
36+ await next ( context ) ;
37+ return ;
38+ }
39+ var requiredRoles = context . GetRequiredRoles ( ) ;
40+
41+ if ( requiredRoles . Length == 0 )
42+ {
43+ _logger . LogInformation ( "No specific roles required for this endpoint, skipping permissions check." ) ;
2644 await next ( context ) ;
2745 return ;
2846 }
2947
3048 var req = await context . GetHttpRequestDataAsync ( ) ;
3149 var user = ( Cis2User ) context . Items [ "Cis2User" ] ! ;
32- var requiredRoles = context . GetRequiredRoles ( ) ;
33-
3450 if ( requiredRoles . Length == 0 || requiredRoles . Any ( role => _roleManager . ValidateRole ( user , role ) ) )
3551 {
3652 await next ( context ) ;
@@ -43,8 +59,7 @@ public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next
4359
4460 private async Task HandleUnauthorizedAsync ( FunctionContext context , HttpRequestData request , string logMessage , string responseMessage )
4561 {
46- var logger = context . GetLogger < PermissionsMiddleware > ( ) ;
47- logger . LogWarning ( "Authorization Error: {LogMessage}" , logMessage ) ;
62+ _logger . LogWarning ( "Permissions Error: {LogMessage}" , logMessage ) ;
4863 var response = await _createResponse . CreateHttpResponseWithBodyAsync ( System . Net . HttpStatusCode . Forbidden , request , responseMessage ) ;
4964 context . GetInvocationResult ( ) . Value = response ;
5065 }
0 commit comments