Esempio n. 1
0
        public override void OnActionExecuting(HttpActionContext context)
        {
            using (IUnitOfWork unitOfWork = new UnitOfWork())
            {
                IRepository <User> repository  = new Repository <User>(unitOfWork);
                IUserService       userService = new UserService(repository);
                IAuthService       authService = new AuthService(repository);

                bool skipAuthorization = context.ActionDescriptor.GetCustomAttributes <AllowAnonymousAttribute>().Any() ||
                                         context.ActionDescriptor.ControllerDescriptor.GetCustomAttributes <AllowAnonymousAttribute>().Any();
                if (skipAuthorization)
                {
                    return;
                }

                if (context.Request.Headers.Authorization == null)
                {
                    context.Response = context.Request.CreateResponse(HttpStatusCode.Unauthorized, new { message = "Authorization key required" });
                    return;
                }
                string   apiKey = context.Request.Headers.Authorization.ToString();
                User     user   = userService.FindBy(x => x.ApiKey == apiKey).FirstOrDefault();
                DateTime now    = DateUtil.GetDateTimeNow();
                if (user == null || (user.ExpiraApiKey.HasValue && user.ExpiraApiKey.Value < now))
                {
                    context.Response = context.Request.CreateResponse(HttpStatusCode.Unauthorized, new { message = "Invalid authorization token" });
                    return;
                }
                LanguageMngr.SetLanguage(user.Language);
                UserApiAuthenticated.SetUserAuthenticated(context, user);
            }
        }
Esempio n. 2
0
        public override void OnActionExecuting(HttpActionContext context)
        {
            using (IUnitOfWork unitOfWork = new UnitOfWork())
            {
                IRepository <User> repository  = new Repository <User>(unitOfWork);
                IUserService       userService = new UserService(repository);
                IAuthService       authService = new AuthService(repository);

                bool skipAuthorization = context.ActionDescriptor.GetCustomAttributes <AllowAnonymousAttribute>().Any() ||
                                         context.ActionDescriptor.ControllerDescriptor.GetCustomAttributes <AllowAnonymousAttribute>().Any();
                if (skipAuthorization)
                {
                    return;
                }

                if (context.Request.Headers.Authorization == null)
                {
                    context.Response = context.Request.CreateResponse(HttpStatusCode.Unauthorized, new { message = "Authorization key required" });
                    return;
                }
                string   apiKey = context.Request.Headers.Authorization.ToString();
                User     user   = userService.FindBy(x => x.ApiKey == apiKey).FirstOrDefault();
                DateTime now    = DateUtil.GetDateTimeNow();
                if (user == null || (user.ExpiraApiKey.HasValue && user.ExpiraApiKey.Value < now))
                {
                    context.Response = context.Request.CreateResponse(HttpStatusCode.Unauthorized, new { message = "Invalid authorization token" });
                    return;
                }
                string actionName     = context.ActionDescriptor.ActionName;
                string controllerName = context.ActionDescriptor.ControllerDescriptor.ControllerName;
                IEnumerable <Permission> permissions = authService.GetPermissions(user.Id,
                                                                                  actionName, controllerName,
                                                                                  Constants.PERMISSIONS_TYPE_ENUM.API.GetEnumValue <string>());
                if (!permissions.Any())
                {
                    context.Response = context.Request.CreateResponse(HttpStatusCode.Forbidden, new { message = "User has no permissions for this action" });
                    return;
                }
                LanguageMngr.SetLanguage(user.Language);
                UserApiAuthenticated.SetUserAuthenticated(context, user);
                //Validacion de tokens generados

                /*
                 * if (!tokenEngine.ValidateToken(apiKey, out clienteId))
                 * {
                 *  context.Response = context.Request.CreateResponse(HttpStatusCode.Unauthorized, new { mensaje = "invalid authorization token" });
                 *  return;
                 * }
                 * context.Request.Properties.Add(new KeyValuePair<string, object>("clienteId", clienteId));*/
                //context.Request.Properties.Add(new KeyValuePair<string, object>("clientEmail", clientEmail));
            }
        }
Esempio n. 3
0
        //<summary>Recibe la peticion del servidor antes de que llegue al controlador para realzar el log de la peticion.</summary>
        /// <param name="cancellationToken"></param>
        /// <param name="request">Objeto que contiene informacion de las peticiones.</param>
        /// <returns>Respuesta del servidor</returns>
        protected override async System.Threading.Tasks.Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            using (IUnitOfWork unitOfWork = new UnitOfWork())
            {
                IRepository <ApiLog> repository     = new Repository <ApiLog>(unitOfWork);
                IRepository <User>   repositoryUser = new Repository <User>(unitOfWork);
                apiLogService = new ApiLogService(repository);
                userService   = new UserService(repositoryUser);

                StringBuilder                 content                = new StringBuilder();
                string                        requestUuid            = request.GetCorrelationId().ToString();
                HttpConfiguration             config                 = GlobalConfiguration.Configuration;
                IHttpRouteData                routeData              = config.Routes.GetRouteData(request);
                HttpControllerContext         controllerContext      = new HttpControllerContext(config, routeData, request);
                DefaultHttpControllerSelector controllerSelector     = new DefaultHttpControllerSelector(config);
                HttpControllerDescriptor      controllerDescriptor   = controllerSelector.SelectController(request);
                ApiControllerActionSelector   apiControllerSelection = new ApiControllerActionSelector();
                controllerContext.ControllerDescriptor = controllerDescriptor;
                HttpActionDescriptor actionDescriptor = apiControllerSelection.SelectAction(controllerContext);
                ApiLog requestLog = new ApiLog();
                requestLog.Uuid       = requestUuid;
                requestLog.Controller = controllerDescriptor.ControllerName;
                requestLog.Action     = actionDescriptor.ActionName;
                //Obtiene y decodifica el post para que se muestre la informacion de la manera adecuada
                string data = HttpUtility.UrlDecode(request.Content.ReadAsStringAsync().Result);
                requestLog.Data      = data;
                requestLog.CreatedAt = DateTime.Now;
                requestLog.Url       = request.RequestUri.AbsoluteUri;//request.RequestUri.Host + HttpUtility.UrlDecode(request.RequestUri.PathAndQuery);
                requestLog.Method    = request.Method.Method;
                requestLog.Status    = "Started";
                object headers = request.Headers.ToDictionary(x => x.Key, y => y.Value);
                requestLog.Headers = JsonConvert.SerializeObject(headers);
                //unitOfWork.BeginTransaction();
                try
                {
                    apiLogService.Create(requestLog);
                    //unitOfWork.Commit();
                }
                catch (Exception e)
                {
                    //unitOfWork.Rollback();
                }
                //Se espera la respuesta del controlador
                var response = await base.SendAsync(request, cancellationToken);

                requestUuid = request.GetCorrelationId().ToString();
                //unitOfWork.BeginTransaction();
                try
                {
                    requestLog = apiLogService.FindBy(x => x.Uuid == requestUuid).FirstOrDefault();
                    User user   = null;
                    int? userId = UserApiAuthenticated.GetUserAuthenticatedId(request.GetRequestContext());
                    if (userId.HasValue)
                    {
                        user = userService.GetById(userId.Value);
                    }
                    if (user != null)
                    {
                        requestLog.CreatedBy = user;
                    }
                    if (requestLog != null)
                    {
                        if (response.RequestMessage != null && response.Content != null)
                        {
                            var responseContent = await response.Content.ReadAsStringAsync();

                            if (requestLog.Exception != null)
                            {
                                requestLog.Status = "HasException";
                            }
                            else
                            {
                                requestLog.Status = "Completed";
                            }
                            requestLog.Result = responseContent.ToString();
                            apiLogService.Update(requestLog);
                        }
                    }
                    //unitOfWork.Commit();
                }catch (Exception e)
                {
                    //unitOfWork.Rollback();
                }
                return(response);
            }
        }