|
| 1 | +using System.Security.Claims; |
| 2 | +using Hyperbee.Pipeline.Context; |
| 3 | +using Microsoft.Extensions.DependencyInjection; |
| 4 | + |
| 5 | +namespace Hyperbee.Pipeline.Auth; |
| 6 | + |
| 7 | +public static class PipelineAuthExtensions |
| 8 | +{ |
| 9 | + private const string ClaimsPrincipalKey = nameof( ClaimsPrincipalKey ); |
| 10 | + |
| 11 | + public static IPipelineBuilder<TInput, TNext> PipeIfClaim<TInput, TOutput, TNext>( |
| 12 | + this IPipelineBuilder<TInput, TOutput> builder, |
| 13 | + Claim claim, |
| 14 | + Func<IPipelineStartBuilder<TOutput, TOutput>, IPipelineBuilder<TOutput, TNext>> childBuilder ) |
| 15 | + { |
| 16 | + return (IPipelineBuilder<TInput, TNext>) builder |
| 17 | + .PipeIf( ( context, arg ) => |
| 18 | + { |
| 19 | + var claimsPrincipal = context.GetClaimsPrincipal(); |
| 20 | + |
| 21 | + return claimsPrincipal.HasClaim( x => x.Type == claim.Type && x.Value == claim.Value ); |
| 22 | + } |
| 23 | + , childBuilder ); |
| 24 | + |
| 25 | + } |
| 26 | + |
| 27 | + public static IPipelineBuilder<TInput, TOutput> WithAuth<TInput, TOutput>( |
| 28 | + this IPipelineStartBuilder<TInput, TOutput> builder, |
| 29 | + Func<IPipelineContext, TOutput, ClaimsPrincipal, bool> validateClaims ) |
| 30 | + { |
| 31 | + return builder |
| 32 | + .WithAuth() |
| 33 | + .Call( ( context, argument ) => |
| 34 | + { |
| 35 | + var claimsPrincipal = context.GetClaimsPrincipal(); |
| 36 | + |
| 37 | + if ( !validateClaims( context, argument, claimsPrincipal ) ) |
| 38 | + context.CancelAfter(); |
| 39 | + |
| 40 | + } ); |
| 41 | + } |
| 42 | + |
| 43 | + public static IPipelineBuilder<TInput, TOutput> WithAuth<TInput, TOutput>( |
| 44 | + this IPipelineStartBuilder<TInput, TOutput> builder ) |
| 45 | + { |
| 46 | + return builder.HookAsync( async ( context, argument, next ) => |
| 47 | + { |
| 48 | + context.GetClaimsPrincipal(); |
| 49 | + |
| 50 | + return await next( context, argument ); |
| 51 | + |
| 52 | + } ); |
| 53 | + } |
| 54 | + |
| 55 | + public static ClaimsPrincipal GetClaimsPrincipal( this IPipelineContext context ) |
| 56 | + { |
| 57 | + if ( context.Items.TryGetValue<ClaimsPrincipal>( ClaimsPrincipalKey, out var claimsPrincipal ) ) |
| 58 | + return claimsPrincipal; |
| 59 | + |
| 60 | + var claimsPrincipalAccessor = context.ServiceProvider.GetService<IClaimsPrincipalAccessor>(); |
| 61 | + claimsPrincipal = claimsPrincipalAccessor.ClaimsPrincipal; |
| 62 | + |
| 63 | + context.Items.SetValue( ClaimsPrincipalKey, claimsPrincipal ); |
| 64 | + return claimsPrincipal; |
| 65 | + } |
| 66 | + |
| 67 | + |
| 68 | +} |
0 commit comments