Example #1
0
        public void ConfigureServices(IServiceCollection services)
        {
            using var vaultClient = new VaultClient.VaultClient(new VaultOptions
            {
                BaseUrl = new Uri(EnvironmentVariableHelper.Get("Vault:Endpoint", Configuration)),
                Engine  = Configuration["Vault:Engine"],
                Role    = Configuration["Vault:Role"]
            });
            vaultClient.Login(EnvironmentVariableHelper.Get("Vault:Token", Configuration)).GetAwaiter().GetResult();

            var authorityOptions = vaultClient.Get(Configuration["Authority:Options"]).GetAwaiter().GetResult();

            services.AddHealthChecks()
            .AddDbContextCheck <EdoContext>()
            .AddRedis(EnvironmentVariableHelper.Get("Redis:Endpoint", Configuration));

            services.ConfigureAuthentication(authorityOptions);
            services.AddControllers()
            .AddNewtonsoftJson(opts => opts.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter()))
            .AddJsonOptions(opts => opts.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()))
            .AddFluentValidation(fv =>
            {
                fv.DisableDataAnnotationsValidation         = true;
                fv.ImplicitlyValidateRootCollectionElements = true;
                fv.ImplicitlyValidateChildProperties        = true;
                fv.RegisterValidatorsFromAssembly(Assembly.GetExecutingAssembly());
            });
            services.AddResponseCompression();
            services.ConfigureTracing(Configuration, HostEnvironment);
            services.AddProblemDetailsErrorHandling();
            services.ConfigureApiVersioning();
            services.ConfigureSwagger();
            services.ConfigureCache(Configuration);
            services.ConfigureHttpClients(Configuration, HostEnvironment, vaultClient, authorityOptions["authorityUrl"]);
            services.ConfigureServiceOptions(Configuration, HostEnvironment, vaultClient);
            services.ConfigureUserEventLogging(Configuration, vaultClient);
            services.AddServices(HostEnvironment, Configuration, vaultClient);
            services.AddSignalR().AddStackExchangeRedis(EnvironmentVariableHelper.Get("Redis:Endpoint", Configuration));

            // override services
            services.AddTransient <AccommodationAvailabilitiesService>();
            services.AddTransient <AccommodationService>();
            services.AddTransient <IAgentContextService, AgentContextService>();
            services.AddTransient <BookingCancellationService>();
            services.AddTransient <IBookingEvaluationService, DirectApiBookingEvaluationService>();
            services.AddTransient <INotificationService, EdoDummyNotificationService>();
            services.AddTransient <ValuationService>();
            services.AddTransient <WideAvailabilitySearchService>();
            services.AddTransient <BookingInfoService>();
            services.AddTransient <BookingCreationService>();
            services.AddTransient <IBookingRegistrationService, DirectApiBookingRegistrationService>();
            services.AddTransient <ClientReferenceCodeValidationService>();
            services.ConfigureWideAvailabilityStorage(HostEnvironment, Configuration, vaultClient);
        }
Example #2
0
        private static Dictionary <string, string> GetDbOptions(IConfiguration configuration)
        {
            using var vaultClient = new VaultClient.VaultClient(new VaultOptions
            {
                BaseUrl = new Uri(Environment.GetEnvironmentVariable(configuration["Vault:Endpoint"]), UriKind.Absolute),
                Engine  = configuration["Vault:Engine"],
                Role    = configuration["Vault:Role"]
            });
            vaultClient.Login(Environment.GetEnvironmentVariable(configuration["Vault:Token"])).Wait();

            return(vaultClient.Get(configuration["EDO:Database:Options"]).Result);
        }
Example #3
0
        public void ConfigureServices(IServiceCollection services)
        {
            var serializationSettings = new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver(),
                Formatting       = Formatting.None
            };

            JsonConvert.DefaultSettings = () => serializationSettings;

            using var vaultClient = new VaultClient.VaultClient(new VaultOptions
            {
                BaseUrl = new Uri(EnvironmentVariableHelper.Get("Vault:Endpoint", Configuration)),
                Engine  = Configuration["Vault:Engine"],
                Role    = Configuration["Vault:Role"]
            });
            vaultClient.Login(EnvironmentVariableHelper.Get("Vault:Token", Configuration)).GetAwaiter().GetResult();

            services.AddHealthChecks();

            services.ConfigureServiceOptions(Configuration, vaultClient)
            .AddServices()
            .AddMemoryCache();

            services.AddStaticDataPublicationServices(vaultClient, Configuration, _environment);
            services.AddHostedService <DataUpdateHostedService>();

            services.AddTracing(Configuration, options =>
            {
                options.ServiceName = $"{_environment.ApplicationName}-{_environment.EnvironmentName}";
                options.JaegerHost  = _environment.IsLocal()
                    ? Configuration.GetValue <string>("Jaeger:AgentHost")
                    : Configuration.GetValue <string>(Configuration.GetValue <string>("Jaeger:AgentHost"));
                options.JaegerPort = _environment.IsLocal()
                    ? Configuration.GetValue <int>("Jaeger:AgentPort")
                    : Configuration.GetValue <int>(Configuration.GetValue <string>("Jaeger:AgentPort"));
                options.RedisEndpoint = Configuration.GetValue <string>(Configuration.GetValue <string>("Redis:Endpoint"));
            });
        }
Example #4
0
        public void ConfigureServices(IServiceCollection services)
        {
            var serializationSettings = new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver(),
                Formatting       = Formatting.None
            };

            JsonConvert.DefaultSettings = () => serializationSettings;

            using var vaultClient = new VaultClient.VaultClient(new VaultOptions
            {
                Engine  = Configuration["Vault:Engine"],
                Role    = Configuration["Vault:Role"],
                BaseUrl = new Uri(EnvironmentVariableHelper.Get("Vault:Endpoint", Configuration))
            });

            vaultClient.Login(EnvironmentVariableHelper.Get("Vault:Token", Configuration)).Wait();

            var jobsSettings = vaultClient.Get(Configuration["Identity:JobsOptions"]).GetAwaiter().GetResult();
            var clientSecret = jobsSettings[Configuration["Identity:Secret"]];

            var edoSettings  = vaultClient.Get(Configuration["Edo:EdoOptions"]).GetAwaiter().GetResult();
            var authorityUrl = edoSettings[Configuration["Identity:Authority"]];
            var edoApiUrl    = edoSettings[Configuration["Edo:Api"]];

            services.AddAccessTokenManagement(options =>
            {
                options.User.RefreshBeforeExpiration = TimeSpan.FromMinutes(2);
                options.Client.Clients.Add(HttpClientNames.Identity, new ClientCredentialsTokenRequest
                {
                    Address      = $"{authorityUrl}connect/token",
                    ClientId     = Configuration["Identity:ClientId"],
                    ClientSecret = clientSecret
                });
            });

            services.AddTracing(Configuration, options =>
            {
                options.ServiceName = $"{_environment.ApplicationName}-{_environment.EnvironmentName}";
                options.JaegerHost  = _environment.IsLocal()
                    ? Configuration.GetValue <string>("Jaeger:AgentHost")
                    : Configuration.GetValue <string>(Configuration.GetValue <string>("Jaeger:AgentHost"));
                options.JaegerPort = _environment.IsLocal()
                    ? Configuration.GetValue <int>("Jaeger:AgentPort")
                    : Configuration.GetValue <int>(Configuration.GetValue <string>("Jaeger:AgentPort"));
            });

            services
            .Configure <CompletionOptions>(Configuration.GetSection("Completion"))
            .Configure <ChargeOptions>(Configuration.GetSection("Charge"))
            .Configure <CancellationOptions>(Configuration.GetSection("Cancellation"))
            .Configure <NotificationOptions>(Configuration.GetSection("Notification"))
            .Configure <MarkupBonusMaterializationOptions>(Configuration.GetSection("MarkupBonusMaterialization"))
            .Configure <RefundOptions>(Configuration.GetSection("Refund"));

            services.AddHttpClient(HttpClientNames.EdoApi, client =>
            {
                client.BaseAddress = new Uri(edoApiUrl);
                client.Timeout     = TimeSpan.FromHours(1);
            })
            .AddPolicyHandler((sp, _) => Policy(sp))
            .AddClientAccessTokenHandler(HttpClientNames.Identity);

            services.AddHealthChecks();

            services.AddHostedService <UpdaterService>();
        }
Example #5
0
        public void ConfigureServices(IServiceCollection services)
        {
            var serializationSettings = new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver(),
                Formatting       = Formatting.None
            };

            JsonConvert.DefaultSettings = () => serializationSettings;

            using var vaultClient = new VaultClient.VaultClient(new VaultOptions
            {
                BaseUrl = new Uri(EnvironmentVariableHelper.Get("Vault:Endpoint", Configuration)),
                Engine  = Configuration["Vault:Engine"],
                Role    = Configuration["Vault:Role"]
            });
            vaultClient.Login(EnvironmentVariableHelper.Get("Vault:Token", Configuration)).GetAwaiter().GetResult();

            services.AddResponseCompression()
            .AddCors()
            .AddLocalization()
            .AddMemoryCache()
            .AddMemoryFlow()
            .AddStackExchangeRedisCache(options => { options.Configuration = EnvironmentVariableHelper.Get("Redis:Endpoint", Configuration); })
            .AddDoubleFlow()
            .AddCacheFlowJsonSerialization()
            .AddTracing(HostingEnvironment, Configuration);

            services.ConfigureServiceOptions(Configuration, HostingEnvironment, vaultClient)
            .ConfigureHttpClients(Configuration, HostingEnvironment, vaultClient)
            .ConfigureAuthentication(Configuration, HostingEnvironment, vaultClient)
            .AddServices();

            services.AddHealthChecks()
            .AddDbContextCheck <EdoContext>()
            .AddRedis(EnvironmentVariableHelper.Get("Redis:Endpoint", Configuration))
            .AddCheck <ControllerResolveHealthCheck>(nameof(ControllerResolveHealthCheck));

            services.AddApiVersioning(options =>
            {
                options.AssumeDefaultVersionWhenUnspecified = false;
                options.DefaultApiVersion = new ApiVersion(1, 0);
                options.ReportApiVersions = true;
            });

            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1.0", new OpenApiInfo {
                    Title = "HappyTravel.com Edo API", Version = "v1.0"
                });

                var xmlCommentsFileName = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlCommentsFilePath = Path.Combine(AppContext.BaseDirectory, xmlCommentsFileName);
                options.IncludeXmlComments(xmlCommentsFilePath);
                options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name        = "Authorization",
                    In          = ParameterLocation.Header,
                    Type        = SecuritySchemeType.ApiKey
                });
                options.AddSecurityRequirement(new OpenApiSecurityRequirement()
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id   = "Bearer"
                            },
                            Scheme = "oauth2",
                            Name   = "Bearer",
                            In     = ParameterLocation.Header,
                        },
                        Array.Empty <string>()
                    }
                });
            });
            services.AddSwaggerGenNewtonsoftSupport();

            services.AddOData();

            services.AddMvcCore(options =>
            {
                options.Conventions.Insert(0, new LocalizationConvention());
                options.Conventions.Add(new AuthorizeControllerModelConvention());
                options.Filters.Add(new MiddlewareFilterAttribute(typeof(LocalizationPipelineFilter)));
                options.Filters.Add(typeof(ModelValidationFilter));

                AddODataMediaTypes(options);
            })
            .AddAuthorization()
            .AddControllersAsServices()
            .AddMvcOptions(m => m.EnableEndpointRouting = true)
            .AddFormatterMappings()
            .AddNewtonsoftJson(options => options.SerializerSettings.Converters.Add(new StringEnumConverter()))
            .AddApiExplorer()
            .AddCacheTagHelper()
            .AddDataAnnotations();
        }
Example #6
0
        public void ConfigureServices(IServiceCollection services)
        {
            var serializationSettings = new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver(),
                Formatting       = Formatting.None
            };

            JsonConvert.DefaultSettings = () => serializationSettings;

            using var vaultClient = new VaultClient.VaultClient(new VaultOptions
            {
                BaseUrl = new Uri(EnvironmentVariableHelper.Get("Vault:Endpoint", Configuration)),
                Engine  = Configuration["Vault:Engine"],
                Role    = Configuration["Vault:Role"]
            });
            vaultClient.Login(EnvironmentVariableHelper.Get("Vault:Token", Configuration)).GetAwaiter().GetResult();

            services.AddMemoryCache()
            .AddStackExchangeRedisCache(options =>
            {
                options.Configuration = EnvironmentVariableHelper.Get("Redis:Endpoint", Configuration);
            })
            .AddDoubleFlow();

            services.ConfigureServiceOptions(Configuration, vaultClient)
            .AddServices();

            services.AddHealthChecks()
            .AddCheck <ControllerResolveHealthCheck>(nameof(ControllerResolveHealthCheck))
            .AddRedis(EnvironmentVariableHelper.Get("Redis:Endpoint", Configuration));

            services.AddResponseCompression()
            .AddHttpContextAccessor()
            .AddCors()
            .AddLocalization()
            .AddMemoryCache()
            .AddTracing(Configuration, options =>
            {
                options.ServiceName = $"{_environment.ApplicationName}-{_environment.EnvironmentName}";
                options.JaegerHost  = _environment.IsLocal()
                        ? Configuration.GetValue <string>("Jaeger:AgentHost")
                        : Configuration.GetValue <string>(Configuration.GetValue <string>("Jaeger:AgentHost"));
                options.JaegerPort = _environment.IsLocal()
                        ? Configuration.GetValue <int>("Jaeger:AgentPort")
                        : Configuration.GetValue <int>(Configuration.GetValue <string>("Jaeger:AgentPort"));
                options.RedisEndpoint = Configuration.GetValue <string>(Configuration.GetValue <string>("Redis:Endpoint"));
            });

            services.AddApiVersioning(options =>
            {
                options.AssumeDefaultVersionWhenUnspecified = false;
                options.DefaultApiVersion = new ApiVersion(1, 0);
                options.ReportApiVersions = true;
            });

            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1.0",
                                   new OpenApiInfo {
                    Title = "HappyTravel.com Property Management System API", Version = "v1.0"
                });

                var apiXmlCommentsFilePath = Path.Combine(AppContext.BaseDirectory,
                                                          $"{Assembly.GetExecutingAssembly().GetName().Name}.xml");
                options.IncludeXmlComments(apiXmlCommentsFilePath);

                foreach (var assembly in Assembly.GetExecutingAssembly().GetReferencedAssemblies())
                {
                    var path = Path.Combine(AppContext.BaseDirectory, $"{assembly.Name}.xml");
                    if (File.Exists(path))
                    {
                        options.IncludeXmlComments(path);
                    }
                }

                options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name        = "Authorization",
                    In          = ParameterLocation.Header,
                    Type        = SecuritySchemeType.ApiKey
                });
                options.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id   = "Bearer"
                            },
                            Scheme = "oauth2",
                            Name   = "Bearer",
                            In     = ParameterLocation.Header,
                        },
                        Array.Empty <string>()
                    }
                });
                options.CustomSchemaIds(t => t.ToString());
            });
            //  services.AddSwaggerGenNewtonsoftSupport();

            services.AddMvcCore()
            .AddFormatterMappings()
            .AddNewtonsoftJson()
            .AddApiExplorer()
            .AddCacheTagHelper()
            .AddControllersAsServices()
            .AddAuthorization(options =>
            {
                options.FallbackPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
                options.AddPolicy("CanEdit", policy =>
                {
                    policy.RequireClaim("scope", "mapper.edit");
                });
            });

            services.AddTransient <ILocationMappingInfoService, LocationMappingInfoService>();
            services.AddTransient <ILocationMappingFactory, LocationMappingFactory>();
            services.AddTransient <CountryHtIdMappingService>();
            services.AddStaticDataPublicationServices(vaultClient, Configuration, _environment);
            services.AddProblemDetailsErrorHandling();
        }
Example #7
0
        public void ConfigureServices(IServiceCollection services)
        {
            var serializationSettings = new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver(),
                Formatting       = Formatting.None
            };

            JsonConvert.DefaultSettings = () => serializationSettings;

            using var vaultClient = new VaultClient.VaultClient(new VaultOptions
            {
                BaseUrl = new Uri(EnvironmentVariableHelper.Get("Vault:Endpoint", Configuration)),
                Engine  = Configuration["Vault:Engine"],
                Role    = Configuration["Vault:Role"]
            });
            vaultClient.Login(EnvironmentVariableHelper.Get("Vault:Token", Configuration)).GetAwaiter().GetResult();

            services.AddResponseCompression()
            .AddCors()
            .AddLocalization()
            .AddMemoryCache()
            .AddMemoryFlow()
            .AddStackExchangeRedisCache(options =>
            {
                var host = EnvironmentVariableHelper.Get("Redis:Endpoint", Configuration);
                options.ConfigurationOptions = new ConfigurationOptions
                {
                    EndPoints    = { new DnsEndPoint(host, 6379) },
                    AsyncTimeout = 15000,     // set to 15 seconds before we stop storing large objects in Redis
                };
            })
            .AddDoubleFlow()
            .AddCacheFlowJsonSerialization()
            .AddTracing(Configuration, options =>
            {
                options.ServiceName = $"{HostingEnvironment.ApplicationName}-{HostingEnvironment.EnvironmentName}";
                options.JaegerHost  = HostingEnvironment.IsLocal()
                        ? Configuration.GetValue <string>("Jaeger:AgentHost")
                        : Configuration.GetValue <string>(Configuration.GetValue <string>("Jaeger:AgentHost"));
                options.JaegerPort = HostingEnvironment.IsLocal()
                        ? Configuration.GetValue <int>("Jaeger:AgentPort")
                        : Configuration.GetValue <int>(Configuration.GetValue <string>("Jaeger:AgentPort"));
                options.RedisEndpoint = Configuration.GetValue <string>(Configuration.GetValue <string>("Redis:Endpoint"));
            })
            .AddUserEventLogging(Configuration, vaultClient);

            var(apiName, authorityUrl) = GetApiNameAndAuthority(Configuration, HostingEnvironment, vaultClient);

            services.ConfigureServiceOptions(Configuration, HostingEnvironment, vaultClient)
            .ConfigureHttpClients(Configuration, HostingEnvironment, vaultClient, authorityUrl)
            .ConfigureAuthentication(Configuration, HostingEnvironment, apiName, authorityUrl)
            .AddServices(HostingEnvironment, Configuration, vaultClient);

            services.AddHealthChecks()
            .AddDbContextCheck <EdoContext>()
            .AddRedis(EnvironmentVariableHelper.Get("Redis:Endpoint", Configuration))
            .AddCheck <ControllerResolveHealthCheck>(nameof(ControllerResolveHealthCheck));

            services.AddProblemDetailsErrorHandling();

            services.AddApiVersioning(options =>
            {
                options.AssumeDefaultVersionWhenUnspecified = false;
                options.DefaultApiVersion = new ApiVersion(1, 0);
                options.ReportApiVersions = true;
            });

            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("agent", new OpenApiInfo {
                    Title = "Happytravel.com Edo API for an agent app", Version = "v1.0"
                });
                options.SwaggerDoc("admin", new OpenApiInfo {
                    Title = "Happytravel.com Edo API for an admin app", Version = "v1.0"
                });
                options.SwaggerDoc("property-owner", new OpenApiInfo {
                    Title = "Happytravel.com Edo API for property owners", Version = "v1.0"
                });
                options.SwaggerDoc("service", new OpenApiInfo {
                    Title = "Happytravel.com service Edo API", Version = "v1.0"
                });

                var xmlCommentsFileName = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlCommentsFilePath = Path.Combine(AppContext.BaseDirectory, xmlCommentsFileName);
                options.IncludeXmlComments(xmlCommentsFilePath);
                options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name        = "Authorization",
                    In          = ParameterLocation.Header,
                    Type        = SecuritySchemeType.ApiKey
                });
                options.AddSecurityRequirement(new OpenApiSecurityRequirement()
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id   = "Bearer"
                            },
                            Scheme = "oauth2",
                            Name   = "Bearer",
                            In     = ParameterLocation.Header,
                        },
                        Array.Empty <string>()
                    }
                });
                // Use fully qualified object names
                options.CustomSchemaIds(x => x.FullName);
            });
            services.AddSwaggerGenNewtonsoftSupport();

            services.AddNotificationCenter(EnvironmentVariableHelper.Get("Redis:Endpoint", Configuration));

            services.AddMvcCore(options =>
            {
                options.Conventions.Insert(0, new LocalizationConvention());
                options.Conventions.Add(new AuthorizeControllerModelConvention());
                options.Conventions.Add(new ApiExplorerGroupPerVersionConvention());
                options.Filters.Add(new MiddlewareFilterAttribute(typeof(LocalizationPipelineFilter)));
                options.Filters.Add(typeof(ModelValidationFilter));

                AddODataMediaTypes(options);
            })
            .AddAuthorization()
            .AddControllersAsServices()
            .AddMvcOptions(m => m.EnableEndpointRouting = true)
            .AddFormatterMappings()
            .AddNewtonsoftJson(options => options.SerializerSettings.Converters.Add(new StringEnumConverter()))
            .AddApiExplorer()
            .AddCacheTagHelper()
            .AddDataAnnotations()
            .AddOData(opt => opt.Filter().Select().OrderBy().SetMaxTop(100));
        }