protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, AuthorizationTokenRequirement requirement)
        {
            Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext resource          = context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext;
            Microsoft.AspNetCore.Http.DefaultHttpContext          httpContext             = resource.HttpContext as Microsoft.AspNetCore.Http.DefaultHttpContext;
            Microsoft.AspNetCore.Http.Internal.DefaultHttpRequest request                 = httpContext.Request as Microsoft.AspNetCore.Http.Internal.DefaultHttpRequest;
            Microsoft.AspNetCore.Server.Kestrel.Internal.Http.FrameRequestHeaders headers = request.Headers as Microsoft.AspNetCore.Server.Kestrel.Internal.Http.FrameRequestHeaders;

            string AuthorizationToken = headers.HeaderAuthorization;

            if (String.IsNullOrEmpty(AuthorizationToken))
            {
                context.Fail();
            }
            else
            {
                string authvalue    = AuthorizationToken.Replace("Bearer ", "");
                bool   isTokenValid = tokenProvider.IsTokenValid(authvalue);
                if (isTokenValid)
                {
                    ReadOnlyCollection <Claim> claims = tokenProvider.GetClaimsCollection(authvalue);
                    currentAuthenticationContext.setCurrentUser(claims.GetKey(ClaimKeys.USER_ID));
                    currentAuthenticationContext.setCurrentRoleId(claims.GetKey(ClaimKeys.ROLE));
                    context.Succeed(requirement);
                }
                else
                {
                    context.Fail();
                }
            }


            return(Task.CompletedTask);
        }
Ejemplo n.º 2
0
        public InversionsController_Select_Test()
        {
            _contextOptions = CreateNewContextOptions();
            context         = new ApplicationDbContext(_contextOptions);

            // Insert seed data into the database using one instance of the context

            //Areas Temáticas
            context.Areas.Add(new Areas {
                Nombre = "Sanidad"
            });

            //Rating
            var rating = new Rating {
                Nombre = "A"
            };

            context.Rating.Add(rating);

            //Tipos de Inversiones
            context.TiposInversiones.Add(new TiposInversiones {
                Nombre = "Crowdfunding"
            });

            //Proyecto
            context.Proyecto.Add(new Proyecto {
                ProyectoId = 1, FechaExpiracion = new DateTime(2019, 01, 23), Importe = 30000, Interes = (float)5.90, MinInversion = 50, Nombre = "E-MEDICA", NumInversores = 0, Plazo = 12, Progreso = 0, Rating = rating
            });
            context.Proyecto.Add(new Proyecto {
                ProyectoId = 2, FechaExpiracion = new DateTime(2019, 01, 14), Importe = 70000, Interes = (float)7.25, MinInversion = 0, Nombre = "PROTOS", NumInversores = 0, Plazo = 48, Progreso = 0, Rating = rating
            });
            //context.Proyecto.Add (new Proyecto { ProyectoId = 3, FechaExpiracion = new DateTime (2019, 01, 14), Importe = 93000, Interes = (float) 4.50, MinInversion = 100, Nombre = "SUBSOLE", NumInversores = 0, Plazo = 6, Progreso = 0, RatingId = 1 });

            //Inversor
            context.Users.Add(new Inversor {
                UserName         = "******", NIF = "47446245M", PhoneNumber = "684010548", Email = "*****@*****.**",
                Nombre           = "Yasin", Apellido1 = "Muñoz", Apellido2 = "El Merabety", Domicilio = "Gabriel Ciscar, 26", Nacionalidad = "Española",
                PaisDeResidencia = "España", Provincia = "Albacete"
            });

            context.SaveChanges();

            foreach (var proyecto in context.Proyecto.ToList())
            {
                context.ProyectoAreas.Add(new ProyectoAreas {
                    Proyecto = proyecto, Areas = context.Areas.First()
                });
                context.ProyectoTiposInversiones.Add(new ProyectoTiposInversiones {
                    Proyecto = proyecto, TiposInversiones = context.TiposInversiones.First()
                });
            }
            context.SaveChanges();

            //Simulación conexión de un usuario
            System.Security.Principal.GenericIdentity user     = new System.Security.Principal.GenericIdentity("*****@*****.**");
            System.Security.Claims.ClaimsPrincipal    identity = new System.Security.Claims.ClaimsPrincipal(user);
            inversionContext      = new Microsoft.AspNetCore.Http.DefaultHttpContext();
            inversionContext.User = identity;
        }
Ejemplo n.º 3
0
        public static void TestGetHeader()
        {
            Microsoft.AspNetCore.Http.HttpContext ctx = new Microsoft.AspNetCore.Http.DefaultHttpContext();

            ctx.Request.Headers["device-id"]       = "20317";
            ctx.Request.Headers["Accept-Language"] = "en-ca,en;q=0.8,en-us;q=0.6,de-de;q=0.4,de;q=0.2";

            GetHeader(ctx);
        }
Ejemplo n.º 4
0
        public static void SetControllerContext(
            Controller controller,
            string username,
            string[] roles)
        {
            var httpContext = new Microsoft.AspNetCore.Http.DefaultHttpContext();

            httpContext.User = new GenericPrincipal(
                new GenericIdentity(username), roles);

            var controllerContext = new ControllerContext(
                new ActionContext(
                    httpContext,
                    new RouteData(),
                    new Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor()));

            controller.ControllerContext = controllerContext;
        }
        public static void Test()
        {
            // var language = window.navigator.userLanguage || window.navigator.language;
            // window.navigator.userLanguage is IE only and it's the language set in Windows Control Panel - Regional Options and NOT browser language,
            // but you could suppose that a user using a machine with Window Regional settings set to France is probably a French user.
            // navigator.language is FireFox and all other browser.

            Microsoft.AspNetCore.Http.HttpContext ctx = new Microsoft.AspNetCore.Http.DefaultHttpContext();

            ctx.Request.Headers["device-id"] = "20317";
            // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Language
            ctx.Request.Headers["Accept-Language"] = "it;de-CH,en-ca,en;q=0.8,en-us;q=0.6,de-de;q=0.4,de;q=0.2";
            // ctx.Request.Headers["Accept-Language"] = "";

            string defLang = GetDefaultLanguage(ctx, "de");

            System.Console.WriteLine(defLang);
        } // End Sub Test
        public async Task FllwsRejectsUnauthorizedRequestsWith401Error()
        {
            var userRepositoryMock = new Mock <IUserRepository>();
            var loggerMock         = new Mock <ILogger <UserController> >();
            var httpContext        = new Microsoft.AspNetCore.Http.DefaultHttpContext(); // or mock a `HttpContext`
            var controllerContext  = new ControllerContext()
            {
                HttpContext = httpContext,
            };

            var controller = new UserController(userRepositoryMock.Object, loggerMock.Object)
            {
                ControllerContext = controllerContext
            };

            var res = await controller.fllws(new followModel(), "John Doe");

            Assert.IsType <UnauthorizedResult>(res);
        }
        public async Task AddMessageRejectsUnauthorizedRequestsWith401Error()
        {
            var timelineRepositoryMock = new Mock <ITimelineRepository>();
            var loggerMock             = new Mock <ILogger <TimelineController> >();
            var httpContext            = new Microsoft.AspNetCore.Http.DefaultHttpContext(); // or mock a `HttpContext`
            var controllerContext      = new ControllerContext()
            {
                HttpContext = httpContext,
            };

            var controller = new TimelineController(timelineRepositoryMock.Object, loggerMock.Object)
            {
                ControllerContext = controllerContext
            };

            var res = await controller.AddMessage(new TimelineController.MessageCreate {
                content = "hello"
            }, "testUser");

            Assert.IsType <UnauthorizedResult>(res);
        }
        public async Task FllwsExecutesRequestMadeWithSimulatorHeader()
        {
            var userRepositoryMock = new Mock <IUserRepository>();
            var loggerMock         = new Mock <ILogger <UserController> >();
            var httpContext        = new Microsoft.AspNetCore.Http.DefaultHttpContext(); // or mock a `HttpContext`

            httpContext.Request.Headers["Authorization"] = AuthorizationConstants.terribleHackAuth;
            var controllerContext = new ControllerContext()
            {
                HttpContext = httpContext,
            };

            var controller = new UserController(userRepositoryMock.Object, loggerMock.Object)
            {
                ControllerContext = controllerContext
            };

            var res = await controller.fllws(new followModel(), "John Doe");

            Assert.IsType <NoContentResult>(res);
        }
Ejemplo n.º 9
0
        //Search google for "e-Settlements" and return the number of matches pointing to sympli.com.au in the first 100 results.
        public void TestGoogleSearchSuccess()
        {
            var mockContext = new Microsoft.AspNetCore.Http.DefaultHttpContext();

            mockContext.Request.Headers.Add("searchString", "e-Settlements");
            mockContext.Request.Headers.Add("targetUrl", "www.sympli.com.au");
            mockContext.Request.Headers.Add("resultsCount", "100");
            mockContext.Request.Headers.Add("engineTypeId", $"{(int)SearchEngineType.Google}");

            var ctl = new SEOSearchController()
            {
                ControllerContext = new Microsoft.AspNetCore.Mvc.ControllerContext()
                {
                    HttpContext = mockContext
                }
            };

            var response = ctl.Get();

            Assert.IsTrue(response.Success);
        }
        public async Task AddMessageExecutesRequestMadeWithSimulatorHeader()
        {
            var timelineRepositoryMock = new Mock <ITimelineRepository>();
            var loggerMock             = new Mock <ILogger <TimelineController> >();
            var httpContext            = new Microsoft.AspNetCore.Http.DefaultHttpContext(); // or mock a `HttpContext`

            httpContext.Request.Headers["Authorization"] = AuthorizationConstants.terribleHackAuth;
            var controllerContext = new ControllerContext()
            {
                HttpContext = httpContext,
            };

            var controller = new TimelineController(timelineRepositoryMock.Object, loggerMock.Object)
            {
                ControllerContext = controllerContext
            };

            var res = await controller.AddMessage(new TimelineController.MessageCreate {
                content = "hello"
            }, "testUser");

            Assert.IsType <NoContentResult>(res);
        }
Ejemplo n.º 11
0
        //Tests two separate google results, ensuring that incorrect data isn't pulled from the cache
        public void TestSeparateGoogleResults()
        {
            var mockContext = new Microsoft.AspNetCore.Http.DefaultHttpContext();

            mockContext.Request.Headers.Add("searchString", "e-Settlements");
            mockContext.Request.Headers.Add("targetUrl", "www.sympli.com.au");
            mockContext.Request.Headers.Add("resultsCount", "100");
            mockContext.Request.Headers.Add("engineTypeId", $"{(int)SearchEngineType.Google}");

            var ctl = new SEOSearchController()
            {
                ControllerContext = new Microsoft.AspNetCore.Mvc.ControllerContext()
                {
                    HttpContext = mockContext
                }
            };

            var response = ctl.Get();

            System.Threading.Thread.Sleep(1000);

            var mockContext2 = new Microsoft.AspNetCore.Http.DefaultHttpContext();

            mockContext2.Request.Headers.Add("searchString", "Digital Settlements");
            mockContext2.Request.Headers.Add("targetUrl", "www.sympli.com.au");
            mockContext2.Request.Headers.Add("resultsCount", "50");
            mockContext2.Request.Headers.Add("engineTypeId", $"{(int)SearchEngineType.Google}");

            ctl.ControllerContext = new Microsoft.AspNetCore.Mvc.ControllerContext()
            {
                HttpContext = mockContext2
            };

            var secondResponse = ctl.Get();

            Assert.IsTrue(response.Success && secondResponse.Success && secondResponse.SearchDate != response.SearchDate);
        }
 public DefaultHttpResponse(Microsoft.AspNetCore.Http.DefaultHttpContext context)
 {
 }
 public DefaultHttpRequest(Microsoft.AspNetCore.Http.DefaultHttpContext context)
 {
 }
        public InversionRecuperadasController_Select_test()
        {
            _contextOptions = CreateNewContextOptions();
            context         = new ApplicationDbContext(_contextOptions);
            //Insertar datos semilla en la base de datos usando una instancia de contexto


            var rating = new Rating {
                Nombre = "A"
            };

            context.Rating.Add(rating);
            var area = new Areas {
                Nombre = "Sanidad"
            };

            context.Areas.Add(area);
            var tipo = new TiposInversiones {
                Nombre = "Crownfunding"
            };

            context.TiposInversiones.Add(tipo);



            Proyecto proyecto1 = new Proyecto
            {
                ProyectoId      = 1,
                FechaExpiracion = new DateTime(2020, 1, 1),
                Importe         = 12,
                Interes         = 2,
                MinInversion    = 5,
                Nombre          = "Pruebas en sanidad",
                NumInversores   = 0,
                Plazo           = 12,
                Progreso        = 34,
                Rating          = rating
            };

            context.Proyecto.Add(proyecto1);

            context.ProyectoAreas.Add(new ProyectoAreas {
                Proyecto = proyecto1, Areas = area
            });


            Inversor inversor1 = new Inversor
            {
                Id               = "1",
                Nombre           = "*****@*****.**",
                Email            = "*****@*****.**",
                Apellido1        = "Girón",
                Apellido2        = "López",
                Domicilio        = "C/Cuenca",
                Municipio        = "Albacete",
                NIF              = "48259596",
                Nacionalidad     = "Española",
                PaisDeResidencia = "España",
                Provincia        = "Albacete",
                PasswordHash     = "hola",
                UserName         = "******"
            };

            context.Users.Add(inversor1);


            context.Inversion.Add(new Inversion
            {
                InversionId        = 1,
                Cuota              = 6,
                EstadosInversiones = "En_Curso",
                Intereses          = 12,
                Inversor           = inversor1,
                Proyecto           = proyecto1,
                TipoInversionesId  = 1,
                Total              = 50
            });

            context.Inversion.Add(new Inversion
            {
                InversionId        = 2,
                Cuota              = 15,
                EstadosInversiones = "Finalizado",
                Intereses          = 23,
                Inversor           = inversor1,
                Proyecto           = proyecto1,
                TipoInversionesId  = 1,
                Total              = 100
            });

            context.SaveChanges();

            //Para simular la conexión:
            System.Security.Principal.GenericIdentity user     = new System.Security.Principal.GenericIdentity("*****@*****.**");
            System.Security.Claims.ClaimsPrincipal    identity = new System.Security.Claims.ClaimsPrincipal(user);
            inversionRecuperadaContext      = new Microsoft.AspNetCore.Http.DefaultHttpContext();
            inversionRecuperadaContext.User = identity;
        }
        public SolicitudesController_Select_test()
        {
            _contextOptions = CreateNewContextOptions();
            // Insert seed data into the database using one instance of the
            context = new ApplicationDbContext(_contextOptions);


            context.Users.Add(new Trabajador {
                UserName  = "******", Email = "*****@*****.**", Apellido1 = "Ruiz", Apellido2 = "Villafranca",
                Domicilio = "C/Hellin", Municipio = "Albacete", NIF = "06290424", Nacionalidad = "Española", PaisDeResidencia = "España", Provincia
                          = "Albacete"
            });


            Areas area = new Areas {
                Nombre = "TIC"
            };

            context.Areas.Add(area);

            TiposInversiones tipo = new TiposInversiones {
                Nombre = "Crowdfunding"
            };

            // TiposInversiones tipo2 = new TiposInversiones { Nombre = "TIC" };

            context.TiposInversiones.Add(tipo);
            //     context.TiposInversiones.Add(tipo2);

            context.Proyecto.Add(new Proyecto {
                ProyectoId = 1, FechaExpiracion = new DateTime(2019, 01, 23), Importe = 70000, Interes = null, MinInversion = 50, Nombre = "POCHOLO RULES", NumInversores = 0, Plazo = null, Progreso = 0, RatingId = null
            });
            context.Proyecto.Add(new Proyecto {
                ProyectoId = 2, FechaExpiracion = new DateTime(2019, 01, 23), Importe = 30000, Interes = null, MinInversion = 50, Nombre = "GRE-GYM", NumInversores = 0, Plazo = null, Progreso = 0, RatingId = null
            });
            context.Proyecto.Add(new Proyecto {
                ProyectoId = 3, FechaExpiracion = new DateTime(2019, 01, 23), Importe = 30000, Interes = null, MinInversion = 50, Nombre = "EINSTEIN-MANIA", NumInversores = 0, Plazo = null, Progreso = 0, RatingId = 1
            });



            context.SaveChanges();

            foreach (var proyecto in context.Proyecto.ToList())
            {
                context.ProyectoAreas.Add(new ProyectoAreas {
                    Proyecto = proyecto, Areas = context.Areas.First()
                });
                context.ProyectoTiposInversiones.Add(new ProyectoTiposInversiones {
                    Proyecto = proyecto, TiposInversiones = context.TiposInversiones.First()
                });
            }

            /*
             * Proyecto proyecto1 = new Proyecto { ProyectoId = 4, FechaExpiracion = new DateTime(2019, 01, 23), Importe = 30000, Interes = null, MinInversion = 50, Nombre = "EINSTEIN-MANIA", NumInversores = 0, Plazo = null, Progreso = 0, RatingId = null };
             * context.Proyecto.Add(proyecto1);
             * context.ProyectoTiposInversiones.Add(new ProyectoTiposInversiones { Proyecto = proyecto1, TiposInversiones = tipo2 });
             */
            context.SaveChanges();

            //how to simulate the connection
            System.Security.Principal.GenericIdentity user     = new System.Security.Principal.GenericIdentity("*****@*****.**");
            System.Security.Claims.ClaimsPrincipal    identity = new System.Security.Claims.ClaimsPrincipal(user);
            solicitudContext      = new Microsoft.AspNetCore.Http.DefaultHttpContext();
            solicitudContext.User = identity;
        }
        public Account_SelectPreferenciasForInversor_test()
        {
            _contextOptions = CreateNewContextOptions();
            context         = new ApplicationDbContext(_contextOptions);

            // Insert seed data into the database using one instance of the context

            context.Areas.Add(new Areas {
                AreasId = 1, Nombre = "Sanidad",
            });
            context.Areas.Add(new Areas {
                AreasId = 2, Nombre = "Consultoria"
            });
            context.Areas.Add(new Areas {
                AreasId = 3, Nombre = "Educación"
            });
            context.Areas.Add(new Areas {
                AreasId = 4, Nombre = "Seguridad"
            });
            context.Areas.Add(new Areas {
                AreasId = 5, Nombre = "Construcción"
            });
            context.Areas.Add(new Areas {
                AreasId = 6, Nombre = "Transporte"
            });
            context.Areas.Add(new Areas {
                AreasId = 7, Nombre = "TIC"
            });
            context.Areas.Add(new Areas {
                AreasId = 8, Nombre = "Ingeniería"
            });
            context.Areas.Add(new Areas {
                AreasId = 9, Nombre = "Hogar"
            });
            context.Areas.Add(new Areas {
                AreasId = 10, Nombre = "Alimentación"
            });
            context.Areas.Add(new Areas {
                AreasId = 11, Nombre = "Textil"
            });
            context.Areas.Add(new Areas {
                AreasId = 12, Nombre = "Comercio"
            });
            context.Areas.Add(new Areas {
                AreasId = 13, Nombre = "Hosteleria"
            });
            context.Areas.Add(new Areas {
                AreasId = 14, Nombre = "Administración"
            });
            context.Areas.Add(new Areas {
                AreasId = 15, Nombre = "Automóviles"
            });
            context.Areas.Add(new Areas {
                AreasId = 16, Nombre = "Reparaciones"
            });
            context.Areas.Add(new Areas {
                AreasId = 17, Nombre = "Banca"
            });
            context.Areas.Add(new Areas {
                AreasId = 18, Nombre = "Maquinaría"
            });

            context.TiposInversiones.Add(new TiposInversiones {
                TiposInversionesId = 1, Nombre = "Business Angels"
            });
            context.TiposInversiones.Add(new TiposInversiones {
                TiposInversionesId = 2, Nombre = "Crownfunding"
            });
            context.TiposInversiones.Add(new TiposInversiones {
                TiposInversionesId = 3, Nombre = "Venture Capital"
            });

            context.Rating.Add(new Rating {
                RatingId = 1, Nombre = "A"
            });
            context.Rating.Add(new Rating {
                RatingId = 2, Nombre = "B"
            });
            context.Rating.Add(new Rating {
                RatingId = 3, Nombre = "C"
            });
            context.Rating.Add(new Rating {
                RatingId = 4, Nombre = "D"
            });

            context.SaveChanges();

            System.Security.Principal.GenericIdentity user     = new System.Security.Principal.GenericIdentity("*****@*****.**");
            System.Security.Claims.ClaimsPrincipal    identity = new System.Security.Claims.ClaimsPrincipal(user);
            accountContext      = new Microsoft.AspNetCore.Http.DefaultHttpContext();
            accountContext.User = identity;
        }