Ejemplo n.º 1
0
        public async Task Handle(CreateTravel command)
        {
            if (command.AggregateId == null || command.AggregateId == Guid.Empty)
            {
                throw new IncorrectRequestException(ErrorCodes.ParameterCannotBeEmpty, nameof(command.AggregateId));
            }

            if (string.IsNullOrWhiteSpace(command.Destination))
            {
                throw new IncorrectRequestException(ErrorCodes.ParameterCannotBeEmpty, nameof(command.Destination));
            }

            Models.Travel travel = await store.Get(command.AggregateId);

            if (travel != null)
            {
                throw new IncorrectRequestException(ErrorCodes.IdAlreadyExists, nameof(command.AggregateId));
            }

            await eventPublisher.Publish(new TravelCreated
            {
                RelatedCommandId = command.CommandId,
                AggregateVersion = 1,
                Id          = Guid.NewGuid(),
                Owner       = identityProvider.GetIdentity().Username,
                Destination = command.Destination,
                Date        = command.Date,
            });
        }
Ejemplo n.º 2
0
        private TokenApiModel GenerateToken(HttpContext context)
        {
            var username = context.Request.Form["username"];
            var password = context.Request.Form["password"];
            var now      = DateTime.UtcNow;

            var identity = _identityProvider.GetIdentity(new LoginApiModel {
                Email = username, Password = password
            });

            if (identity == null)
            {
                return(null);
            }

            var claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub, username),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.Iat, now.ToUniversalTime().Second.ToString(), ClaimValueTypes.Integer64)
            };

            claims.AddRange(identity);


            var jwt = new JwtSecurityToken(
                issuer: _options.Issuer,
                audience: _options.Audience,
                claims: claims,
                notBefore: now,
                expires: now.Add(_options.Expiration),
                signingCredentials: _options.SigningCredentials);

            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            var token = new TokenApiModel
            {
                Token     = encodedJwt,
                ExpiresIn = (long)_options.Expiration.TotalSeconds
            };

            _logger.LogInformation($"Token was successfuly generated for user with email: {username} ");

            return(token);
        }
Ejemplo n.º 3
0
        public async Task Handle(EditTravel command)
        {
            if (command.AggregateId == null || command.AggregateId == Guid.Empty)
            {
                throw new IncorrectRequestException(ErrorCodes.ParameterCannotBeEmpty, nameof(command.AggregateId));
            }

            if (string.IsNullOrWhiteSpace(command.Destination) && !command.Date.HasValue)
            {
                throw new IncorrectRequestException(ErrorCodes.ParameterCannotBeEmpty, $"{nameof(command.Destination)}, {nameof(command.Date)}");
            }

            Models.Travel travel = await store.Get(command.AggregateId);

            if (travel == null || travel.Deleted)
            {
                throw new IncorrectRequestException(ErrorCodes.ResourceDoesNotExist, nameof(travel));
            }

            if (travel.Version != command.AggregateVersion)
            {
                throw new ResourceStateChangedException(nameof(Travel), travel.Id, travel.Version);
            }

            Identity identity = identityProvider.GetIdentity();

            if (travel.Owner != identity.Username && identity.Role != Roles.Admin)
            {
                throw new UnauthorizedUserException();
            }

            var @event = new TravelUpdated
            {
                RelatedCommandId = command.CommandId,
                Id          = travel.Id,
                Destination = string.IsNullOrWhiteSpace(command.Destination) ? travel.Destination : command.Destination,
                Date        = command.Date.HasValue ? command.Date.Value : travel.Date,
            };

            travel.ApplyEvent(@event);
            @event.AggregateVersion = travel.Version;

            await eventPublisher.Publish(@event);
        }
Ejemplo n.º 4
0
        public async Task Handle(DeleteTravel command)
        {
            if (command.AggregateId == null || command.AggregateId == Guid.Empty)
            {
                throw new IncorrectRequestException(ErrorCodes.ParameterCannotBeEmpty, nameof(command.AggregateId));
            }

            Models.Travel travel = await store.Get(command.AggregateId);

            if (travel == null || travel.Deleted)
            {
                throw new IncorrectRequestException(ErrorCodes.ResourceDoesNotExist, nameof(travel));
            }

            if (travel.Version != command.AggregateVersion)
            {
                throw new ResourceStateChangedException(nameof(Travel), travel.Id, travel.Version);
            }

            Identity identity = identityProvider.GetIdentity();

            if (travel.Owner != identity.Username && identity.Role != Roles.Admin)
            {
                throw new UnauthorizedUserException();
            }

            var @event = new TravelDeleted
            {
                RelatedCommandId = command.CommandId,
                Id = command.AggregateId,
            };

            travel.ApplyEvent(@event);
            @event.AggregateVersion = travel.Version;

            await eventPublisher.Publish(@event);
        }
        private ReceiptViewModel GetReceiptForPayment(DibsPaymentResult result)
        {
            var processingResult = _paymentProcessor.ProcessPaymentResult(result, _identityProvider.GetIdentity());

            return(_receiptViewModelBuilder.BuildFor(processingResult));
        }
Ejemplo n.º 6
0
 public Task <IEnumerable <Models.Travel> > Handle(UserTravels query)
 {
     return(store.Query(x => x.Owner == identityProvider.GetIdentity().Username, x => x));
 }
Ejemplo n.º 7
0
        public async Task <Task> InvokeAsync(HttpContext httpContext,
                                             ExpressionConverterResolver expressionConverterResolver,
                                             IEnumerable <IExtensionMethodsProvider> extensionMethodsProviders,
                                             IEnumerable <IStaticMethodsProvider> staticMethodsProviders,
                                             IQueryProviderProvider queryProviderProvider,
                                             IEnumerable <IIdentifier> Identifiers,
                                             IEnumerable <IIdentifierProvider> identifierProviders,
                                             JsonSerializer jsonSerializer,
                                             IEnumerable <IRuleMapsProvider> ruleMapsProviders,
                                             IEnumerable <IRuleMap> ruleMaps,
                                             IEnumerable <ICustomMethodCallExpressionConverter> customMethodCallExpressionConverters,
                                             IIdentityProvider identityProvider,
                                             System.Text.Json.JsonSerializerOptions jsonSerializerOptions)
        {
            Esprima.Ast.Expression jsExpression = null;
            string payload = null;

            using (var reader = new StreamReader(httpContext.Request.Body)) {
                payload = await reader.ReadToEndAsync();

                var parser = new JavaScriptParser(payload, new ParserOptions()
                {
                    Range = true
                });
                jsExpression = parser.ParseExpression();
            }

            // The context holds the converters
            // Building the expression

            var currentUser = identityProvider.GetIdentity().User;

            // The context olds the factories
            ruleMaps = ruleMaps.Union(ruleMapsProviders.SelectMany(rmp => rmp.RuleMaps));
            var expressionConvertersContext = new ExpressionConverterContext()
            {
                ExpressionConverterResolver = expressionConverterResolver,
                ExtensionMethods            = extensionMethodsProviders.SelectMany(emp => emp.Methods),
                StaticMethods   = staticMethodsProviders.SelectMany(emp => emp.Methods),
                RuleMapRegistry = new RuleMapRegistry(ruleMaps, Enumerable.Empty <IRuleMapsProvider>()),
                RuleMaps        = ruleMaps,
                CustomMethodCallExpressionConverters = customMethodCallExpressionConverters,
                securityContext = new Context()
                {
                    User = currentUser
                },
                Source = payload
            };

            var identifiers = new Dictionary <string, System.Linq.Expressions.Expression>();

            foreach (var identifierProvider in identifierProviders)
            {
                foreach (var identifier in identifierProvider.Identifiers)
                {
                    identifiers[identifier.Key] = identifier.Value;
                }
            }
            foreach (var identifier in Identifiers)
            {
                identifiers[identifier.Name] = identifier.Expression;
            }
            // The scope olds the target type, the generic parameter map and varibales set.
            // Note that the target type is null since we cannot predict it at this stage.
            // Note that the generic parameter map is null since we cannot predict it at this stage
            var expressionConvertersScope = new ExpressionConverterScope(null, null)
            {
                Variables = identifiers
            };
            var expression = expressionConverterResolver.Convert(jsExpression, expressionConvertersContext, expressionConvertersScope, false);

            if (expression.Type != typeof(void) && expression.Type != typeof(Task))
            {
                Func <Task <object> > asyncFunction = null;
                if (expression.Type.IsGenericType && expression.Type.GetGenericTypeDefinition() == typeof(Task <>))
                {
                    var f = System.Linq.Expressions.Expression.Lambda <Func <Task> >(expression).Compile();
                    asyncFunction = async() => {
                        var   task = f();
                        await task;
                        return((object)((dynamic)task).Result);
                    };
                }
                else
                {
                    var function = System.Linq.Expressions.Expression.Lambda <Func <object> >(System.Linq.Expressions.Expression.Convert(expression, typeof(object))).Compile();
                    asyncFunction = new Func <Task <object> >(() => Task.FromResult(function()));
                }
                var result = await asyncFunction();

                httpContext.Response.Headers.Add("Content-Type", "application/json");
                httpContext.Response.Headers.Add("charset", "utf8");
                var queryable = result as IQueryable <object>;
                if (queryable != null)
                {
                    result = queryable.ToArray();
                }
                using (var streamWriter = new StreamWriter(httpContext.Response.Body)) {
                    using (var jsonWriter = new JsonTextWriter(streamWriter)) {
                        jsonSerializer.Serialize(jsonWriter, result);
                    }
                }
            }
            else
            {
                Func <Task> asyncAction = null;
                if (expression.Type == typeof(Task))
                {
                    asyncAction = System.Linq.Expressions.Expression.Lambda <Func <Task> >(expression).Compile();
                }
                else
                {
                    var a = System.Linq.Expressions.Expression.Lambda <Action>(expression).Compile();
                    asyncAction = new Func <Task>(() => {
                        a();
                        return(Task.CompletedTask);
                    });
                }
                await asyncAction();
            }
            return(Task.CompletedTask);
        }
Ejemplo n.º 8
0
 public FlirtsController(IDateFirstData data, IIdentityProvider identityProvider)
 {
     this.data = data;
     this.principal = identityProvider.GetIdentity();
 }
Ejemplo n.º 9
0
        public string GetUserId(IRequest request)
        {
            var identity = _identityProvider.GetIdentity(request);

            return(identity.IsAuthenticated ? identity.Name : null);
        }