Пример #1
0
        public ReviewTest()
        {
            var mapperConfig = new MapperConfiguration(cfg => cfg.AddMaps(ProfileRegistration.GetProfiles()));

            _mapper          = mapperConfig.CreateMapper();
            _reviewGenerator = new ReviewGenerator(new GameGenerator());
            _fakeRepository  = new Mock <IReviewRepository>();
            _fakeUnitOfWork  = new Mock <IUnitOfWork>();
            _fakeUnitOfWork.Setup(m => m.ReviewRepository).Returns(_fakeRepository.Object);
            _controller = new ReviewController(_fakeUnitOfWork.Object, _mapper);
        }
Пример #2
0
        public GameTest()
        {
            var mapperConfig = new MapperConfiguration(cfg => cfg.AddMaps(ProfileRegistration.GetProfiles()));

            _mapper         = mapperConfig.CreateMapper();
            _gameGenerator  = new GameGenerator();
            _mockRepository = new Mock <IGameRepository>();
            _mockUnitOfWork = new Mock <IUnitOfWork>();
            _mockUnitOfWork.Setup(m => m.GameRepository).Returns(_mockRepository.Object);
            _controller = new GameController(_mockUnitOfWork.Object, _mapper);
        }
Пример #3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddHealthChecks();

            // TODO: Permitir que a implementação seja escolhida por Settings
            services.AddGenerators();
            services.AddMemoryPersistence();
            services.AddAutoMapper(ProfileRegistration.GetProfiles());

            services.AddMvc();

            GitHubSettings = _configuration.GetSection(nameof(GitHubSettings)).Get <GitHubSettings>();   // TODO: Criar uma extension para facilitar a vida

            if (GitHubSettings == null)
            {
                throw new ArgumentNullException(nameof(GitHubSettings), "GitHub OAuth settings were not found. Did you forget to edit your appSettings.json?");
            }

            services
            .AddAuthentication(opt =>
            {
                opt.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                opt.DefaultSignInScheme       = CookieAuthenticationDefaults.AuthenticationScheme;
                opt.DefaultChallengeScheme    = "GitHub";
            })
            .AddCookie()
            .AddGitHub("GitHub", opt =>
            {
                opt.ClientId     = GitHubSettings.ClientId;
                opt.ClientSecret = GitHubSettings.ClientSecret;
                opt.CallbackPath = new PathString(GitHubSettings.CallbackPath);
                opt.SaveTokens   = true;

                opt.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "id");
                opt.ClaimActions.MapJsonKey(ClaimTypes.Name, "name");
                opt.ClaimActions.MapJsonKey("urn:github:login", "login");
                opt.ClaimActions.MapJsonKey("urn:github:url", "html_url");
                opt.ClaimActions.MapJsonKey("urn:github:avatar", "avatar_url");

                opt.Events = new OAuthEvents
                {
                    OnCreatingTicket = async context =>
                    {
                        var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint);
                        request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken);

                        var response = await context.Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, context.HttpContext.RequestAborted);
                        response.EnsureSuccessStatusCode();

                        var user = JObject.Parse(await response.Content.ReadAsStringAsync());

                        context.RunClaimActions(user);
                    }
                };
            });

            // Armazenando as configurações do GitHub para uso Futuro
            services.Configure <GitHubSettings>(_configuration.GetSection(nameof(GitHubSettings)));

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Version     = "v1",
                    Title       = "NetCore Playground API",
                    Description = "API para testes com .NET Core 2.2",
                    Contact     = new Contact {
                        Name = "Rodolpho Alves", Url = @"https://github.com/rodolphocastro", Email = "*****@*****.**"
                    }                                                                                                                                 // TODO: Algum dia colocar um e-mail válido :shrug:
                });

                c.AddSecurityDefinition("GitHub", new OAuth2Scheme
                {
                    Type             = "oauth2",
                    Flow             = "accessCode",
                    AuthorizationUrl = "https://github.com/login/oauth/authorize",
                    TokenUrl         = "https://github.com/login/oauth/access_token"
                });

                c.OperationFilter <SecurityRequirementsOperationFilter>();
            });
        }
Пример #4
0
        public ReviewViewModelsTest()
        {
            var mapperConfig = new MapperConfiguration(cfg => cfg.AddMaps(ProfileRegistration.GetProfiles()));

            _mapper = mapperConfig.CreateMapper();
        }
Пример #5
0
 private static void App_Start()
 {
     ProfileRegistration.RegisterMapping();
     _context = new DesignTimeDbContextFactory().CreateDbContext(null);
     //_studentService = new StudentService(_context);
 }
Пример #6
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <FrameworkContext>(options =>
                                                     options.UseSqlServer("Server=localhost;Database=NetCoreFramework;Trusted_Connection=True;MultipleActiveResultSets=true").EnableSensitiveDataLogging(true));

            services.AddScoped <IStudentService, StudentService>();

            services.AddMvc(/*options=> options.Filters.Add(typeof(ValidateModelStateAttribute))*/).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);


            services.AddCors();

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }
                                       ).AddJwtBearer(options =>
            {
                options.Events = new JwtBearerEvents()
                {
                    OnChallenge = context =>
                    {
                        // Skip the default logic.
                        context.HandleResponse();

                        var payload = new JObject
                        {
                            ["error"]      = "Needed valid token to authorize!",
                            ["statusCode"] = 401
                        };
                        context.Response.StatusCode = 401;
                        return(context.Response.Body.WriteAsync(Encoding.Default.GetBytes(payload.ToString())).AsTask());
                    }
                };

                options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("Jwt Key Jwt Key Jwt Key Jwt Key Jwt Key")),
                    ValidateIssuer           = false,
                    ValidateAudience         = false,
                    ValidateLifetime         = true,
                    ClockSkew = TimeSpan.Zero
                };
            });


            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1doc", new Info {
                    Title = "NetCoreFramework.Presentation.WebAPI", Version = "1.0"
                });

                // Swagger 2.+ support
                var security = new Dictionary <string, IEnumerable <string> >
                {
                    { "Bearer", new string[] { } },
                };

                c.AddSecurityDefinition("Bearer", new ApiKeyScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name        = "Authorization",
                    In          = "header",
                    Type        = "apiKey"
                });
                c.AddSecurityRequirement(security);
            });


            services.AddRabbitMq(Configuration);

            ProfileRegistration.RegisterMapping();
        }