Esempio n. 1
0
        internal bool TrySetPassword(UserWrapper user, Expression<Func<string>> valueSelector, ErrorBuilder errors)
        {
            string newPassword = valueSelector.Compile().Invoke();

             string passErr = ValidatePassword(newPassword);

             if (errors.Assert(passErr == null, passErr, valueSelector)) {

            string currentPassword = user.Password;

            user.Password = ProcessPasswordForStorage(newPassword);

            if (errors.ValidProperty(() => user.Password))
               return true;

            user.Password = currentPassword;
             }

             return false;
        }
Esempio n. 2
0
        public Result Change(ChangeInput input)
        {
            if (input == null) throw new ArgumentNullException("input");

             var errors = new ErrorBuilder();

             if (errors.NotValid(input)) {
            return errors;
             }

             string username = this.context.CurrentUserName;
             UserWrapper user = this.repo.FindUserByName(username);

             if (errors.Not(user != null, AccountResources.Validation_UserNotExist.FormatInvariant(username))
            || errors.Not(this.passServ.PasswordEquals(input.CurrentPassword, user.Password), AccountResources.Validation_CurrentPasswordIncorrect, () => input.CurrentPassword)
            || !this.passServ.TrySetPassword(user, () => input.NewPassword, errors)) {

            return errors;
             }

             this.repo.UpdateUser(user);

             return HttpStatusCode.OK;
        }
Esempio n. 3
0
        protected override void Configure(IObjectTypeDescriptor descriptor)
        {
            descriptor.ExtendMutation();
            descriptor.Field("createScrapeContext")
            .UseClientMutationId()
            .UseAutoSubscription()
            .Argument("input", arg => arg.Type <CreateScrapeContextInputType>())
            .Resolve(async ctx =>
            {
                var input   = ctx.ArgumentValue <CreateScrapeContextInput>("input");
                var plugins = ctx.SnowflakeService <IPluginManager>();
                var cullers = plugins.GetCollection <ICuller>()
                              .Where(c => input.Cullers.Contains(c.Name, StringComparer.InvariantCulture));
                var scrapers = plugins.GetCollection <IScraper>()
                               .Where(c => input.Scrapers.Contains(c.Name, StringComparer.InvariantCulture));
                var game = await ctx.SnowflakeService <IGameLibrary>().GetGameAsync(input.GameID);
                if (game == null)
                {
                    return(ErrorBuilder.New()
                           .SetCode("SCRP_NOTFOUND_GAME")
                           .SetMessage("The specified game does not exist.")
                           .Build());
                }
                var jobQueueFactory    = ctx.SnowflakeService <IAsyncJobQueueFactory>();
                var jobQueue           = jobQueueFactory.GetJobQueue <IScrapeContext, IEnumerable <ISeed> >(false);
                var guid               = await jobQueue.QueueJob(new GameScrapeContext(game, scrapers, cullers));
                IScrapeContext context = jobQueue.GetSource(guid);
                ctx.AssignGameGuid(game, guid);
                return(new CreateScrapeContextPayload()
                {
                    ClientMutationID = input.ClientMutationID,
                    ScrapeContext = context,
                    Game = game,
                    JobID = guid,
                });
            })
            .Type <NonNullType <CreateScrapeContextPayloadType> >();

            descriptor.Field("cancelScrapeContext")
            .Description("Requests cancellation of the specified scrape context. If this succeeds, the next iteration will halt the " +
                         "scrape context regardless of the stage. There is no way to determine whether or not " +
                         "the cancellation succeeded until the scrape context is moved to the next step. Only then will it be eligible for deletion.")
            .UseClientMutationId()
            .UseAutoSubscription()
            .Argument("input", arg => arg.Type <CancelScrapeContextInputType>())
            .Resolve(async ctx =>
            {
                var input = ctx.ArgumentValue <CancelScrapeContextInput>("input");

                var jobQueueFactory = ctx.SnowflakeService <IAsyncJobQueueFactory>();
                var jobQueue        = jobQueueFactory.GetJobQueue <IScrapeContext, IEnumerable <ISeed> >(false);

                var jobId         = input.JobID;
                var scrapeContext = jobQueue.GetSource(jobId);
                if (scrapeContext == null)
                {
                    return(ErrorBuilder.New()
                           .SetCode("SCRP_NOTFOUND_SCRAPECONTEXT")
                           .SetMessage("The specified scrape context does not exist.")
                           .Build());
                }
                jobQueue.RequestCancellation(jobId);

                var payload = new CancelScrapeContextPayload()
                {
                    ClientMutationID = input.ClientMutationID,
                    ScrapeContext    = scrapeContext,
                    JobID            = jobId,
                    Game             = ctx.GetAssignedGame(jobId)
                };
                await ctx.SendEventMessage(new OnScrapeContextCancelMessage(payload));
                return(payload);
            })
            .Type <NonNullType <CancelScrapeContextPayloadType> >();

            descriptor.Field("deleteScrapeContext")
            .Description("Deletes a scrape context, halting its execution.")
            .UseClientMutationId()
            .UseAutoSubscription()
            .Argument("input", arg => arg.Type <DeleteScrapeContextInputType>())
            .Resolve(async ctx =>
            {
                var input = ctx.ArgumentValue <DeleteScrapeContextInput>("input");

                var jobQueueFactory = ctx.SnowflakeService <IAsyncJobQueueFactory>();
                var jobQueue        = jobQueueFactory.GetJobQueue <IScrapeContext, IEnumerable <ISeed> >(false);

                if (!jobQueue.HasJob(input.JobID))
                {
                    return(ErrorBuilder.New()
                           .SetCode("SCRP_NOTFOUND_SCRAPECONTEXT")
                           .SetMessage("The specified scrape context does not exist.")
                           .Build());
                }

                jobQueue.RequestCancellation(input.JobID);
                await jobQueue.GetNext(input.JobID);
                bool result = jobQueue.TryRemoveSource(input.JobID, out var scrapeContext);

                var payload = new DeleteScrapeContextPayload()
                {
                    ScrapeContext = scrapeContext,
                    JobID         = input.JobID,
                    Success       = result,
                    Game          = ctx.GetAssignedGame(input.JobID)
                                    .ContinueWith(g =>
                    {
                        if (result)
                        {
                            ctx.RemoveAssignment(input.JobID);
                        }
                        return(g);
                    }).Unwrap()
                };
                await ctx.SendEventMessage(new OnScrapeContextDeleteMessage(payload));
                return(payload);
            })
            .Type <NonNullType <DeleteScrapeContextPayloadType> >();

            descriptor.Field("nextScrapeContextStep")
            .Description("Proceeds to the next step of the specified scrape context. " +
                         "Returns the output of the next step in the scrape context iterator, until " +
                         "it is exhausted. If the iterator is exhausted, `current` will be null, and `hasNext` will be false . " +
                         "If the specified scrape context does not exist, `context` and `current` will be null, and `hasNext` will be false. ")
            .UseClientMutationId()
            .UseAutoSubscription()
            .Argument("input", arg => arg.Type <NextScrapeContextStepInputType>())
            .Resolve(async ctx =>
            {
                var input    = ctx.ArgumentValue <NextScrapeContextStepInput>("input");
                var jobQueue = ctx.SnowflakeService <IAsyncJobQueueFactory>()
                               .GetJobQueue <IScrapeContext, IEnumerable <ISeed> >(false);
                var scrapeContext = jobQueue.GetSource(input.JobID);
                if (scrapeContext == null)
                {
                    return(ErrorBuilder.New()
                           .SetCode("SCRP_NOTFOUND_SCRAPECONTEXT")
                           .SetMessage("The specified scrape context does not exist.")
                           .Build());
                }

                var addSeeds = input.Seeds;
                if (addSeeds != null)
                {
                    foreach (var graft in addSeeds)
                    {
                        var seed = scrapeContext.Context[graft.SeedID];
                        if (seed == null)
                        {
                            continue;
                        }
                        var seedTree  = graft.Tree.ToSeedTree();
                        var seedGraft = seedTree.Collapse(seed, ISeed.ClientSource);
                        scrapeContext.Context.AddRange(seedGraft);
                    }
                }

                var(current, movedNext) = await jobQueue.GetNext(input.JobID);

                if (movedNext)
                {
                    var payload = new ScrapeContextStepPayload
                    {
                        ScrapeContext = scrapeContext,
                        Current       = current,
                        JobID         = input.JobID,
                        Game          = ctx.GetAssignedGame(input.JobID)
                    };
                    await ctx.SendEventMessage(new OnScrapeContextStepMessage(payload));
                    return(payload);
                }
                var completePayload = new ScrapeContextCompletePayload
                {
                    ScrapeContext = scrapeContext,
                    JobID         = input.JobID,
                    Game          = ctx.GetAssignedGame(input.JobID)
                };

                await ctx.SendEventMessage(new OnScrapeContextCompleteMessage(completePayload));
                return(completePayload);
            }).Type <NonNullType <ScrapeContextPayloadInterface> >();

            descriptor.Field("exhaustScrapeContextSteps")
            .Description("Exhausts the specified scrape context until completion. " +
                         "Returns the output of the last step of the scrape context, when there are no more remaining left to continue with.")
            .UseClientMutationId()
            .UseAutoSubscription()
            .Argument("input", arg => arg.Type <NextScrapeContextStepInputType>())
            .Resolve(async ctx =>
            {
                var input    = ctx.ArgumentValue <NextScrapeContextStepInput>("input");
                var jobQueue = ctx.SnowflakeService <IAsyncJobQueueFactory>()
                               .GetJobQueue <IScrapeContext, IEnumerable <ISeed> >(false);
                var scrapeContext = jobQueue.GetSource(input.JobID);
                if (scrapeContext == null)
                {
                    return(ErrorBuilder.New()
                           .SetCode("SCRP_NOTFOUND_SCRAPECONTEXT")
                           .SetMessage("The specified scrape context does not exist.")
                           .Build());
                }

                var addSeeds = input.Seeds;
                if (addSeeds != null)
                {
                    foreach (var graft in addSeeds)
                    {
                        var seed = scrapeContext.Context[graft.SeedID];
                        if (seed == null)
                        {
                            continue;
                        }
                        var seedTree  = graft.Tree.ToSeedTree();
                        var seedGraft = seedTree.Collapse(seed, ISeed.ClientSource);
                        scrapeContext.Context.AddRange(seedGraft);
                    }
                }

                await foreach (IEnumerable <ISeed> val in jobQueue.AsEnumerable(input.JobID))
                {
                    ScrapeContextStepPayload payload = new ScrapeContextStepPayload
                    {
                        ScrapeContext = scrapeContext,
                        Current       = val,
                        JobID         = input.JobID,
                        Game          = ctx.GetAssignedGame(input.JobID)
                    };
                    await ctx.SendEventMessage(new OnScrapeContextStepMessage(payload));
                }

                var completePayload = new ScrapeContextCompletePayload
                {
                    ScrapeContext = scrapeContext,
                    JobID         = input.JobID,
                    Game          = ctx.GetAssignedGame(input.JobID)
                };

                await ctx.SendEventMessage(new OnScrapeContextCompleteMessage(completePayload));
                return(completePayload);
            }).Type <NonNullType <ScrapeContextCompletePayloadType> >();

            descriptor.Field("applyScrapeContext")
            .Description("Applies the specified scrape results to the specified game as-is. Be sure to delete the scrape context afterwards.")
            .UseClientMutationId()
            .UseAutoSubscription()
            .Argument("input", arg => arg.Type <ApplyScrapeContextInputType>())
            .Resolve(async ctx =>
            {
                var input    = ctx.ArgumentValue <ApplyScrapeContextInput>("input");
                var jobQueue = ctx.SnowflakeService <IAsyncJobQueueFactory>()
                               .GetJobQueue <IScrapeContext, IEnumerable <ISeed> >(false);
                var gameLibrary    = ctx.SnowflakeService <IGameLibrary>();
                var pluginManager  = ctx.SnowflakeService <IPluginManager>();
                var fileTraversers = pluginManager.GetCollection <IFileInstallationTraverser>()
                                     .Where(c => input.FileTraversers.Contains(c.Name, StringComparer.InvariantCulture));

                var metaTraversers = pluginManager.GetCollection <IGameMetadataTraverser>()
                                     .Where(c => input.MetadataTraversers.Contains(c.Name, StringComparer.InvariantCulture));

                var scrapeContext = jobQueue.GetSource(input.JobID);
                if (scrapeContext == null)
                {
                    return(ErrorBuilder.New()
                           .SetCode("SCRP_NOTFOUND_SCRAPECONTEXT")
                           .SetMessage("The specified scrape context does not exist.")
                           .Build());
                }
                IGame game;

                if (input.GameID == default)
                {
                    game = await ctx.GetAssignedGame(input.GameID);
                }
                else
                {
                    game = await gameLibrary.GetGameAsync(input.GameID);
                }

                if (game == null)
                {
                    return(ErrorBuilder.New()
                           .SetCode("SCRP_NOTFOUND_GAME")
                           .SetMessage("The specified game does not exist.")
                           .Build());
                }

                foreach (var traverser in metaTraversers)
                {
                    await traverser.TraverseAll(game, scrapeContext.Context.Root, scrapeContext.Context);
                }

                foreach (var traverser in fileTraversers)
                {
                    await traverser.TraverseAll(game, scrapeContext.Context.Root, scrapeContext.Context);
                }

                var payload = new ApplyScrapeContextPayload
                {
                    Game          = game,
                    ScrapeContext = scrapeContext,
                };
                await ctx.SendEventMessage(new OnScrapeContextApplyMessage(input.JobID, payload));
                return(payload);
            }).Type <NonNullType <ApplyScrapeContextPayloadType> >();
        }
Esempio n. 4
0
        private CompositionResult TrySatisfyImportsStateMachine(PartManager partManager, ComposablePart part)
        {
            var result = CompositionResult.SucceededResult;

            while (partManager.State < ImportState.Composed)
            {
                var previousState = partManager.State;

                switch (partManager.State)
                {
                // "ed" states which represent a some sort of steady state and will
                // attempt to do a state transition
                case ImportState.NoImportsSatisfied:
                case ImportState.ImportsPreviewed:
                {
                    partManager.State = ImportState.PreExportImportsSatisfying;

                    var prereqImports = part.ImportDefinitions.Where(import => import.IsPrerequisite);
                    result = result.MergeResult(
                        TrySatisfyImportSubset(partManager, prereqImports, null));

                    partManager.State = ImportState.PreExportImportsSatisfied;
                    break;
                }

                case ImportState.PreExportImportsSatisfied:
                {
                    partManager.State = ImportState.PostExportImportsSatisfying;

                    var requiredImports = part.ImportDefinitions.Where(import => !import.IsPrerequisite);

                    result = result.MergeResult(
                        TrySatisfyImportSubset(partManager, requiredImports, null));

                    partManager.State = ImportState.PostExportImportsSatisfied;
                    break;
                }

                case ImportState.PostExportImportsSatisfied:
                {
                    partManager.State = ImportState.ComposedNotifying;

                    partManager.ClearSavedImports();
                    result = result.MergeResult(partManager.TryOnComposed());

                    partManager.State = ImportState.Composed;
                    break;
                }

                // "ing" states which represent some sort of cycle
                // These state should always return, error or not, instead of breaking
                case ImportState.ImportsPreviewing:
                {
                    // We shouldn't nomally ever hit this case but if we do
                    // then we should just error with a cycle error.
                    return(new CompositionResult(ErrorBuilder.CreatePartCycle(part)));
                }

                case ImportState.PreExportImportsSatisfying:
                case ImportState.PostExportImportsSatisfying:
                {
                    if (InPrerequisiteLoop())
                    {
                        return(result.MergeError(ErrorBuilder.CreatePartCycle(part)));
                    }
                    // Cycles in post export imports are allowed so just return in that case
                    return(result);
                }

                case ImportState.ComposedNotifying:
                {
                    // We are currently notifying so don't notify again just return
                    return(result);
                }
                }

                // if an error occured while doing a state transition
                if (!result.Succeeded)
                {
                    // revert to the previous state and return the error
                    partManager.State = previousState;
                    return(result);
                }
            }
            return(result);
        }
Esempio n. 5
0
        private static async Task <bool> AuthorizeWithPolicyAsync(
            IDirectiveContext context,
            AuthorizeDirective directive,
            ClaimsPrincipal principal)
        {
            IServiceProvider      services         = context.Service <IServiceProvider>();
            IAuthorizationService authorizeService =
                services.GetService <IAuthorizationService>();
            IAuthorizationPolicyProvider policyProvider =
                services.GetService <IAuthorizationPolicyProvider>();

            if (authorizeService == null || policyProvider == null)
            {
                return(string.IsNullOrWhiteSpace(directive.Policy));
            }

            AuthorizationPolicy policy = null;

            if (directive.Roles.Count == 0 &&
                string.IsNullOrWhiteSpace(directive.Policy))
            {
                policy = await policyProvider.GetDefaultPolicyAsync()
                         .ConfigureAwait(false);

                if (policy == null)
                {
                    context.Result = context.Result = ErrorBuilder.New()
                                                      .SetMessage(
                        AuthResources.AuthorizeMiddleware_NoDefaultPolicy)
                                                      .SetCode(AuthErrorCodes.NoDefaultPolicy)
                                                      .SetPath(context.Path)
                                                      .AddLocation(context.FieldSelection)
                                                      .Build();
                }
            }

            else if (!string.IsNullOrWhiteSpace(directive.Policy))
            {
                policy = await policyProvider.GetPolicyAsync(directive.Policy)
                         .ConfigureAwait(false);

                if (policy == null)
                {
                    context.Result = ErrorBuilder.New()
                                     .SetMessage(string.Format(
                                                     CultureInfo.InvariantCulture,
                                                     AuthResources.AuthorizeMiddleware_PolicyNotFound,
                                                     directive.Policy))
                                     .SetCode(AuthErrorCodes.PolicyNotFound)
                                     .SetPath(context.Path)
                                     .AddLocation(context.FieldSelection)
                                     .Build();
                }
            }

            if (context.Result == null && policy != null)
            {
                AuthorizationResult result =
                    await authorizeService.AuthorizeAsync(
                        principal, context, policy)
                    .ConfigureAwait(false);

                return(result.Succeeded);
            }

            return(false);
        }
Esempio n. 6
0
 public static GraphQLException BatchExecutor_CannotSerializeVariable(
     string variableName) =>
 new GraphQLException(ErrorBuilder.New()
                      .SetMessage("Could not serialize the specified variable `{0}`.", variableName)
                      .SetCode(ErrorCodes.Execution.CannotSerialize)
                      .Build());
Esempio n. 7
0
 public static GraphQLException SubscriptionExecutor_NoSubscribeResolver() =>
 new GraphQLException(ErrorBuilder.New()
                      .SetMessage("You must declare a subscribe resolver for subscription fields.")
                      .Build());
Esempio n. 8
0
 public static GraphQLException SubscriptionExecutor_ContextInvalidState() =>
 new GraphQLException(ErrorBuilder.New()
                      .SetMessage("The request context is in an invalid state for subscriptions.")
                      .Build());
Esempio n. 9
0
 public static IQueryResult ResponseTypeNotSupported() =>
 QueryResultBuilder.CreateError(
     ErrorBuilder.New()
     .SetMessage(AspNetCoreResources.ErrorHelper_ResponseTypeNotSupported)
     .Build());
Esempio n. 10
0
 public static GraphQLException OperationResolverHelper_NoOperationFound(
     DocumentNode documentNode) =>
 new GraphQLException(ErrorBuilder.New()
                      .SetMessage(ThrowHelper_OperationResolverHelper_NoOperationFound_Message)
                      .AddLocation(documentNode)
                      .Build());
Esempio n. 11
0
 public static GraphQLException SubscriptionExecutor_NoSubscribeResolver() =>
 new GraphQLException(ErrorBuilder.New()
                      .SetMessage(ThrowHelper_SubscriptionExecutor_NoSubscribeResolver_Message)
                      .Build());
Esempio n. 12
0
 public static GraphQLException SubscriptionExecutor_SubscriptionsMustHaveOneField() =>
 new GraphQLException(ErrorBuilder.New()
                      .SetMessage(ThrowHelper_SubscriptionExecutor_SubscriptionsMustHaveOneField_Message)
                      .Build());
Esempio n. 13
0
 public static GraphQLException SubscriptionExecutor_ContextInvalidState() =>
 new GraphQLException(ErrorBuilder.New()
                      .SetMessage(ThrowHelper_SubscriptionExecutor_ContextInvalidState_Message)
                      .Build());
Esempio n. 14
0
 public object Error9()
 {
     return(ErrorBuilder.New()
            .SetMessage("query error 9")
            .Build());
 }
Esempio n. 15
0
        public IReadOnlyDictionary <NameString, ArgumentValue> CoerceArguments(
            IVariableCollection variables,
            ITypeConversion converter)
        {
            if (_hasArgumentErrors)
            {
                throw new QueryException(_args.Values.Select(t => t.Error));
            }

            if (_vars == null)
            {
                return(_args);
            }

            var args = _args.ToDictionary(t => t.Key, t => t.Value);

            foreach (KeyValuePair <NameString, VariableValue> var in _vars)
            {
                IError error = null;

                if (!variables.TryGetVariable(
                        var.Value.VariableName,
                        out object value))
                {
                    value = var.Value.DefaultValue is IValueNode literal
                        ? var.Value.Type.ParseLiteral(literal)
                        : value = var.Value.DefaultValue;

                    if (var.Value.Type.IsNonNullType() && value is null)
                    {
                        error = ErrorBuilder.New()
                                .SetMessage(string.Format(string.Format(
                                                              CultureInfo.InvariantCulture,
                                                              TypeResources.ArgumentValueBuilder_NonNull,
                                                              var.Key,
                                                              TypeVisualizer.Visualize(var.Value.Type))))
                                .AddLocation(Selection)
                                .SetExtension(_argumentProperty, Path.New(var.Key))
                                .SetPath(_path)
                                .Build();
                    }
                }
                else
                {
                    error = InputTypeNonNullCheck.CheckForNullValueViolation(
                        var.Key,
                        var.Value.Type,
                        value,
                        converter,
                        message => ErrorBuilder.New()
                        .SetMessage(message)
                        .SetPath(_path.AppendOrCreate(ResponseName))
                        .AddLocation(Selection)
                        .SetExtension("argument", var.Key)
                        .Build());
                }

                if (error is null)
                {
                    args[var.Key] = new ArgumentValue(var.Value.Type, value);
                }
                else
                {
                    throw new QueryException(error);
                }
            }

            return(args);
        }
Esempio n. 16
0
 public static GraphQLException FieldVisibility_ValueNotSupported(IValueNode value) =>
 new GraphQLException(
     ErrorBuilder.New()
     .SetMessage(ThrowHelper_FieldVisibility_ValueNotSupported_Message)
     .AddLocation(value)
     .Build());
Esempio n. 17
0
        OperationResult<ResetResult> ResetImpl(ResetInput input)
        {
            if (input == null) throw new ArgumentNullException("input");

             var errors = new ErrorBuilder();

             if (errors.NotValid(input))
            return errors;

             UserWrapper user = this.repo.FindUserByEmail(input.Email);

             MailMessage message;
             string destinationEmail;

             bool canResetPassword = user != null
            && !user.Disabled;

             if (canResetPassword) {

            user.PasswordResetTicketExpiration = this.Configuration.GetNow()
               .Add(this.Configuration.PasswordResetTicketExpiration);

            this.repo.UpdateUser(user);

            string verificationTicket = new VerificationData(user.Id, null).GetVerificationTicket();
            string verificationUrl = AbsoluteUrl(this.Url.Action(Finish, verificationTicket));

            var mailModel = new VerificationMessageViewModel {
               SiteName = GetSiteName(),
               Url = verificationUrl
            };

            if (!EmailEquals(user.Email, user.Username))
               mailModel.Username = user.Username;

            destinationEmail = user.Email;

            message = new MailMessage {
               To = { destinationEmail },
               Subject = AccountResources.Model_PasswordResetVerificationMessageSubject,
               Body = RenderEmailView(Views.Password.Reset._VerificationMessage, mailModel)
            };

             } else {

            destinationEmail = input.Email;

            var mailModel = new ErrorMessageViewModel {
               SiteName = GetSiteName(),
               ErrorReason = (user == null) ?
                  ErrorReason.AccountNotFound
                  : ErrorReason.AccountDisabled
            };

            message = new MailMessage {
               To = { destinationEmail },
               Subject = AccountResources.Model_PasswordResetVerificationMessageSubject,
               Body = RenderEmailView(Views.Password.Reset._ErrorMessage, mailModel)
            };
             }

             SendEmail(message);

             return new OperationResult<ResetResult>(HttpStatusCode.Accepted, new ResetResult(destinationEmail));
        }
Esempio n. 18
0
 public static GraphQLException OperationCompiler_FragmentNoSelections(
     ISyntaxNode syntaxNode) =>
 new GraphQLException(ErrorBuilder.New()
                      .SetMessage("Fragment selection set is empty.")
                      .AddLocation(syntaxNode)
                      .Build());
Esempio n. 19
0
 public static GraphQLException RootTypeNotSupported(
     OperationType operationType) =>
 new GraphQLException(ErrorBuilder.New()
                      .SetMessage("The root type `{0}` is not supported.", operationType)
                      .Build());
Esempio n. 20
0
 public static GraphQLException OperationCompiler_NoOperationSelections(
     OperationDefinitionNode syntaxNode) =>
 new GraphQLException(ErrorBuilder.New()
                      .SetMessage("The operation has no selections.")
                      .AddLocation(syntaxNode)
                      .Build());
Esempio n. 21
0
 public static GraphQLException SubscriptionExecutor_SubscriptionsMustHaveOneField() =>
 new GraphQLException(ErrorBuilder.New()
                      .SetMessage("Subscription queries must have exactly one root field.")
                      .Build());
        public static FieldDelegate Use(FieldDelegate next)
        {
            return(async middlewareContext =>
            {
                var argumentNodes = middlewareContext.Selection.SyntaxNode.Arguments;

                if (argumentNodes is { Count : > 0 })
                {
                    var objectFieldOptions = middlewareContext.Field.ContextData.GetObjectFieldOptions();

                    for (var nodeIndex = 0; nodeIndex < argumentNodes.Count; nodeIndex++)
                    {
                        var argumentNode = argumentNodes[nodeIndex];

                        var argument = objectFieldOptions.Arguments.TryGetArgument(argumentNode.Name.Value);

                        if (argument is null)
                        {
                            continue;
                        }

                        var argumentOptions = argument.ContextData.GetArgumentOptions();

                        var shouldSkipValidation = await argumentOptions.SkipValidation !
                                                   .Invoke(new SkipValidationContext(middlewareContext, argument))
                                                   .ConfigureAwait(false);

                        if (shouldSkipValidation)
                        {
                            continue;
                        }

                        var inputValidators = argumentOptions.InputValidators !;

                        for (var validatorIndex = 0; validatorIndex < inputValidators.Count; validatorIndex++)
                        {
                            var inputValidator = inputValidators[validatorIndex];

                            var validationResult = await inputValidator
                                                   .Invoke(new InputValidatorContext(middlewareContext, argument))
                                                   .ConfigureAwait(false);

                            if (validationResult?.IsValid is null or true)
                            {
                                continue;
                            }

                            for (var errorIndex = 0; errorIndex < validationResult.Errors.Count; errorIndex++)
                            {
                                var validationFailure = validationResult.Errors[errorIndex];

                                var errorBuilder = ErrorBuilder.New();

                                argumentOptions.ErrorMapper !.Invoke(
                                    errorBuilder,
                                    new ErrorMappingContext(middlewareContext, argument, validationResult, validationFailure));

                                middlewareContext.ReportError(errorBuilder.Build());
                            }
                        }
                    }
                }

                if (middlewareContext.HasErrors is false)
                {
                    await next(middlewareContext).ConfigureAwait(false);
                }
            });
Esempio n. 23
0
 public static GraphQLException OperationResolverHelper_NoOperationFound(
     DocumentNode documentNode) =>
 throw new GraphQLException(ErrorBuilder.New()
                            .SetMessage("There are now operations in the GraphQL document.")
                            .AddLocation(documentNode)
                            .Build());
Esempio n. 24
0
        protected override void Configure(IObjectTypeDescriptor descriptor)
        {
            descriptor.ExtendMutation();
            descriptor.Field("createSaveProfile")
            .Description("Create a new save profile.")
            .UseClientMutationId()
            .UseAutoSubscription()
            .Argument("input", arg => arg.Type <CreateSaveProfileInputType>())
            .Resolve(async ctx =>
            {
                var gameLibrary = ctx.SnowflakeService <IGameLibrary>();
                var input       = ctx.ArgumentValue <CreateSaveProfileInput>("input");
                var game        = await gameLibrary.GetGameAsync(input.GameID);
                if (game == null)
                {
                    return(ErrorBuilder.New()
                           .SetCode("SAVE_NOTFOUND_GAME")
                           .SetMessage("The specified game does not exist.")
                           .Build());
                }
                var saveProfile = game.WithFiles().WithSaves()
                                  .CreateProfile(input.ProfileName, input.SaveType, input.ManagementStrategy);
                return(new CreateSaveProfilePayload()
                {
                    SaveProfile = saveProfile,
                    Game = game,
                });
            })
            .Type <NonNullType <CreateSaveProfilePayloadType> >();

            descriptor.Field("deleteSaveProfile")
            .Description("Delete a save profile.")
            .UseClientMutationId()
            .UseAutoSubscription()
            .Argument("input", arg => arg.Type <DeleteSaveProfileInputType>())
            .Resolve(async ctx =>
            {
                var gameLibrary = ctx.SnowflakeService <IGameLibrary>();
                var input       = ctx.ArgumentValue <DeleteSaveProfileInput>("input");
                var game        = await gameLibrary.GetGameAsync(input.GameID);
                if (game == null)
                {
                    return(ErrorBuilder.New()
                           .SetCode("SAVE_NOTFOUND_GAME")
                           .SetMessage("The specified game does not exist.")
                           .Build());
                }
                var gameSaves   = game.WithFiles().WithSaves();
                var saveProfile = gameSaves.GetProfile(input.ProfileID);
                if (saveProfile == null)
                {
                    return(ErrorBuilder.New()
                           .SetCode("SAVE_NOTFOUND_PROFILE")
                           .SetMessage("The specified save profile does not exist.")
                           .Build());
                }
                gameSaves.DeleteProfile(input.ProfileID);
                return(new DeleteSaveProfilePayload()
                {
                    SaveProfile = saveProfile,
                    Game = game,
                });
            })
            .Type <NonNullType <DeleteSaveProfilePayloadType> >();
        }
Esempio n. 25
0
 public static GraphQLException FieldVisibility_ValueNotSupported(IValueNode value) =>
 new GraphQLException(
     ErrorBuilder.New()
     .SetMessage("The skip/include if-argument value has to be a 'Boolean'.")
     .AddLocation(value)
     .Build());
Esempio n. 26
0
        public object?OnAfterDeserialize(object?runtimeValue)
        {
            if (runtimeValue is null)
            {
                return(null);
            }

            if (runtimeValue is string s)
            {
                try
                {
                    IdValue id = _idSerializer.Deserialize(s);

                    if (!_validateType || _typeName.Equals(id.TypeName))
                    {
                        return(id.Value);
                    }
                }
                catch
                {
                    throw new GraphQLException(
                              ErrorBuilder.New()
                              .SetMessage("The ID `{0}` has an invalid format.", s)
                              .Build());
                }

                throw new GraphQLException(
                          ErrorBuilder.New()
                          .SetMessage("The ID `{0}` is not an ID of `{1}`.", s, _typeName)
                          .Build());
            }

            if (runtimeValue is IEnumerable <string> stringEnumerable)
            {
                try
                {
                    IList list = _createList();

                    foreach (string sv in stringEnumerable)
                    {
                        IdValue id = _idSerializer.Deserialize(sv);

                        if (!_validateType || _typeName.Equals(id.TypeName))
                        {
                            list.Add(id.Value);
                        }
                    }

                    return(list);
                }
                catch
                {
                    throw new GraphQLException(
                              ErrorBuilder.New()
                              .SetMessage(
                                  "The IDs `{0}` have an invalid format.",
                                  string.Join(", ", stringEnumerable))
                              .Build());
                }
            }

            throw new GraphQLException(
                      ErrorBuilder.New()
                      .SetMessage("The specified value is not a valid ID value.")
                      .Build());
        }
        public void Build_ExpressionBuilderError_ThrowsBuildException()
        {
            var builder = new ErrorBuilder();

            RunInspector(builder);
        }
        protected override async Task ExecuteRequestAsync(
            HttpContext context,
            IServiceProvider services)
        {
            IReadOnlyList <GraphQLRequest> batch =
                await ReadRequestAsync(context)
                .ConfigureAwait(false);

            if (batch.Count == 0)
            {
                // TODO : resources
                var result = QueryResult.CreateError(
                    ErrorHandler.Handle(
                        ErrorBuilder.New()
                        .SetMessage("The GraphQL batch request has no elements.")
                        .SetCode(ErrorCodes.Server.RequestInvalid)
                        .Build()));

                await _resultSerializer.SerializeAsync(
                    result, context.Response.Body)
                .ConfigureAwait(false);
            }
            else if (batch.Count == 1)
            {
                string operations = context.Request.Query[_batchOperations];

                if (operations == null)
                {
                    await ExecuteQueryAsync(context, services, batch[0])
                    .ConfigureAwait(false);
                }
                else if (TryParseOperations(operations,
                                            out IReadOnlyList <string> operationNames))
                {
                    await ExecuteOperationBatchAsync(
                        context, services, batch[0], operationNames)
                    .ConfigureAwait(false);
                }
                else
                {
                    // TODO : resources
                    var result = QueryResult.CreateError(
                        ErrorHandler.Handle(
                            ErrorBuilder.New()
                            .SetMessage("Invalid GraphQL Request.")
                            .SetCode(ErrorCodes.Server.RequestInvalid)
                            .Build()));

                    SetResponseHeaders(
                        context.Response,
                        _resultSerializer.ContentType);

                    await _resultSerializer.SerializeAsync(
                        result, context.Response.Body)
                    .ConfigureAwait(false);
                }
            }
            else
            {
                await ExecuteQueryBatchAsync(context, services, batch)
                .ConfigureAwait(false);
            }
        }
Esempio n. 29
0
 public static GraphQLException OffsetPagingHandler_MaxPageSize() =>
 new GraphQLException(
     ErrorBuilder.New()
     .SetMessage("The maximum allowed items per page were exceeded.")
     .SetCode("PAGINATION_MAX_ITEMS")
     .Build());
Esempio n. 30
0
        private static void ResolveScopedVariableArguments(
            IResolverContext context,
            SelectionPathComponent component,
            IOutputField field,
            ICollection <VariableValue> variables)
        {
            ITypeConversion typeConversion =
                context.Service <IServiceProvider>()
                .GetTypeConversion();

            foreach (ArgumentNode argument in component.Arguments)
            {
                if (!field.Arguments.TryGetField(argument.Name.Value,
                                                 out IInputField arg))
                {
                    throw new QueryException(new Error
                    {
                        Message = string.Format(
                            CultureInfo.InvariantCulture,
                            StitchingResources
                            .DelegationMiddleware_ArgumentNotFound,
                            argument.Name.Value)
                    });
                }

                if (argument.Value is ScopedVariableNode sv)
                {
                    VariableValue variable =
                        _resolvers.Resolve(context, sv, arg.Type.ToTypeNode());

                    if (context.Schema.TryGetType(
                            arg.Type.NamedType().Name,
                            out ILeafType leafType))
                    {
                        object value = variable.Value;

                        if (!leafType.IsInstanceOfType(value))
                        {
                            value = typeConversion.Convert(
                                typeof(object), leafType.ClrType, value);
                        }

                        variable = new VariableValue
                                   (
                            variable.Name,
                            variable.Type,
                            leafType.Serialize(value),
                            variable.DefaultValue
                                   );
                    }
                    else
                    {
                        // TODO : resources
                        throw new QueryException(
                                  ErrorBuilder.New()
                                  .SetMessage(string.Format(
                                                  CultureInfo.InvariantCulture,
                                                  "Serialize argument {0} of type {1}.",
                                                  arg.Name, arg.Type.Visualize()))
                                  .SetPath(context.Path)
                                  .Build());
                    }

                    variables.Add(variable);
                }
            }
        }
Esempio n. 31
0
 public static GraphQLException RootTypeNotSupported(
     OperationType operationType) =>
 new GraphQLException(ErrorBuilder.New()
                      .SetMessage(ThrowHelper_RootTypeNotSupported_Message, operationType)
                      .Build());
Esempio n. 32
0
 public static IError ProjectionProvider_CreateMoreThanOneError() =>
 ErrorBuilder.New()
 .SetMessage(DataResources.ProjectionProvider_CreateMoreThanOneError)
 .SetCode("SELECTIONS_SINGLE_MORE_THAN_ONE")
 .Build();
Esempio n. 33
0
        OperationResult FinishImpl(string cipher, FinishInput input)
        {
            if (input == null) throw new ArgumentNullException("input");

             var canFinishResult = CanFinish(cipher);

             if (canFinishResult.IsError)
            return canFinishResult;

             UserWrapper user = canFinishResult.ValueAsSuccess;

             var errors = new ErrorBuilder();

             if (errors.NotValid(input)
            || !this.passServ.TrySetPassword(user, () => input.NewPassword, errors))
            return errors;

             user.PasswordResetTicketExpiration = null;

             this.repo.UpdateUser(user);

             return HttpStatusCode.OK;
        }
Esempio n. 34
0
 public static IError ProjectionProvider_CouldNotProjectSorting(
     IValueNode node) =>
 ErrorBuilder.New()
 .SetMessage(DataResources.ProjectionProvider_CouldNotProjectSorting)
 .AddLocation(node)
 .Build();
Esempio n. 35
0
        OperationResult ChangeImpl(ChangeInput input)
        {
            if (input == null) throw new ArgumentNullException("input");

             var errors = new ErrorBuilder();

             if (errors.NotValid(input))
            return errors;

             UserWrapper user = this.repo.FindUserByName(this.CurrentUserName);

             string currentEmail = user.Email;
             string newEmail = input.NewEmail;

             if (errors.Not(currentEmail.HasValue(), AccountResources.Validation_MissingEmail))
            return errors;

             if (errors.Not(this.passServ.PasswordEquals(input.CurrentPassword, user.Password), AccountResources.Validation_CurrentPasswordIncorrect, () => input.CurrentPassword)
            | errors.Not(!EmailEquals(currentEmail, newEmail), AccountResources.Validation_NewEmailSameAsCurrent, () => input.NewEmail))
            return errors;

             if (errors.Not(this.repo.FindUserByEmail(newEmail) == null, AccountResources.Validation_EmailAlreadyExists, () => input.NewEmail))
            return errors;

             if (!this.Configuration.EnableEmailVerification) {

            user.Email = newEmail;

            this.repo.UpdateUser(user);

            return HttpStatusCode.OK;
             }

             user.EmailChangeTicketExpiration = this.Configuration.GetNow().Add(this.Configuration.EmailChangeTicketExpiration);

             this.repo.UpdateUser(user);

             var notifyModel = new NotificationMessageViewModel {
            SiteName = GetSiteName(),
            NewEmail = newEmail,
            OldEmail = currentEmail,
            HelpResource = this.Configuration.HelpResource
             };

             if (!EmailEquals(currentEmail, user.Username))
            notifyModel.Username = user.Username;

             var notifyMessage = new MailMessage {
            To = { user.Email },
            Subject = AccountResources.Model_EmailChangeNotificationMessageSubject,
            Body = RenderEmailView(Views.Email.Change._NotificationMessage, notifyModel)
             };

             string verificationTicket = new VerificationData(user.Id, newEmail).GetVerificationTicket();
             string verificationUrl = AbsoluteUrl(this.Url.Action(Verify, verificationTicket));

             var verifyModel = new VerificationMessageViewModel {
            SiteName = notifyModel.SiteName,
            Url = verificationUrl
             };

             var verifyMessage = new MailMessage {
            To = { newEmail },
            Subject = AccountResources.Model_EmailChangeVerificationMessageSubject,
            Body = RenderEmailView(Views.Email.Change._VerificationMessage, verifyModel)
             };

             SendEmail(notifyMessage);
             SendEmail(verifyMessage);

             return new OperationResult(HttpStatusCode.Accepted, new ChangeResult(newEmail));
        }
        OperationResult<string> ValidateUser(SignInInput input)
        {
            if (input == null) throw new ArgumentNullException("input");

             var errors = new ErrorBuilder();

             if (errors.NotValid(input))
            return errors;

             string userPassNotMatchMessage = AccountResources.Validation_UserPassNotMatch.FormatInvariant(AccountResources.Model_Username);

             UserWrapper user = this.repo.FindUserByName(input.Username);

             if (errors.Not(user != null, userPassNotMatchMessage))
            return errors;

             DateTime now = this.Configuration.GetNow();

             if (!user.Password.HasValue())
            return new OperationResult<string>(HttpStatusCode.Forbidden, AccountResources.Validation_MissingPasswordCannotAuthenticate);

             int maxInvalidAttempts = this.Configuration.MaxInvalidSignInAttempts;

             bool passwordCorrect = this.passServ.PasswordEquals(input.Password, user.Password);
             int failedAttempts = user.FailedSignInAttempts;

             if (passwordCorrect) {

            if (user.Disabled)
               return new OperationResult<string>(HttpStatusCode.Forbidden, AccountResources.Validation_UserDisabled);

             } else {

            if (user.Disabled)
               return new OperationResult<string>(HttpStatusCode.BadRequest, userPassNotMatchMessage);

            if (failedAttempts <= maxInvalidAttempts) {

               failedAttempts++;

               user.FailedSignInAttempts = failedAttempts;
               user.FailedSignInAttemptWindowStart = now;

               if (failedAttempts > maxInvalidAttempts
                  && this.Configuration.DisableOnMaxInvalidSignInAttempts
                  && !user.Disabled) {

                  user.Disabled = true;
               }

               this.repo.UpdateUser(user);

               if (failedAttempts <= maxInvalidAttempts
                  || user.Disabled) {

                  return new OperationResult<string>(HttpStatusCode.BadRequest, userPassNotMatchMessage);
               }
            }
             }

             if (failedAttempts > maxInvalidAttempts) {

            DateTime lockEnd = user.FailedSignInAttemptWindowStart.GetValueOrDefault().Add(this.Configuration.SignInAttemptWindow);

            TimeSpan timeLeft = (lockEnd > now) ?
               lockEnd.Subtract(now)
               : TimeSpan.MinValue;

            double totalMinutes = timeLeft.TotalMinutes;
            double minutes = Math.Ceiling(totalMinutes);

            if (minutes > 0) {
               return new OperationResult<string>(
                  HttpStatusCode.Forbidden,
                  AccountResources.Validation_MaxInvalidSignInAttempts.FormatInvariant(minutes)
               );
            }
             }

             if (passwordCorrect) {

            user.FailedSignInAttempts = 0;
            user.FailedSignInAttemptWindowStart = null;
            user.LastSignIn = now;

             } else {

            // Window passed but password is incorrect, restart failed attempts count

            user.FailedSignInAttempts = 1;
            user.FailedSignInAttemptWindowStart = now;
             }

             this.repo.UpdateUser(user);

             if (!passwordCorrect)
            return new OperationResult<string>(HttpStatusCode.BadRequest, userPassNotMatchMessage);

             return user.Username;
        }