From 5594141e67603aa56d556084f556eb1d72bce962 Mon Sep 17 00:00:00 2001 From: Chris Nissen Date: Wed, 5 Dec 2018 16:45:57 -0700 Subject: [PATCH] Refactored so as not to calculate the variable values twice. --- .../AuthorizationValidationRule.cs | 30 ++++++++++--------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/src/GraphQL.Authorization/AuthorizationValidationRule.cs b/src/GraphQL.Authorization/AuthorizationValidationRule.cs index 182e839..1f8de8a 100644 --- a/src/GraphQL.Authorization/AuthorizationValidationRule.cs +++ b/src/GraphQL.Authorization/AuthorizationValidationRule.cs @@ -60,37 +60,39 @@ public INodeVisitor Validate(ValidationContext context) }); } - private bool SkipAuthCheck(Field fieldAst, ValidationContext context) + private bool SkipAuthCheck(Field field, ValidationContext context) { - if (fieldAst.Directives == null || !fieldAst.Directives.Any()) return false; + if (field.Directives == null || !field.Directives.Any()) return false; - var includeField = GetDirectiveValue(context, fieldAst.Directives, DirectiveGraphType.Include); + var operationName = context.OperationName; + var documentOperations = context.Document.Operations; + var operation = !string.IsNullOrWhiteSpace(operationName) + ? documentOperations.WithName(operationName) + : documentOperations.FirstOrDefault(); + var variables = ExecutionHelper.GetVariableValues(context.Document, context.Schema, + operation?.Variables, context.Inputs); + + var includeField = GetDirectiveValue(context, field.Directives, DirectiveGraphType.Include, variables); if (includeField.HasValue) return !includeField.Value; - var skipField = GetDirectiveValue(context, fieldAst.Directives, DirectiveGraphType.Skip); + var skipField = GetDirectiveValue(context, field.Directives, DirectiveGraphType.Skip, variables); if (skipField.HasValue) return skipField.Value; return false; } - private static bool? GetDirectiveValue(ValidationContext context, Directives directives, DirectiveGraphType directiveType) + private static bool? GetDirectiveValue(ValidationContext context, Directives directives, DirectiveGraphType directiveType, Variables variables) { var directive = directives.Find(directiveType.Name); if (directive == null) return null; - var operationName = context.OperationName; - var documentOperations = context.Document.Operations; - var operation = !string.IsNullOrWhiteSpace(operationName) - ? documentOperations.WithName(operationName) - : documentOperations.FirstOrDefault(); - - var values = ExecutionHelper.GetArgumentValues( + var argumentValues = ExecutionHelper.GetArgumentValues( context.Schema, directiveType.Arguments, directive.Arguments, - ExecutionHelper.GetVariableValues(context.Document, context.Schema, operation?.Variables, context.Inputs)); + variables); - values.TryGetValue("if", out object ifObj); + argumentValues.TryGetValue("if", out object ifObj); return bool.TryParse(ifObj?.ToString() ?? string.Empty, out bool ifVal) && ifVal; }