Skip to content

Commit

Permalink
Refactored so as not to calculate the variable values twice.
Browse files Browse the repository at this point in the history
  • Loading branch information
chris-nissen committed Dec 5, 2018
1 parent e4aaebb commit 5594141
Showing 1 changed file with 16 additions and 14 deletions.
30 changes: 16 additions & 14 deletions src/GraphQL.Authorization/AuthorizationValidationRule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down

0 comments on commit 5594141

Please sign in to comment.