|
| 1 | +using GraphQL.Resolvers; |
| 2 | +using GraphQL.Types; |
| 3 | +using GraphQL.Utilities; |
| 4 | +using Micro.Auth.Api.GraphQL.Directives.Exceptions; |
| 5 | +using Micro.Auth.Api.GraphQL.Directives.Extensions; |
| 6 | +using Microsoft.AspNetCore.Http; |
| 7 | + |
| 8 | +namespace Micro.Auth.Api.GraphQL.Directives |
| 9 | +{ |
| 10 | + public class RequirePermissionDirective : DirectiveGraphType |
| 11 | + { |
| 12 | + public const string DirectiveName = "requirePermission"; |
| 13 | + |
| 14 | + public RequirePermissionDirective() : base( |
| 15 | + DirectiveName, |
| 16 | + DirectiveLocation.Field, |
| 17 | + DirectiveLocation.Mutation, |
| 18 | + DirectiveLocation.Query, |
| 19 | + DirectiveLocation.FieldDefinition) |
| 20 | + { |
| 21 | + } |
| 22 | + } |
| 23 | + public class RequirePermissionDirectiveVisitor : BaseSchemaNodeVisitor |
| 24 | + { |
| 25 | + private readonly IHttpContextAccessor _contextAccessor; |
| 26 | + |
| 27 | + public RequirePermissionDirectiveVisitor(IHttpContextAccessor contextAccessor) |
| 28 | + { |
| 29 | + _contextAccessor = contextAccessor; |
| 30 | + } |
| 31 | + public override void VisitObjectFieldDefinition(FieldType field, IObjectGraphType type, ISchema schema) |
| 32 | + { |
| 33 | + var permission = field.GetAppliedPermission(); |
| 34 | + if (permission == null) |
| 35 | + { |
| 36 | + return; |
| 37 | + } |
| 38 | + |
| 39 | + var isAuthorized = _contextAccessor |
| 40 | + .HttpContext |
| 41 | + ?.User |
| 42 | + .HasClaim(x => x.Type == "Permission" && x.Value == permission); |
| 43 | + |
| 44 | + if (isAuthorized == true) |
| 45 | + { |
| 46 | + return; |
| 47 | + } |
| 48 | + |
| 49 | + field.Resolver = new AsyncFieldResolver<object>(async context => throw new NotAuthorizedException()); |
| 50 | + } |
| 51 | + } |
| 52 | +} |
0 commit comments