<commit_before>﻿using AutoMapper;
using Bossr.Api.Attributes;
using Bossr.Api.Converters;
using Bossr.Api.Factories;
using Bossr.Api.Middleware;
using Bossr.Api.Repositories;
using Bossr.Api.Services;
using Bossr.Lib.Models.Entities;
using Dapper;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System.Text;

namespace Bossr.Api
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddUserSecrets<Startup>()
                .AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton<IDbConnectionFactory>(new SqlConnectionFactory(Configuration["ConnectionString"]));

            services.AddTransient<ITokenResponseFactory, TokenResponseFactory>();
            services.AddTransient<IJwtTokenFactory, JwtTokenFactory>();
            services.AddTransient<IClaimsFetcher, ClaimsFetcher>();

            services.AddTransient<IUserRepository, UserRepository>();
            services.AddTransient<IWorldRepository, WorldRepository>();
            services.AddTransient<ICreatureRepository, CreatureRepository>();
            services.AddTransient<IScrapeRepository, ScrapeRepository>();
            services.AddTransient<IPositionRepository, PositionRepository>();
            services.AddTransient<ICategoryRepository, CategoryRepository>();
            services.AddTransient<ITagRepository, TagRepository>();
            services.AddTransient<IRaidRepository, RaidRepository>();
            services.AddTransient<ISpawnRepository, SpawnRepository>();
            services.AddTransient<IStatisticRepository, StatisticRepository>();

            services.AddTransient<IUserManager, UserManager>();
            services.AddTransient<IHashGenerator, HashGenerator>();
            services.AddTransient<IPasswordValidator, PasswordValidator>();
            services.AddTransient<ISaltGenerator, SaltGenerator>();
            services.AddTransient<ITokenGenerator, TokenGenerator>();
            services.AddTransient<IResponseWriter, ResponseWriter>();

            services.AddMvc(x => { x.Filters.Add(new ModelStateValidationFilterAttribute()); });
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            Mapper.Initialize(x =>
            {
                x.CreateMap<User, UserDto>();

                x.CreateMap<Scrape, ScrapeDto>()
                    .ForMember(dest => dest.Date, opts => opts.MapFrom(y => LocalDateStringConverter.ToString(y.Date)));

                x.CreateMap<ScrapeDto, Scrape>()
                    .ForMember(dest => dest.Date, opts => opts.MapFrom(y => LocalDateStringConverter.ToLocalDate(y.Date)));

                x.CreateMap<Raid, RaidDto>()
                    .ForMember(dest => dest.FrequencyHoursMin, opts => opts.MapFrom(y => DurationHoursConverter.ToHours(y.FrequencyMin)))
                    .ForMember(dest => dest.FrequencyHoursMax, opts => opts.MapFrom(y => DurationHoursConverter.ToHours(y.FrequencyMax)));

                x.CreateMap<RaidDto, Raid>()
                    .ForMember(dest => dest.FrequencyMin, opts => opts.MapFrom(y => DurationHoursConverter.ToDuration(y.FrequencyHoursMin)))
                    .ForMember(dest => dest.FrequencyMax, opts => opts.MapFrom(y => DurationHoursConverter.ToDuration(y.FrequencyHoursMax)));

                x.AllowNullCollections = false;
                x.AllowNullDestinationValues = false;
            });

            SqlMapper.AddTypeHandler(new LocalDateTypeHandler());
            SqlMapper.AddTypeHandler(new DurationTypeHandler());

            var securityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration["SecretKey"]));

            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseMiddleware<TokenProviderMiddleware>(Options.Create(new TokenProviderOptions
            {
                SigningCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256)
            }));

            app.UseJwtBearerAuthentication(new JwtBearerOptions
            {
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
                TokenValidationParameters = new TokenValidationParameters
                {<commit_msg>Added cors for the api<commit_after>﻿using AutoMapper;
using Bossr.Api.Attributes;
using Bossr.Api.Converters;
using Bossr.Api.Factories;
using Bossr.Api.Middleware;
using Bossr.Api.Repositories;
using Bossr.Api.Services;
using Bossr.Lib.Models.Entities;
using Dapper;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System.Text;

namespace Bossr.Api
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddUserSecrets<Startup>()
                .AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton<IDbConnectionFactory>(new SqlConnectionFactory(Configuration["ConnectionString"]));

            services.AddTransient<ITokenResponseFactory, TokenResponseFactory>();
            services.AddTransient<IJwtTokenFactory, JwtTokenFactory>();
            services.AddTransient<IClaimsFetcher, ClaimsFetcher>();

            services.AddTransient<IUserRepository, UserRepository>();
            services.AddTransient<IWorldRepository, WorldRepository>();
            services.AddTransient<ICreatureRepository, CreatureRepository>();
            services.AddTransient<IScrapeRepository, ScrapeRepository>();
            services.AddTransient<IPositionRepository, PositionRepository>();
            services.AddTransient<ICategoryRepository, CategoryRepository>();
            services.AddTransient<ITagRepository, TagRepository>();
            services.AddTransient<IRaidRepository, RaidRepository>();
            services.AddTransient<ISpawnRepository, SpawnRepository>();
            services.AddTransient<IStatisticRepository, StatisticRepository>();

            services.AddTransient<IUserManager, UserManager>();
            services.AddTransient<IHashGenerator, HashGenerator>();
            services.AddTransient<IPasswordValidator, PasswordValidator>();
            services.AddTransient<ISaltGenerator, SaltGenerator>();
            services.AddTransient<ITokenGenerator, TokenGenerator>();
            services.AddTransient<IResponseWriter, ResponseWriter>();

            services.AddMvc(x => { x.Filters.Add(new ModelStateValidationFilterAttribute()); });
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            Mapper.Initialize(x =>
            {
                x.CreateMap<User, UserDto>();

                x.CreateMap<Scrape, ScrapeDto>()
                    .ForMember(dest => dest.Date, opts => opts.MapFrom(y => LocalDateStringConverter.ToString(y.Date)));

                x.CreateMap<ScrapeDto, Scrape>()
                    .ForMember(dest => dest.Date, opts => opts.MapFrom(y => LocalDateStringConverter.ToLocalDate(y.Date)));

                x.CreateMap<Raid, RaidDto>()
                    .ForMember(dest => dest.FrequencyHoursMin, opts => opts.MapFrom(y => DurationHoursConverter.ToHours(y.FrequencyMin)))
                    .ForMember(dest => dest.FrequencyHoursMax, opts => opts.MapFrom(y => DurationHoursConverter.ToHours(y.FrequencyMax)));

                x.CreateMap<RaidDto, Raid>()
                    .ForMember(dest => dest.FrequencyMin, opts => opts.MapFrom(y => DurationHoursConverter.ToDuration(y.FrequencyHoursMin)))
                    .ForMember(dest => dest.FrequencyMax, opts => opts.MapFrom(y => DurationHoursConverter.ToDuration(y.FrequencyHoursMax)));

                x.AllowNullCollections = false;
                x.AllowNullDestinationValues = false;
            });

            SqlMapper.AddTypeHandler(new LocalDateTypeHandler());
            SqlMapper.AddTypeHandler(new DurationTypeHandler());

            var securityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration["SecretKey"]));

            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseCors(x => x.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());

            app.UseMiddleware<TokenProviderMiddleware>(Options.Create(new TokenProviderOptions
            {
                SigningCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256)
            }));

            app.UseJwtBearerAuthentication(new JwtBearerOptions
            {
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
                TokenValidationParameters = new TokenValidationParameters
                {
{'fraction_non_alphanumeric': 0.09906967537608868, 'fraction_numerical': 0.0005938242280285036, 'mean_word_length': 2.9426453374951227, 'pattern_counts': {'":': 0, '<': 57, '<?xml version=': 0, '>': 98, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '801451', 'n_tokens_mistral': 2571, 'n_tokens_neox': 2461, 'n_words': 382}