示例#1
0
        public static async Task <List <MiddlewareResponse> > CreateBulkInvoiceMiddlewareAsync(AuthenticationProvider authenticationProvider, List <OrderResource> orders)
        {
            try
            {
                List <MiddlewareResponse> result = new List <MiddlewareResponse>();

                // Create the HTTP client to perform the request

                using (HttpClient client = new HttpClient())
                {
                    await authenticationProvider.SetAccessTokenAsync(client);

                    foreach (var order in orders)
                    {
                        InvoiceProcessResource resource = Mappers.ToInvoiceProcess(order);

                        string res = await MiddlewareController.InsertInvoiceToIEAsync(client, resource);

                        MiddlewareResponse r = JsonSerializer.Deserialize <MiddlewareResponse>(res);

                        result.Add(r);
                    }
                }

                return(result);
            }
            catch (Exception exception)
            {
                throw new Exception(exception.Message);
            }
        }
示例#2
0
        public async Task MiddlewareExecutionCompleted(MiddlewareResponse response)
        {
            var currentMiddleware = _middlewares[_currentExecutingMidlewareIndex];

            Console.WriteLine($"Middleware {currentMiddleware.Name} executed in {response.TimeTaken.TotalMilliseconds} ms");
            await ExecuteNext(response);
        }
示例#3
0
        public static async Task <MiddlewareResponse> GetStateInvoiceMiddlewareAsync(AuthenticationProvider authenticationProvider, Guid id)
        {
            try
            {
                // Create the HTTP client to perform the request

                using (HttpClient client = new HttpClient())
                {
                    await authenticationProvider.SetAccessTokenAsync(client);

                    MiddlewareResponse res = await MiddlewareController.GetInvoiceProcessAsync(client, id);

                    if (res.state.Equals("Succeeded", StringComparison.OrdinalIgnoreCase))
                    {
                        res.details = await MiddlewareController.GetInvoiceOutputProcessAsync(client, id);
                    }

                    return(res);
                }
            }
            catch (Exception exception)
            {
                throw new Exception(exception.Message);
            }
        }
示例#4
0
        public async Task CreateInvoiceAsync()
        {
            using (var controllerStore = new InvoicingController(AuthenticationProvider))
            {
                // order para criar no invoicing
                List <ItemLine> items = new List <ItemLine>()
                {
                    new ItemLine("Cad-0001", "Cadeira Branca 0001", 2, 10)
                };

                Client shipping = new Client("INDIF", "Miguel Dias", "Rua dos Bombeiros", "Leiria", "4509-003");

                // order para criar no invoicing
                OrderResource order = new OrderResource("ENC.2021.1", shipping, items);

                var result = await controllerStore.PostInvoiceAsync(order);

                if (string.IsNullOrEmpty(result.Value))
                {
                    throw new Exception((result.Result as ObjectResult).Value.ToString());
                }

                MiddlewareResponse r = JsonSerializer.Deserialize <MiddlewareResponse>(result.Value);

                Debug.WriteLine(string.Concat("ProcessId: ", r.id));
                Debug.WriteLine(string.Concat("State: ", r.state));

                Assert.IsTrue(!string.IsNullOrEmpty(result.Value));
            }
        }
示例#5
0
        private Message Convert(MiddlewareResponse response)
        {
            var message = new Message()
            {
                Id                = response.Id.ToString(),
                Payload           = _converter.Serialize(response),
                Properties        = new Dictionary <string, object>(response.ExecutionConfiguration),
                FilterCorrelation = response.PipelineId,
                IsControl         = false,
                ContentType       = typeof(MiddlewareResponse).FullName
            };

            return(message);
        }
示例#6
0
        private Event Convert(MiddlewareResponse response)
        {
            var @event = new Event()
            {
                Payload      = _converter.Serialize(response),
                CreatedOn    = response.CreatedOn,
                Id           = response.Id.ToString(),
                PartitionKey = response.PipelineId,
                ContentType  = typeof(MiddlewareResponse).FullName,
                Properties   = new Dictionary <string, object>(response.ExecutionConfiguration)
            };

            return(@event);
        }
示例#7
0
 public override async Task <PipelineResponse> Complete(MiddlewareResponse response)
 {
     return(await Task.Run(() =>
     {
         Console.WriteLine($"Pipeline {Name} execution {ExecutionId} completed.");
         _timer.Stop();
         return new PipelineResponse()
         {
             IsSuccessfull = true,
             Exception = null,
             ResponseObject = response.Response,
             TimeTaken = _timer.Elapsed
         };
     }));
 }
        public override async Task ExecuteNextAsync(MiddlewareResponse response)
        {
            _currentMiddlewarePosition++;
            if (_currentMiddlewarePosition == Middlewares.Count)
            {
                await CompleteAsync(response);
            }

            var middleware = Middlewares[_currentMiddlewarePosition];
            var request    = new MiddlewareRequest(ExecutionId, response.Message)
            {
                Id = Guid.NewGuid(),
                ExecutionConfiguration = response.ExecutionConfiguration //TODO - Logic to be defined later
            };

            await ExecuteMiddleware(middleware, request);
        }
示例#9
0
        public override Task Process(MiddlewareRequest request)
        {
            var timer = new Stopwatch();

            timer.Start();

            try
            {
                var items = JsonConvert.DeserializeObject <List <Item> >(request.Request);
                if (items == null)
                {
                    timer.Stop();
                    var exception = new MiddlewareExceptionResponse()
                    {
                        Exception              = new Exception("JSON not formed properly"),
                        CompletedAt            = DateTime.UtcNow,
                        TimeTaken              = timer.Elapsed,
                        ExecutionConfiguration = request.ExecutionConfiguration
                    };
                    return(Abort(exception));
                }

                timer.Stop();
                var response = new MiddlewareResponse()
                {
                    Response               = request.Request,
                    CompletedAt            = DateTime.UtcNow,
                    TimeTaken              = timer.Elapsed,
                    ExecutionConfiguration = request.ExecutionConfiguration
                };
                return(Complete(response));
            }
            catch (Exception error)
            {
                timer.Stop();
                var response = new MiddlewareExceptionResponse()
                {
                    Exception              = error,
                    CompletedAt            = DateTime.UtcNow,
                    TimeTaken              = timer.Elapsed,
                    ExecutionConfiguration = request.ExecutionConfiguration
                };
                return(Abort(response));
            }
        }
示例#10
0
        public async Task GetStateInvoiceProcessAsync()
        {
            using (var controllerStore = new InvoicingController(AuthenticationProvider))
            {
                Guid processId = new Guid("8f113710-3c49-458c-b904-08cf600fdcad");

                MiddlewareResponse result = await controllerStore.GetStateInvoiceProcessAsync(processId);

                Debug.WriteLine(string.Concat("ProcessId: ", result.id));
                Debug.WriteLine(string.Concat("State: ", result.state));

                if (result.details != null && !string.IsNullOrEmpty(result.details.invoiceId))
                {
                    Debug.WriteLine(string.Concat("Invoice Id: ", result.details.invoiceId));
                }

                Assert.IsTrue(result.details != null && !string.IsNullOrEmpty(result.details.invoiceId));
            }
        }
        public override Task Process(MiddlewareRequest request)
        {
            var timer = new Stopwatch();

            timer.Start();
            try
            {
                var items = JsonConvert.DeserializeObject <List <Item> >(request.Request);

                foreach (var item in items)
                {
                    Console.WriteLine($"ID: {item.Id}");
                    Console.WriteLine($"Name: {item.Id}");
                    Console.WriteLine($"Description: {item.Id}");
                    Console.WriteLine($"SKU: {item.SKU}");
                    Console.WriteLine($"Cost: {item.Cost}");
                }

                timer.Stop();
                var response = new MiddlewareResponse()
                {
                    Response               = JsonConvert.SerializeObject(items),
                    CompletedAt            = DateTime.UtcNow,
                    TimeTaken              = timer.Elapsed,
                    ExecutionConfiguration = request.ExecutionConfiguration
                };
                return(Complete(response));
            }
            catch (Exception error)
            {
                timer.Stop();
                var response = new MiddlewareExceptionResponse()
                {
                    Exception              = error,
                    CompletedAt            = DateTime.UtcNow,
                    TimeTaken              = timer.Elapsed,
                    ExecutionConfiguration = request.ExecutionConfiguration
                };
                return(Abort(response));
            }
        }
示例#12
0
        private Task ExecuteNext(MiddlewareResponse lastResponse)
        {
            var nextRequest = new MiddlewareRequest()
            {
                ExecutionConfiguration = lastResponse.ExecutionConfiguration,
                Request     = lastResponse.Response,
                InvokedAt   = DateTime.UtcNow,
                ExecutionId = ExecutionId
            };

            _currentExecutingMidlewareIndex++;
            if (_currentExecutingMidlewareIndex >= _middlewares.Count)
            {
                return(Complete(lastResponse));
            }
            else
            {
                var currentMiddleware = _middlewares[_currentExecutingMidlewareIndex];
                return(currentMiddleware.Invoke(nextRequest));
            }
        }
        public override Task Process(MiddlewareRequest request)
        {
            var timer = new Stopwatch();

            timer.Start();

            try
            {
                var items  = JsonConvert.DeserializeObject <List <Item> >(request.Request);
                var prefix = EnvironmentConfiguration["SKU.Prefix"] as string;

                foreach (var item in items)
                {
                    item.SKU = prefix + Guid.NewGuid().ToString().Substring(0, 6);
                }

                timer.Stop();
                var response = new MiddlewareResponse()
                {
                    Response               = JsonConvert.SerializeObject(items),
                    CompletedAt            = DateTime.UtcNow,
                    TimeTaken              = timer.Elapsed,
                    ExecutionConfiguration = request.ExecutionConfiguration
                };
                return(Complete(response));
            }
            catch (Exception error)
            {
                timer.Stop();
                var response = new MiddlewareExceptionResponse()
                {
                    Exception              = error,
                    CompletedAt            = DateTime.UtcNow,
                    TimeTaken              = timer.Elapsed,
                    ExecutionConfiguration = request.ExecutionConfiguration
                };
                return(Abort(response));
            }
        }
示例#14
0
        public static async Task <MiddlewareResponse> GetInvoiceProcessAsync(HttpClient client, Guid id)
        {
            // Create the HTTP client to perform the request

            string url = string.Format(
                MiddlewareRoutes.InvoicesPostRoute,
                Constants.MiddlewareUrlBase,
                Identity.Account,
                Identity.Subscription,
                MiddlewareRoutes.InvoicesUrlBase + "/" + id);

            var response = await client.GetAsync(url).ConfigureAwait(false);

            if (response.IsSuccessStatusCode)
            {
                MiddlewareResponse r = JsonSerializer.Deserialize <MiddlewareResponse>(await response.Content.ReadAsStringAsync());

                return(r);
            }
            else
            {
                throw new Exception(await response.Content.ReadAsStringAsync());
            }
        }
示例#15
0
 public InternalServerErrorObjectResult(MiddlewareResponse contentResult)
 {
     response = contentResult;
 }
示例#16
0
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var response = new MiddlewareResponse {
                Status = new APIResponseStatus {
                    Message = new APIResponseMessage()
                }
            };
            var           userId            = context.HttpContext.User?.FindFirst("userId")?.Value ?? string.Empty;
            List <string> thisUserRoleIds   = new List <string>();
            List <string> thisUserRoleNames = new List <string>();
            List <string> roleActivities    = new List <string>();
            var           thisUserRoleCan   = false;

            if (string.IsNullOrEmpty(userId))
            {
                context.HttpContext.Response.StatusCode = 401;
                context.Result = new UnauthorizedObjectResult(response);
                return;
            }

            using (var scope = context.HttpContext.RequestServices.CreateScope())
            {
                try
                {
                    var scopedServices = scope.ServiceProvider;

                    var serverRequest = scopedServices.GetRequiredService <IIdentityServerRequest>();

                    var userroles = await serverRequest.GetUserRolesAsync();

                    var activities = await serverRequest.GetAllActivityAsync();

                    thisUserRoleIds = userroles.UserRoles.Where(x => x.UserId == userId).Select(x => x.RoleId).ToList();

                    thisUserRoleNames = (from userRole in userroles.UserRoles select userRole?.RoleName).ToList();

                    roleActivities = (from activity in activities.Activities
                                      join userActivityRole
                                      in userroles.UserRoleActivities on activity.ActivityId equals userActivityRole.ActivityId
                                      select userActivityRole.RoleName).ToList();

                    bool hasMatch = roleActivities.Select(x => x).Intersect(thisUserRoleNames).Any();
                    if (hasMatch)
                    {
                        if (Action == UserActions.Add)
                        {
                            thisUserRoleCan = userroles.UserRoleActivities.Any(x => thisUserRoleIds.Contains(x.RoleId) && x.ActivityId == Activity && x.CanAdd == true);
                        }
                        if (Action == UserActions.Approve)
                        {
                            thisUserRoleCan = userroles.UserRoleActivities.Any(x => thisUserRoleIds.Contains(x.RoleId) && x.ActivityId == Activity && x.CanApprove == true);
                        }
                        if (Action == UserActions.Delete)
                        {
                            thisUserRoleCan = userroles.UserRoleActivities.Any(x => thisUserRoleIds.Contains(x.RoleId) && x.ActivityId == Activity && x.CanDelete == true);
                        }
                        if (Action == UserActions.Update)
                        {
                            thisUserRoleCan = userroles.UserRoleActivities.Any(x => thisUserRoleIds.Contains(x.RoleId) && x.ActivityId == Activity && x.CanEdit == true);
                        }
                        if (Action == UserActions.View)
                        {
                            thisUserRoleCan = userroles.UserRoleActivities.Any(x => thisUserRoleIds.Contains(x.RoleId) && x.ActivityId == Activity && x.CanView == true);
                        }
                    }
                    if (!thisUserRoleNames.Contains(StaticRoles.GODP))
                    {
                        if (!thisUserRoleCan)
                        {
                            response.Status.Message.FriendlyMessage = "You don't have privilege to perform this action";
                            var contentResponse = new ContentResult
                            {
                                Content     = JsonConvert.SerializeObject(response),
                                ContentType = "application/json",
                                StatusCode  = 403
                            };
                        }
                    }
                    await next();

                    return;
                }
                catch (Exception ex)
                {
                    var contentResponse = new MiddlewareResponse
                    {
                        Status = new APIResponseStatus
                        {
                            IsSuccessful = false,
                            Message      = new APIResponseMessage {
                                FriendlyMessage = ex?.Message, TechnicalMessage = ex.InnerException?.Message
                            }
                        }
                    };
                    context.HttpContext.Response.StatusCode = 500;
                    context.Result = contentResponse;
                    return;
                }
            }
        }
示例#17
0
 protected virtual async Task CompleteAsync(MiddlewareResponse response)
 {
     await Outbox.SendMessage(response);
 }
示例#18
0
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var response = new MiddlewareResponse {
                Status = new APIResponseStatus {
                    IsSuccessful = false, Message = new APIResponseMessage()
                }
            };
            string       userId     = context.HttpContext.User?.FindFirst("userId")?.Value ?? string.Empty;
            StringValues authHeader = context.HttpContext.Request.Headers["Authorization"];

            bool hasAllowAnonymous = context.ActionDescriptor.EndpointMetadata.Any(em => em.GetType() == typeof(AllowAnonymousAttribute));

            if (context == null || hasAllowAnonymous)
            {
                await next();

                return;
            }
            if (string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(authHeader))
            {
                context.HttpContext.Response.StatusCode = 401;
                context.Result = new UnauthorizedObjectResult(response);
                return;
            }
            string token    = authHeader.ToString().Replace("Bearer ", "").Trim();
            var    handler  = new JwtSecurityTokenHandler();
            var    tokena   = handler.ReadJwtToken(token);
            var    FromDate = tokena.IssuedAt.AddHours(1);
            var    EndDate  = tokena.ValidTo.AddHours(1);

            var expieryMatch = DateTime.UtcNow.AddHours(1);

            if (expieryMatch > EndDate)
            {
                context.HttpContext.Response.StatusCode = 401;
                context.Result = new UnauthorizedObjectResult(response);
                return;
            }

            using (var scope = context.HttpContext.RequestServices.CreateScope())
            {
                try
                {
                    IServiceProvider scopedServices = scope.ServiceProvider;
                    JwtSettings      tokenSettings  = scopedServices.GetRequiredService <JwtSettings>();
                    DataContext      _dataContext   = scopedServices.GetRequiredService <DataContext>();

                    IDetectionService _detectionService = scopedServices.GetRequiredService <IDetectionService>();
                    if (_detectionService.Device.Type.ToString().ToLower() == Device.Desktop.ToString().ToLower())
                    {
                        var currentDeviceDetail = _dataContext.Tracker.Where(q => q.UserId == userId && q.Token == token).ToList();
                        if (currentDeviceDetail.Count() == 0)
                        {
                            context.HttpContext.Response.StatusCode = 401;
                            response.Status.Message.FriendlyMessage = "Duplicate Login Detected";
                            context.Result = new UnauthorizedObjectResult(response);
                            return;
                        }
                    }
                    IMeasureService _measureService = scopedServices.GetRequiredService <IMeasureService>();
                    //if(_measureService.CheckForSessionTrailAsync(userId, (int)Modules.CENTRAL).Result.StatusCode == 401)
                    //{
                    //    context.HttpContext.Response.StatusCode = 401;
                    //    context.Result = new UnauthorizedObjectResult(response);
                    //    return;
                    //}
                    await next();

                    return;
                }
                catch (Exception ex)
                {
                    context.HttpContext.Response.StatusCode  = 500;
                    response.Status.IsSuccessful             = false;
                    response.Status.Message.FriendlyMessage  = ex.Message;
                    response.Status.Message.TechnicalMessage = ex.ToString();
                    context.Result = new InternalServerErrorObjectResult(response);
                    return;
                }
            }
        }
示例#19
0
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var response = new MiddlewareResponse {
                Status = new APIResponseStatus {
                    Message = new APIResponseMessage()
                }
            };
            var userId = context.HttpContext.User?.FindFirst("userId")?.Value ?? string.Empty;
            IEnumerable <string> thisUserRoleIds   = new List <string>();
            IEnumerable <string> thisUserRoleNames = new List <string>();
            IEnumerable <string> roleActivities    = new List <string>();
            var thisUserRoleCan = false;

            using (var scope = context.HttpContext.RequestServices.CreateScope())
            {
                try
                {
                    var scopedServices = scope.ServiceProvider;
                    var _dataContext   = scopedServices.GetRequiredService <DataContext>();

                    thisUserRoleIds = _dataContext?.UserRoles?.Where(x => x.UserId == userId).ToList().Select(x => x.RoleId);

                    thisUserRoleNames = (from role in _dataContext.Roles
                                         join userRole in _dataContext.UserRoles
                                         on role.Id.Trim().ToLower() equals userRole.RoleId.Trim().ToLower()
                                         where userRole.UserId == userId
                                         select role.Name).ToList();

                    roleActivities = (from activity in _dataContext.cor_activity
                                      join userActivityRole in _dataContext.cor_userroleactivity on activity.ActivityId equals userActivityRole.ActivityId
                                      join roles in _dataContext.Roles on userActivityRole.RoleId equals roles.Id
                                      select roles.Name).ToList();

                    bool hasMatch = roleActivities.Select(x => x).Intersect(thisUserRoleNames).Any();

                    if (hasMatch)
                    {
                        if (Action == UserActions.Add)
                        {
                            thisUserRoleCan = _dataContext.cor_userroleactivity.Any(x => thisUserRoleIds.Contains(x.RoleId) && x.ActivityId == Activity && x.CanAdd == true);
                        }
                        if (Action == UserActions.Approve)
                        {
                            thisUserRoleCan = _dataContext.cor_userroleactivity.Any(x => thisUserRoleIds.Contains(x.RoleId) && x.ActivityId == Activity && x.CanApprove == true);
                        }
                        if (Action == UserActions.Delete)
                        {
                            thisUserRoleCan = _dataContext.cor_userroleactivity.Any(x => thisUserRoleIds.Contains(x.RoleId) && x.ActivityId == Activity && x.CanDelete == true);
                        }
                        if (Action == UserActions.Update)
                        {
                            thisUserRoleCan = _dataContext.cor_userroleactivity.Any(x => thisUserRoleIds.Contains(x.RoleId) && x.ActivityId == Activity && x.CanEdit == true);
                        }
                        if (Action == UserActions.View)
                        {
                            thisUserRoleCan = _dataContext.cor_userroleactivity.Any(x => thisUserRoleIds.Contains(x.RoleId) && x.ActivityId == Activity && x.CanView == true);
                        }
                    }


                    if (!thisUserRoleNames.Contains(StaticRoles.GODP))
                    {
                        if (!thisUserRoleCan)
                        {
                            response.Status.Message.FriendlyMessage = GenericMiddlwareMessages.NO_PRIVILEGE;
                            var contentResponse = new ContentResult
                            {
                                Content     = JsonConvert.SerializeObject(response),
                                ContentType = "application/json",
                                StatusCode  = 403
                            };
                            context.HttpContext.Response.StatusCode = 403;
                            context.Result = contentResponse;
                            return;
                        }
                    }
                    await next();

                    return;
                }
                catch (Exception ex)
                {
                    var contentResponse = new MiddlewareResponse
                    {
                        Status = new APIResponseStatus
                        {
                            IsSuccessful = false,
                            Message      = new APIResponseMessage {
                                FriendlyMessage = ex?.Message, TechnicalMessage = ex.InnerException?.Message
                            }
                        }
                    };
                    context.HttpContext.Response.StatusCode = 500;
                    context.Result = new BadRequestObjectResult(contentResponse);
                    return;
                }
            }
        }
示例#20
0
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var response = new MiddlewareResponse {
                Status = new APIResponseStatus {
                    IsSuccessful = false, Message = new APIResponseMessage()
                }
            };

            using (var scope = context.HttpContext.RequestServices.CreateScope())
            {
                try
                {
                    IServiceProvider   scopedServices = scope.ServiceProvider;
                    RedisCacheSettings redisSettings  = scopedServices.GetRequiredService <RedisCacheSettings>();
                    if (!redisSettings.Enabled)
                    {
                        await next();

                        return;
                    }

                    DataContext           _dataContext         = scopedServices.GetRequiredService <DataContext>();
                    IResponseCacheService responseCacheService = scopedServices.GetRequiredService <IResponseCacheService>();
                    var cacheKey = Cache.GenerateCacheKeyFromRequest(context.HttpContext.Request);

                    if (context.HttpContext.Request.Method != "GET")
                    {
                        await responseCacheService.ResetCacheAsync(cacheKey);
                    }
                    var cachedResponse = await responseCacheService.GetCacheResponseAsync(cacheKey);

                    if (!string.IsNullOrEmpty(cachedResponse))
                    {
                        var contentResult = new ContentResult
                        {
                            Content     = cachedResponse,
                            ContentType = "application/json",
                            StatusCode  = 200
                        };
                        context.Result = contentResult;
                        return;
                    }

                    var executedContext = await next();

                    if (executedContext.Result is OkObjectResult okObjectResult)
                    {
                        await responseCacheService.CatcheResponseAsync(cacheKey, okObjectResult, TimeSpan.FromSeconds(1000));

                        context.HttpContext.Response.StatusCode = 200;
                        context.Result = new OkObjectResult(okObjectResult);
                        return;
                    }
                    await next();
                }
                catch (Exception ex)
                {
                    context.HttpContext.Response.StatusCode  = 500;
                    response.Status.IsSuccessful             = false;
                    response.Status.Message.FriendlyMessage  = ex.Message;
                    response.Status.Message.TechnicalMessage = ex.ToString();
                    context.Result = new InternalServerErrorObjectResult(response);
                    return;
                }
            }
        }
示例#21
0
 public abstract Task ExecuteNextAsync(MiddlewareResponse response);