Пример #1
0
        internal async Task Invoke(HttpContext context, IScSession session)
        {
            if (session.CurrentUser == null)
            {
                context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                await context.Response.WriteAsync($"{(session.InvalidToken ? "Invalid" : "Missing")} Sandwich-Auth-Token header");

                return;
            }

            await _next(context);
        }
Пример #2
0
        public SandwichClubQuery(IScSession session, IUserService userService, IWeekService weekService, IWeekUserLinkService weekUserLinkService)
        {
            Name = "Query";

            Field <StringGraphType>(
                "version",
                resolve: context => typeof(SandwichClubQuery).Assembly.GetName().Version.ToString());

            FieldAsync <UserType>(
                "me",
                resolve: async context =>
            {
                return(await userService.GetByIdAsync((session.CurrentUser?.UserId).Value));
            }
                );


            FieldAsync <UserType>(
                "primaryShopper",
                resolve: async context =>
            {
                return(await userService.GetPrimaryShopperAsync());
            }
                );

            FieldAsync <ListGraphType <UserType> >(
                "users",
                resolve: async context => await userService.GetAsync()
                );

            FieldAsync <UserType>(
                "user",
                arguments: new QueryArguments(
                    new QueryArgument <IntGraphType> {
                Name = "userId", Description = "UserId of the user"
            },
                    new QueryArgument <StringGraphType> {
                Name = "facebookId", Description = "FacebookId of the user"
            }
                    ),
                resolve: async context =>
            {
                var userId = context.GetArgument <int?>("userId");
                if (userId != null)
                {
                    return(await userService.GetByIdAsync(userId.Value));
                }
                var socialId = context.GetArgument <string>("facebookId");
                if (socialId != null)
                {
                    return(await userService.GetBySocialId(socialId));
                }
                return(null);
            }
                );

            FieldAsync <WeekType>(
                "thisweek",
                resolve: async context => await weekService.GetCurrentWeekAsync()
                );

            FieldAsync <ListGraphType <WeekType> >(
                "weeks",
                resolve: async context => await weekService.GetAsync()
                );

            FieldAsync <WeekType>(
                "week",
                arguments: new QueryArguments(
                    new QueryArgument <IntGraphType> {
                Name = "weekId", Description = "WeekId of the user"
            }
                    ),
                resolve: async context =>
            {
                var weekId = context.GetArgument <int?>("weekId");
                if (weekId != null)
                {
                    return(await weekService.GetByIdAsync(weekId.Value));
                }
                return(null);
            }
                );

            FieldAsync <WeekUserLinkType>(
                "weekLink",
                arguments: new QueryArguments(
                    new QueryArgument <IntGraphType> {
                Name = "weekId", Description = "WeekId of the user"
            }
                    ),
                resolve: async context =>
            {
                var weekId = context.GetArgument <int>("weekId");
                return(await weekUserLinkService.GetByIdAsync(new WeekUserLinkId {
                    WeekId = weekId, UserId = (session.CurrentUser?.UserId).Value
                }));
            }
                );
        }
Пример #3
0
        private async Task <ExecutionResult> ExecuteAsync(HttpRequest request, ISchema schema, IScSession session, IGraphQLAuthenticationValidator _graphqlAuthenticationValidator)
        {
            string requestBodyText;

            using (var streamReader = new StreamReader(request.Body))
            {
                requestBodyText = await streamReader.ReadToEndAsync().ConfigureAwait(true);
            }
            JObject o = JObject.Parse(requestBodyText);
            var     graphqlRequest = new GraphQLRequest {
                Query         = o["query"]?.ToString(),
                Variables     = o["variables"]?.ToString(),
                Mutation      = o["mutation"]?.ToString(),
                OperationName = o["operationName"]?.ToString()
            };

            var result = await new DocumentExecuter().ExecuteAsync(new ExecutionOptions
            {
                Schema          = schema,
                Query           = o["query"]?.ToString(),
                OperationName   = o["operationName"]?.ToString(),
                Inputs          = o["variables"]?.ToString().ToInputs(),
                UserContext     = session,
                ValidationRules = (new [] { _graphqlAuthenticationValidator }).Concat(DocumentValidator.CoreRules())
            }).ConfigureAwait(true);

            return(result);
        }
Пример #4
0
        public SandwichClubMutation(IScSession session,
                                    IUserService userService,
                                    IPaymentService paymentService,
                                    IWeekService weekService)
        {
            Name = "Mutation";
            FieldAsync <WeekType>(
                "subscribeToWeek",
                arguments: new QueryArguments(
                    new QueryArgument <IntGraphType> {
                Name = "userId", Description = "UserId of the user"
            },
                    new QueryArgument <IntGraphType> {
                Name = "weekId", Description = "WeekId of the week"
            },
                    new QueryArgument <IntGraphType> {
                Name = "slices", Description = "WeekId of the week"
            }
                    ),
                resolve: async context =>
            {
                var userId = context.GetArgument <int>("userId");
                var weekId = context.GetArgument <int>("weekId");
                var slices = context.GetArgument <int>("slices");

                return(await weekService.SubscibeToWeek(weekId, userId, slices));
            }
                );

            FieldAsync <PaymentType>(
                "markAllWeeksPaidForUser",
                arguments: new QueryArguments(
                    new QueryArgument <IntGraphType> {
                Name = "userId", Description = "UserId to mark weeks paid for"
            }
                    ),
                resolve: async context =>
            {
                var userId = context.GetArgument <int>("userId");

                return(await paymentService.PayOwedForUser(userId));
            }
                );

            FieldAsync <WeekType>(
                "updateWeek",
                arguments: new QueryArguments(
                    new QueryArgument <IntGraphType> {
                Name = "weekId", Description = "WeekId of the week"
            },
                    new QueryArgument <IntGraphType> {
                Name = "shopperId", Description = "UserId of the shopper"
            },
                    new QueryArgument <FloatGraphType> {
                Name = "cost", Description = "cost of the week"
            }
                    ),
                resolve: async context =>
            {
                var shopperId = context.GetArgument <int?>("shopperId");
                var weekId    = context.GetArgument <int>("weekId");
                var cost      = context.GetArgument <double?>("cost");

                return(await weekService.SaveAsync(new Week
                {
                    WeekId = weekId,
                    ShopperUserId = shopperId,
                    Cost = cost ?? 0,
                }));
            }
                );

            Field <UserType>(
                "updateMe",
                arguments: new QueryArguments(
                    new QueryArgument <StringGraphType> {
                Name = "bankName", Description = "The name of the users week bank"
            },
                    new QueryArgument <StringGraphType> {
                Name = "bankDetails", Description = "Details for making payments"
            },
                    new QueryArgument <BooleanGraphType> {
                Name = "shopper", Description = "Set as shopper"
            }
                    ),
                resolve: (context) =>
            {
                var user = session.CurrentUser;

                var bankName    = context.GetArgument <string>("bankName");
                var bankDetails = context.GetArgument <string>("bankDetails");
                var shopper     = context.GetArgument <bool?>("shopper");

                if (bankName != null)
                {
                    user.BankName = bankName;
                }
                if (bankDetails != null)
                {
                    user.BankDetails = bankDetails;
                }
                if (shopper != null)
                {
                    user.Shopper = shopper.Value;
                }

                return(userService.SaveAsync(user));
            }
                );
        }
 public AuthorizationMiddlewareTests()
 {
     Mock <IScSession>().SetupAllProperties();
     _session = Mock <IScSession>().Object;
 }
        internal async Task Authenticate(HttpContext context, IOptions <AuthenticationMiddlewareConfig> config, IScSession session, IAuthorisationService authorisationService)
        {
            if (config.Value.IgnoreAuth)
            {
                var userService = context.RequestServices.GetService <IUserService>();
                session.CurrentUser = (await userService.GetAsync()).FirstOrDefault();
                return;
            }

            var ntoken = GetToken(context);

            if (!ntoken.HasValue || ntoken.Value == default(string))
            {
                // Missing token
                return;
            }

            var token = ntoken.Value;

            if (_tokenCache.TryGetValue(token, out UserAuthItem authItem))
            {
                if (DateTime.Now.Subtract(authItem.CacheTime).TotalMinutes > 30)
                {
                    _tokenCache.TryRemove(token, out authItem);
                }
                else
                {
                    session.CurrentUser = authItem.User;
                }
            }
            else
            {
                if (await authorisationService.CanAuthorise(token))
                {
                    var user = await authorisationService.Authorise(token);

                    if (user != null)
                    {
                        authItem = new UserAuthItem {
                            CacheTime = DateTime.Now, User = user
                        };
                        _tokenCache.TryAdd(token, authItem);
                        session.CurrentUser = user;
                    }
                }
            }

            if (session.CurrentUser == null)
            {
                session.InvalidToken = true;
            }
        }