Ejemplo n.º 1
0
        private bool disposedValue = false; // To detect redundant calls

        // TODO: Refactor to abide by OCP, currently a new deserialiser would require this class to be changed
        public IDeserialise Create(ApiResponseFormat Format)
        {
            switch (Format)
            {
            case ApiResponseFormat.JSON:
                return(new JsonDeserialise());

            default:
                throw new ArgumentException("Invalid argument");
            }
        }
Ejemplo n.º 2
0
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            Check.Argument.IsNotNull(controllerContext, "controllerContext");

            ApiCommand command = (ApiCommand)base.BindModel(controllerContext, bindingContext);

            HttpContextBase httpContext = controllerContext.HttpContext;
            HttpRequestBase httpRequest = httpContext.Request;

            command.IPAddress = httpRequest.UserHostAddress;

            string format = null;

            // First we will check whether format is explicitly specified
            ValueProviderResult providerResult = controllerContext.Controller.ValueProvider.GetValue("format");

            if (providerResult != null)
            {
                format = (string)providerResult.ConvertTo(typeof(string), Culture.Current);
            }

            ApiResponseFormat responseFormat = ApiResponseFormat.Text;

            if (string.IsNullOrWhiteSpace(format) || !Enum.TryParse(format, true, out responseFormat))
            {
                // No format exist, try the AcceptTypes
                if ((httpRequest.AcceptTypes != null) && (httpRequest.AcceptTypes.Length > 0))
                {
                    string firstAcceptType = QValueSorter.Sort(httpRequest.AcceptTypes).FirstOrDefault() ?? string.Empty;

                    if (!string.IsNullOrWhiteSpace(firstAcceptType))
                    {
                        if (firstAcceptType.Equals("application/json", StringComparison.OrdinalIgnoreCase) || firstAcceptType.Equals("text/json", StringComparison.OrdinalIgnoreCase))
                        {
                            responseFormat = ApiResponseFormat.Json;
                        }
                        else if (firstAcceptType.Equals("application/xml", StringComparison.OrdinalIgnoreCase) || firstAcceptType.Equals("text/xml", StringComparison.OrdinalIgnoreCase))
                        {
                            responseFormat = ApiResponseFormat.Xml;
                        }
                    }
                }
            }

            command.ResponseFormat = responseFormat;

            return(command);
        }
Ejemplo n.º 3
0
        public void ExecuteResult_should_write_correct_content_to_response(ApiResponseFormat responseFormat, string content)
        {
            var alias = new Alias {
                Name = "MSDN", ShortUrl = new ShortUrl {
                    Title = "MSDN", Url = "http://msdn.microsoft.com/"
                }
            };
            var shortUrlDto = new ShortUrlDTO(alias, 3, "http://shrinkr.com/msdn", "http://shrinkr.com/Preview/msdn");
            var viewModel   = new CreateUrlViewModel(shortUrlDto);

            controllerContext.Controller.ViewData = new ViewDataDictionary(viewModel);

            var result = new ApiResult(responseFormat);

            result.ExecuteResult(controllerContext);

            httpContext.Verify(c => c.Response.Write(content));
        }
Ejemplo n.º 4
0
 public HipChatClient(string token, ApiResponseFormat format)
     : this(token)
 {
     this.Format = format;
 }
Ejemplo n.º 5
0
        public void ExecuteResult_should_set_response_content_type_to_correct_response_format_type(ApiResponseFormat responseFormat, string expectedContentType)
        {
            var result = new ApiResult(responseFormat);

            result.ExecuteResult(controllerContext);

            httpContext.VerifySet(c => c.Response.ContentType = expectedContentType);
        }
Ejemplo n.º 6
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddTransient <IPasswordValidator <Usuario>, ValidarContrasenia>();
            services.AddDbContext <BibliotecaOtakaBDContext>(options => options.UseSqlServer(Configuration.GetConnectionString("BibliotecaOtakaAglr")), ServiceLifetime.Transient);

            services.AddCors();

            services.AddIdentity <Usuario, IdentityRole>(options =>
            {
                options.Password.RequiredLength         = 6;
                options.Password.RequireDigit           = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequiredUniqueChars    = 0;
                options.Password.RequireLowercase       = false;
                options.Password.RequireNonAlphanumeric = false;

                options.User.RequireUniqueEmail        = true;
                options.User.AllowedUserNameCharacters = " ABCDEFGHIJKLMNOPRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_*";

                options.Tokens.EmailConfirmationTokenProvider = "emailconfirmation";
            })
            .AddEntityFrameworkStores <BibliotecaOtakaBDContext>()
            .AddDefaultTokenProviders()
            .AddTokenProvider <EmailConfirmationTokenProvider <Usuario> >("emailconfirmation");

            services.Configure <DataProtectionTokenProviderOptions>(opt => opt.TokenLifespan    = TimeSpan.FromHours(2));
            services.Configure <EmailConfirmationTokenProviderOptions>(opt => opt.TokenLifespan = TimeSpan.FromDays(3));

            services.AddSingleton(Configuration.GetSection("EmailConfiguration").Get <MensajeroConfiguracion>());
            services.AddScoped <IMensajero, Mensajero>();

            services.AddControllers();
            services.AddMvcCore()
            .ConfigureApiBehaviorOptions(options =>
            {
                options.InvalidModelStateResponseFactory = (context) =>
                {
                    IDictionary <string, string[]> Errors = new Dictionary <string, string[]>();

                    foreach (var keyModelStatePair in context.ModelState)
                    {
                        var campo  = keyModelStatePair.Key;
                        var errors = keyModelStatePair.Value.Errors;
                        if (errors != null && errors.Count > 0)
                        {
                            if (errors.Count == 1)
                            {
                                var errorMessage = string.IsNullOrEmpty(errors[0].ErrorMessage) ? "Valor invalido." : errors[0].ErrorMessage;
                                Errors.Add(campo, new[] { errorMessage });
                            }
                            else
                            {
                                var errorMessages = new string[errors.Count];
                                for (var i = 0; i < errors.Count; i++)
                                {
                                    errorMessages[i] = string.IsNullOrEmpty(errors[0].ErrorMessage) ? "Valor invalido." : errors[0].ErrorMessage;
                                }

                                Errors.Add(campo, errorMessages);
                            }
                        }
                    }

                    var result = new ApiResponseFormat
                    {
                        Dato    = Errors,
                        Estado  = (int)HttpStatusCode.BadRequest,
                        Mensaje = "Uno o varios errores detectados",
                    };
                    return(new BadRequestObjectResult(result));
                };
            })
            .AddNewtonsoftJson(options => {
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            });

            services.AddScoped <IUserService, UserService>();
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddGoogle(options =>
            {
                options.ClientId         = Configuration["Authentication:Google:ClientId"];
                options.ClientSecret     = Configuration["Authentication:Google:ClientSecret"];
                options.AccessDeniedPath = new PathString("/uwu");
            })
            .AddFacebook(options =>
            {
                options.ClientId         = Configuration["Authentication:Facebook:ClientId"];
                options.ClientSecret     = Configuration["Authentication:Facebook:ClientSecret"];
                options.AccessDeniedPath = new PathString("/uwu");
            })
            .AddJwtBearer(options =>
            {
                options.Events = new JwtBearerEvents
                {
                    OnTokenValidated = context =>
                    {
                        var userService = context.HttpContext.RequestServices.GetRequiredService <IUserService>();
                        var userName    = context.Principal.Identity.Name;
                        var user        = userService.GetByName(userName);
                        var validtoken  = userService.ValidateToken(userName).Result;
                        if (user == null)
                        {
                            // return unauthorized if user no longer exists
                            context.Fail("Unauthorized");
                        }
                        else if (validtoken == false)
                        {
                            // return message if token is not longer valid
                            context.Fail("Sesion expirada, inicie sesion de nuevo");
                        }
                        return(Task.CompletedTask);
                    }
                };
                options.RequireHttpsMetadata      = false;
                options.SaveToken                 = true;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration["SecretTokenKey:Key"])),
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                };
            });

            services.ConfigureApplicationCookie(options =>
            {
                options.LoginPath          = new PathString("/Inicio-sesion");
                options.AccessDeniedPath   = new PathString("/uwu");
                options.ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
                options.SlidingExpiration  = true;
                options.ExpireTimeSpan     = TimeSpan.FromHours(1);
                options.Cookie.Name        = "Pranamix";
            });

            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });
        }
Ejemplo n.º 7
0
 public ApiResult(ApiResponseFormat responseFormat)
 {
     ResponseFormat = responseFormat;
 }
Ejemplo n.º 8
0
 public HipChatClient(string token, int room, ApiResponseFormat format)
     : this(token, room)
 {
     this.Format = format;
 }
Ejemplo n.º 9
0
 public void AddDefaultResponseFormat(ApiResponseFormat responseFormat)
 {
     DefaultResponseFormats.Add(responseFormat);
 }
Ejemplo n.º 10
0
        public void ResultFormat_should_be_detected_from_accept_types_when_no_format_is_specified(string accpetTypes, ApiResponseFormat format)
        {
            var httpContext = MvcTestHelper.CreateHttpContext();

            httpContext.SetupGet(c => c.Request.AcceptTypes).Returns(accpetTypes.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
            httpContext.SetupGet(c => c.Request.UserHostAddress).Returns("192,168.0.1");

            var routeData = new RouteData();

            routeData.Values.Add("controller", "dummy");
            routeData.Values.Add("action", "Process");

            var requestContext = new RequestContext(httpContext.Object, routeData);

            var valueProvider = new Mock <IValueProvider>();
            var controller    = new DummyController {
                ValueProvider = valueProvider.Object
            };

            var controllerContext = new ControllerContext(requestContext, controller);

            controller.ControllerContext = controllerContext;

            var bindingContext = new ModelBindingContext
            {
                ModelMetadata         = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(DummyCommand)),
                ValueProvider         = valueProvider.Object,
                ModelName             = "command",
                FallbackToEmptyPrefix = true
            };

            var command = (DummyCommand) new ApiCommandBinder().BindModel(controllerContext, bindingContext);

            Assert.Equal(format, command.ResponseFormat);
        }