예제 #1
0
 public void AddGraphTypeFields(QueryCore queryCore)
 {
     queryCore.FieldAsync <UnitTestResultType>(name: "unitTestCollection",
                                               description: $"a set of complex data collections",
                                               resolve: UnitTestCollectionResolver,
                                               deprecationReason: null);
     queryCore.FieldAsync <UnitTestResultType>(name: "unitTestCollectionThrow",
                                               description: $"THROWS a set of complex data collections",
                                               resolve: UnitTestCollectionResolverThrows,
                                               deprecationReason: null);
 }
예제 #2
0
 public void AddGraphTypeFields(QueryCore queryCore)
 {
     queryCore.FieldAsync <StringGraphType>(
         "dogName2",
         resolve: async context => await DogNameAsync()
         );
 }
예제 #3
0
 public void AddGraphTypeFields(QueryCore queryCore)
 {
     var fieldType = queryCore.FieldAsync <HumanType>(
         name: "human",
         description: null,
         arguments: new QueryArguments(new QueryArgument <NonNullGraphType <StringGraphType> >
     {
         Name = "id", Description = "id of the human"
     }),
         resolve: async context =>
     {
         try
         {
             var userContext = context.UserContext.As <GraphQLUserContext>();
             var human       = await _starWarsData.GetHumanByIdAsync(context.GetArgument <string>("id"));
             return(human);
         }
         catch (Exception e)
         {
         }
         return(null);
         //                    return await Task.Run(() => { return ""; });
     },
         deprecationReason: null);
 }
        public void AddGraphTypeFields(QueryCore queryCore)
        {
            queryCore.FieldAsync <PublishStateModelType>(name: "publishState",
                                                         description: $"Fetches current state.",
                                                         resolve: async context =>
            {
                // Authorization worked, but who is calling us
                var graphQLUserContext = context.UserContext as GraphQLUserContext;
                var principal          = graphQLUserContext.HttpContextAccessor.HttpContext.User;

                // Since this is a B2B api, there probably will not be a subject, hence no real user
                // What we have here is an organization, so we have to find out the clientId, and the client_namespace

                var authContext     = principal.ToAuthContext();
                var requestedFields = (from item in context.SubFields
                                       select item.Key).ToList();

                var result = await _b2bPublisherStore.GetPublishStateAsync(
                    authContext, new Contracts.Models.RequestedFields
                {
                    Fields = requestedFields
                });
                return(result);
            },
                                                         deprecationReason: null);
        }
예제 #5
0
        public void AddGraphTypeFields(QueryCore queryCore)
        {
            queryCore.FieldAsync <BindResultType>(name: "bind",
                                                  description: "Given a type of token, we will exchange it for an oAuth2 token to access this service.",
                                                  arguments: new QueryArguments(new QueryArgument <NonNullGraphType <BindInput> > {
                Name = "input"
            }),
                                                  resolve: async context =>
            {
                try
                {
                    var userContext = context.UserContext.As <GraphQLUserContext>();
                    var input       = context.GetArgument <BindInputHandle>("input");

                    var result = await _bindStore.BindAsync(input.Type, input.Token);
                    return(result);
                }
                catch (Exception e)
                {
                    context.Errors.Add(new ExecutionError("Unable to bind with giving input"));
                }
                return(null);
                //                    return await Task.Run(() => { return ""; });
            },
                                                  deprecationReason: null);
        }
 public void AddGraphTypeFields(QueryCore queryCore)
 {
     var fieldName = "subscription";
     var fieldType = queryCore.FieldAsync <SubscriptionDocumentType>(name: fieldName,
                                                                     description: null,
                                                                     arguments: new QueryArguments(new QueryArgument <NonNullGraphType <SubscriptionQueryInput> > {
         Name = "input"
     }),
                                                                     resolve: async context =>
     {
         try
         {
             var userContext = context.UserContext.As <GraphQLUserContext>();
             var input       = context.GetArgument <SubscriptionQueryHandle>("input");
             var result      = new SubscriptionDocumentHandle
             {
                 Value = new SomeData()
                 {
                     SubscriptionQueryHandle = input, Ted = "Well Hellow"
                 },
                 Id       = input.Id,
                 MetaData = input.MetaData
             };
             return(result);
         }
         catch (Exception e)
         {
         }
         return(null);
         //                    return await Task.Run(() => { return ""; });
     },
                                                                     deprecationReason: null);
 }
예제 #7
0
        public void AddGraphTypeFields(QueryCore queryCore)
        {
            queryCore.FieldAsync <ArbitraryNoSubjectResultType>(name: GrantType,
                                                                description: $"mints a custom {GrantType} token.",
                                                                arguments: new QueryArguments(new QueryArgument <NonNullGraphType <ArbitraryNoSubjectInput> > {
                Name = "input"
            }),
                                                                resolve: async context =>
            {
                try
                {
                    var userContext = context.UserContext.As <GraphQLUserContext>();
                    var input       = context.GetArgument <ArbitraryNoSubjectInputHandle>("input");

                    var formValues = new Dictionary <string, StringValues>()
                    {
                        { "grant_type", GrantType },
                        { "client_id", input.client_id },
                        { "client_secret", input.client_secret },
                        { "scope", input.scope },
                        { "arbitrary_claims", input.arbitrary_claims }
                    };
                    if (!string.IsNullOrWhiteSpace(input.arbitrary_amrs))
                    {
                        formValues.Add("arbitrary_amrs", input.arbitrary_amrs);
                    }
                    if (!string.IsNullOrWhiteSpace(input.arbitrary_audiences))
                    {
                        formValues.Add("arbitrary_audiences", input.arbitrary_audiences);
                    }
                    if (input.access_token_lifetime > 0)
                    {
                        formValues.Add("access_token_lifetime", input.access_token_lifetime.ToString());
                    }

                    IFormCollection formCollection = new FormCollection(formValues);

                    var processsedResult = await _endpointHandlerExtra.ProcessRawAsync(formCollection);

                    if (processsedResult.TokenErrorResult != null)
                    {
                        context.Errors.Add(new ExecutionError($"{processsedResult.TokenErrorResult.Response.Error}:{processsedResult.TokenErrorResult.Response.ErrorDescription}"));
                        return(null);
                    }
                    var result = new ArbitraryNoSubjectResult
                    {
                        access_token = processsedResult.TokenResult.Response.AccessToken,
                        expires_in   = processsedResult.TokenResult.Response.AccessTokenLifetime,
                        token_type   = "bearer"
                    };
                    return(result);
                }
                catch (Exception e)
                {
                    context.Errors.Add(new ExecutionError("Unable to process request", e));
                }
                return(null);
            },
                                                                deprecationReason: null);
        }
예제 #8
0
        public void AddGraphTypeFields(QueryCore queryCore)
        {
            queryCore.FieldAsync <IdentityModelType>(name: "authRequired",
                                                     description: null,
                                                     resolve: async context =>
            {
                try
                {
                    var userContext = context.UserContext.As <GraphQLUserContext>();
                    var result      = new GraphQLCore.ExtensionGrants.Models.IdentityModel {
                        Claims = new List <ClaimHandle>()
                    };
                    foreach (var claim in userContext.HttpContextAccessor.HttpContext.User.Claims)
                    {
                        result.Claims.Add(new ClaimHandle()
                        {
                            Name  = claim.Type,
                            Value = claim.Value
                        });
                    }

                    return(result);
                }
                catch (Exception e)
                {
                }

                return(null);
                //                    return await Task.Run(() => { return ""; });
            },
                                                     deprecationReason: null);
        }
        public void AddGraphTypeFields(QueryCore queryCore)
        {
            var fieldName = "program";

            var fieldType = queryCore.FieldAsync <ProgramQueryOutput>(name: fieldName,
                                                                      description: null,
                                                                      arguments: new QueryArguments(new QueryArgument <ProgramQueryInput> {
                Name = "input"
            }),
                                                                      resolve: async context =>
            {
                var input    = context.GetArgument <IsInstalledQuery>("input");
                var programs = new Programs();
                var result   = programs.GetIsInstalled(input);
                var final    = new IsInstalledOutput()
                {
                    DisplayName = input.DisplayName,
                    IsInstalled = result.Result.Value
                };
                return(final);
            },
                                                                      deprecationReason: null);

            fieldName = "installedApps";

            fieldType = queryCore.FieldAsync <InstalledPageType>(name: fieldName,
                                                                 description: null,
                                                                 arguments: new QueryArguments(new QueryArgument <ProgramPageQueryInput> {
                Name = "input"
            }),
                                                                 resolve: async context =>
            {
                var input    = context.GetArgument <PageQuery>("input");
                var programs = new Programs();
                var result   = programs.GetPage(input);
                var final    = new InstalledPage()
                {
                    Count         = result.Length,
                    NextOffset    = input.Offset + input.Count,
                    CurrentOffset = input.Offset,
                    InstalledApps = new List <InstalledApp>(result)
                };
                return(final);
            },
                                                                 deprecationReason: null);
        }
        public void AddGraphTypeFields(QueryCore queryCore)
        {
            queryCore.FieldAsync <DiscoveryResultType>(name: "graphQLDiscovery",
                                                       description: $"Discovery of downstream graphQL services",
                                                       resolve: GraphQLDiscoveryResolver,

                                                       deprecationReason: null);
        }
        public void AddGraphTypeFields(QueryCore queryCore)
        {
            queryCore.FieldAsync <ListGraphType <TokenExchangeResponseType> >(name: "tokenExchange",
                                                                              description: $"Given a proper list of OAuth2 Tokens, returns an authorization payload for downstream authorized calls.",
                                                                              arguments: new QueryArguments(new QueryArgument <NonNullGraphType <TokenExchangeInput> > {
                Name = "input"
            }),
                                                                              resolve: async context =>
            {
                try
                {
                    var graphQLUserContext = context.UserContext as GraphQLUserContext;


                    _summaryLogger.Add("query", "bind");
                    var input = context.GetArgument <BindInputModel>("input");

                    if (input.Tokens == null || input.Tokens.Count == 0)
                    {
                        throw new Exception("no tokens present in the request!");
                    }
                    var requestedFields = (from item in context.SubFields
                                           select item.Key).ToList();

                    var summaryLog = string.Join(";", _summaryLogger.Select(x => x.Key + "=" + x.Value).ToArray());


                    _summaryLogger.Add("requestedFields", string.Join(" ", requestedFields));

                    var tokens = (from item in input.Tokens
                                  let c = new TokenWithScheme()
                    {
                        Token = item.Token,
                        TokenScheme = item.TokenScheme
                    }
                                  select c).ToList();

                    var tokenExchangeRequest = new TokenExchangeRequest()
                    {
                        Tokens = tokens,
                        Extras = input.Extras
                    };
                    var tokenExchangeResponse = await _tokenExchangeHandlerRouter.ProcessExchangeAsync(input.Exchange, tokenExchangeRequest);

                    return(tokenExchangeResponse);
                }
                catch (Exception e)
                {
                    _summaryLogger.Add("exception", e.Message);
                    context.Errors.Add(new ExecutionError("Unable to process request", e));
                }

                return(null);
            },
                                                                              deprecationReason: null);
        }
예제 #12
0
 public void AddGraphTypeFields(QueryCore queryCore)
 {
     var fieldType = queryCore.FieldAsync <CharacterInterface>(
         name: "hero",
         description: null,
         resolve: async context =>
     {
         var result = await _starWarsData.GetDroidByIdAsync("3");
         return(result);
     });
 }
예제 #13
0
 public void AddGraphTypeFields(QueryCore queryCore)
 {
     queryCore.FieldAsync <CustomerType>(
         "customer",
         arguments: new QueryArguments(new QueryArgument <NonNullGraphType <StringGraphType> > {
         Name = "id"
     }),
         resolve: async context => {
         return(await context.TryAsyncResolve(CustomerResolver));
     }
         );
 }
예제 #14
0
        public void AddGraphTypeFields(QueryCore queryCore)
        {
            queryCore.FieldAsync <CustomerResultType>(name: "customerLoyalty",
                                                      description: null,
                                                      resolve: async context =>
            {
                var startQuery = context?.Operation?
                                 .SelectionSet?
                                 .Selections
                                 .Select(x => x as Field)
                                 .FirstOrDefault();


                var fields = startQuery?.SelectionSet?
                             .Selections
                             .Select(x => x as Field)
                             .ToList();
                var prizesField = fields?
                                  .Where(x => "prizes".EqualsNoCase(x.Name))
                                  .FirstOrDefault();


                var userContext = context.UserContext.As <GraphQLUserContext>();
                var user        = userContext.HttpContextAccessor.HttpContext.User;
                var query       = from item in user.Claims
                                  where item.Type == ClaimTypes.NameIdentifier
                                  select item;
                if (query.Any())
                {
                    var claim          = query.First();
                    var userId         = claim.Value;
                    var customer       = await _customerLoyaltyStore.GetCustomerAsync(userId);
                    var customerResult = new CustomerResult
                    {
                        ID = customer.ID,
                        LoyaltyPointBalance = customer.LoyaltyPointBalance
                    };

                    if (prizesField != null)
                    {
                        var prizeStore = _lazyPrizeStore;
                        var prizes     =
                            await prizeStore.GetAvailablePrizesAsync(customer.LoyaltyPointBalance);
                        customerResult.Prizes = prizes;
                    }

                    return(customerResult);
                }
                return(null);
            },
                                                      deprecationReason: null);
        }
예제 #15
0
        public void AddGraphTypeFields(QueryCore queryCore)
        {
            queryCore.FieldAsync <ListGraphType <OrderType> >(
                "orders",
                resolve: async context => await _orders.GetOrdersAsync()
                );

            queryCore.FieldAsync <OrderType>(
                "orderById",
                arguments: new QueryArguments(new QueryArgument <NonNullGraphType <StringGraphType> > {
                Name = "orderId"
            }),
                resolve: async context => {
                return(await context.TryAsyncResolve(
                           async c => await _orders.GetOrderByIdAsync(c.GetArgument <String>("orderId"))
                           ));
            }
                );

            queryCore.FieldAsync <ListGraphType <CustomerType> >(
                "customers",
                resolve: async context => await _customers.GetCustomersAsync()
                );
        }
예제 #16
0
        public void AddGraphTypeFields(QueryCore queryCore)
        {
            var fieldName = "echo";

            var fieldType = queryCore.FieldAsync <VersionQueryOutput>(name: fieldName,
                                                                      description: null,
                                                                      arguments: new QueryArguments(new QueryArgument <VersionQueryInput> {
                Name = "input"
            }),
                                                                      resolve: async context =>
            {
                var input = context.GetArgument <VersionQueryHandle>("input");
                return(input);
            },
                                                                      deprecationReason: null);
        }
        public void AddGraphTypeFields(QueryCore queryCore)
        {
            var fieldName = "resource";

            var fieldType = queryCore.FieldAsync <StringGraphType>(name: fieldName,
                                                                   description: null,
                                                                   arguments: new QueryArguments(new QueryArgument <ResourceQueryInput> {
                Name = "input"
            }),
                                                                   resolve: async context =>
            {
                var userContext = context.UserContext.As <GraphQLUserContext>();
                var rqf         = userContext.HttpContextAccessor.HttpContext.Features.Get <IRequestCultureFeature>();
                // Culture contains the information of the requested culture
                CultureInfo currentCulture = rqf.RequestCulture.Culture;

                var input = context.GetArgument <ResourceQueryHandle>("input");

                if (!string.IsNullOrEmpty(input.Culture))
                {
                    try
                    {
                        currentCulture = new CultureInfo(input.Culture);
                    }
                    catch (Exception)
                    {
                        currentCulture = new CultureInfo("en-US");
                    }
                }
                var obj = await _resourceFetcher.GetResourceSetAsync(
                    new ResourceQueryHandle()
                {
                    Culture   = currentCulture.Name,
                    Id        = input.Id,
                    Treatment = input.Treatment
                });
                return(obj);
            },
                                                                   deprecationReason: null);
        }
예제 #18
0
        public void AddGraphTypeFields(QueryCore queryCore)
        {
            var fieldType = queryCore.FieldAsync <AccessCodeDocumentType>(name: "identity",
                                                                          description: null,
                                                                          arguments: new QueryArguments(new QueryArgument <IdentityQueryInput> {
                Name = "input"
            }),
                                                                          resolve: async context =>
            {
                var userContext = context.UserContext.As <GraphQLUserContext>();

                var oidc = _httpContextAccessor.HttpContext.Session.GetObject <Dictionary <string, string> >(".identity.oidc");

                var input = context.GetArgument <AccessCodeQueryHandle>("input");

                var selectionSet = context.FieldAst.SelectionSet.Selections;
                var scheme       = _httpContextAccessor.HttpContext.Request.IsHttps?"https://":"http://";
                var host         = _httpContextAccessor.HttpContext.Request.Host;
                var redirectUri  = $"{scheme}{host}/sigin-norton";
                var doc          = await _discoveryCache.GetAsync();

                var tokenEndpoint = doc.TokenEndpoint;
                var keys          = doc.KeySet.Keys;

                if (!string.IsNullOrEmpty(oidc["expires_at"]))
                {
                    var ea = DateTimeOffset.Parse(oidc["expires_at"]);
                    if (ea <= DateTimeOffset.UtcNow)
                    {
                        var clientId    = _configuration["Norton-ClientId"];
                        var cientSecret = _configuration["Norton-ClientSecret"];
                        var client      = new TokenClient(
                            doc.TokenEndpoint,
                            clientId,
                            cientSecret);
                        var extras = new Dictionary <string, string>
                        {
                            { OidcConstants.TokenRequest.Scope, "openid" }
                        };
                        var response = await client.RequestRefreshTokenAsync(
                            oidc["refresh_token"], extras);
                        var token = response.AccessToken;
                        if (!response.IsError)
                        {
                            var utcExpiresAt = DateTimeOffset.UtcNow.AddSeconds(response.ExpiresIn).ToString("o");
                            var oidc2        = new Dictionary <string, string>
                            {
                                { "access_token", response.AccessToken },
                                { "id_token", response.IdentityToken },
                                { "refresh_token", response.RefreshToken },
                                { "token_type", response.TokenType },
                                { "expires_at", utcExpiresAt }
                            };
                            var session = _httpContextAccessor.HttpContext.Session;
                            session.SetObject(".identity.oidc", oidc2);
                        }
                    }
                }


                var result = new AccessCodeDocumentHandle
                {
                    Oidc        = oidc,
                    AccessToken = "hi",
                    AccessCode  = "blah"
                };
                return(result);
//                    return input;
            },
                                                                          deprecationReason: null);
        }
예제 #19
0
        public void AddGraphTypeFields(QueryCore queryCore)
        {
            queryCore.FieldAsync <BlogType>(
                "droid",
                arguments: new QueryArguments(new QueryArgument <StringGraphType> {
                Name = "id"
            }),
                resolve: async context =>
            {
                try
                {
                    var userContext = context.UserContext.As <GraphQLUserContext>();
                    var id          = context.GetArgument <string>("id");
                    var result      = await _blogStore.FetchAsync(Guid.Parse(id));
                    return(result);
                }
                catch (Exception e)
                {
                }
                return(null);
                //                    return await Task.Run(() => { return ""; });
            },
                deprecationReason: null);
            queryCore.FieldAsync <BlogPageType>(
                "droids",
                arguments: new QueryArguments(new QueryArgument <BlogsQueryInput> {
                Name = "input"
            }),
                resolve: async context =>
            {
                try
                {
                    var userContext     = context.UserContext.As <GraphQLUserContext>();
                    var blogsPageHandle = context.GetArgument <BlogsPageHandle>("input");

                    var pagingState = blogsPageHandle.PagingState.SafeConvertFromBase64String();

                    var categories                  = blogsPageHandle.Categories?.ToArray();
                    var tags                        = blogsPageHandle.Tags?.ToArray();
                    DateTime baseDateTime           = new DateTime();
                    DateTime?timeStampLowerBoundary = baseDateTime == blogsPageHandle.TimeStampLowerBoundary
                            ? (DateTime?)null
                            : blogsPageHandle.TimeStampLowerBoundary;
                    DateTime?timeStampUpperBoundary = baseDateTime == blogsPageHandle.TimeStampUpperBoundary
                            ? (DateTime?)null
                            : blogsPageHandle.TimeStampUpperBoundary;
                    var result = await _blogStore.PageAsync(
                        blogsPageHandle.PageSize,
                        pagingState,
                        timeStampLowerBoundary,
                        timeStampUpperBoundary,
                        categories,
                        tags);

                    var blogPage = new BlogPage()
                    {
                        PagingState =
                            result.PagingState == null ? "" : result.PagingState.SafeConvertToBase64String(),
                        CurrentPagingState =
                            result.CurrentPagingState == null
                                    ? ""
                                    : result.CurrentPagingState.SafeConvertToBase64String(),
                        Blogs = result.ToList()
                    };
                    return(blogPage);
                }
                catch (Exception e)
                {
                }
                return(null);
                //                    return await Task.Run(() => { return ""; });
            },
                deprecationReason: null);
            queryCore.FieldAsync <BlogDocumentType>(name: "blog",
                                                    description: null,
                                                    arguments: new QueryArguments(new QueryArgument <NonNullGraphType <BlogQueryInput> > {
                Name = "input"
            }),
                                                    resolve: async context =>
            {
                try
                {
                    var userContext = context.UserContext.As <GraphQLUserContext>();
                    var blog        = context.GetArgument <SimpleDocument <Blog> >("input");
                    var result      = await _blogStore.FetchAsync(blog.Id_G);
                    return(result);
                }
                catch (Exception e)
                {
                }
                return(null);
                //                    return await Task.Run(() => { return ""; });
            },
                                                    deprecationReason: null);
            queryCore.FieldAsync <BlogPageType>(name: "blogsPage",
                                                description: null,
                                                arguments: new QueryArguments(new QueryArgument <BlogsQueryInput> {
                Name = "input"
            }),
                                                resolve: async context =>
            {
                try
                {
                    var userContext     = context.UserContext.As <GraphQLUserContext>();
                    var blogsPageHandle = context.GetArgument <BlogsPageHandle>("input");

                    var pagingState = blogsPageHandle.PagingState.SafeConvertFromBase64String();

                    var categories                  = blogsPageHandle.Categories?.ToArray();
                    var tags                        = blogsPageHandle.Tags?.ToArray();
                    DateTime baseDateTime           = new DateTime();
                    DateTime?timeStampLowerBoundary = baseDateTime == blogsPageHandle.TimeStampLowerBoundary
                            ? (DateTime?)null
                            : blogsPageHandle.TimeStampLowerBoundary;
                    DateTime?timeStampUpperBoundary = baseDateTime == blogsPageHandle.TimeStampUpperBoundary
                            ? (DateTime?)null
                            : blogsPageHandle.TimeStampUpperBoundary;
                    var result = await _blogStore.PageAsync(
                        blogsPageHandle.PageSize,
                        pagingState,
                        timeStampLowerBoundary,
                        timeStampUpperBoundary,
                        categories,
                        tags);

                    var blogPage = new BlogPage
                    {
                        CurrentPagingState = result.CurrentPagingState.SafeConvertToBase64String() ?? "",
                        PagingState        = result.PagingState.SafeConvertToBase64String() ?? "",
                        Blogs = result.ToList()
                    };
                    return(blogPage);
                }
                catch (Exception e)
                {
                }
                return(null);
                //                    return await Task.Run(() => { return ""; });
            },
                                                deprecationReason: null);
            queryCore.FieldAsync <ListGraphType <BlogDocumentType> >(name: "blogsPageByNumber",
                                                                     description: null,
                                                                     arguments: new QueryArguments(new QueryArgument <BlogsPageQueryInput> {
                Name = "input"
            }),
                                                                     resolve: async context =>
            {
                try
                {
                    var userContext     = context.UserContext.As <GraphQLUserContext>();
                    var blogsPageHandle = context.GetArgument <BlogsPageByNumberHandle>("input");

                    var categories                  = blogsPageHandle.Categories?.ToArray();
                    var tags                        = blogsPageHandle.Tags?.ToArray();
                    DateTime baseDateTime           = new DateTime();
                    DateTime?timeStampLowerBoundary = baseDateTime == blogsPageHandle.TimeStampLowerBoundary
                            ? (DateTime?)null
                            : blogsPageHandle.TimeStampLowerBoundary;
                    DateTime?timeStampUpperBoundary = baseDateTime == blogsPageHandle.TimeStampUpperBoundary
                            ? (DateTime?)null
                            : blogsPageHandle.TimeStampUpperBoundary;
                    var result = await _blogStore.PageAsync(
                        blogsPageHandle.PageSize,
                        blogsPageHandle.Page,
                        timeStampLowerBoundary,
                        timeStampUpperBoundary,
                        categories,
                        tags);

                    return(result);
                }
                catch (Exception e)
                {
                }
                return(null);
                //                    return await Task.Run(() => { return ""; });
            },
                                                                     deprecationReason: null);
        }