< Summary

Class:SVETA.Api.Startup
Assembly:SVETA.Api
File(s):/opt/dev/sveta_api_build/SVETA.Api/Startup.cs
Covered lines:0
Uncovered lines:289
Coverable lines:289
Total lines:388
Line coverage:0% (0 of 289)
Covered branches:0
Total branches:28
Branch coverage:0% (0 of 28)

Metrics

MethodLine coverage Branch coverage
get_Configuration()0%100%
.ctor(...)0%100%
ConfigureServices(...)0%0%
Configure(...)0%0%
Stopped()0%100%
Shutdown()0%100%

File(s)

/opt/dev/sveta_api_build/SVETA.Api/Startup.cs

#LineLine coverage
 1using Microsoft.AspNetCore.Authentication.JwtBearer;
 2using Microsoft.AspNetCore.Authorization;
 3using Microsoft.Extensions.Options;
 4using Microsoft.AspNetCore.Builder;
 5using Microsoft.AspNetCore.Hosting;
 6using Microsoft.AspNetCore.Localization;
 7using Microsoft.EntityFrameworkCore;
 8using Microsoft.Extensions.Configuration;
 9using Microsoft.Extensions.DependencyInjection;
 10using Microsoft.Extensions.Hosting;
 11using Microsoft.Extensions.Logging;
 12using Microsoft.IdentityModel.Tokens;
 13using Microsoft.OpenApi.Models;
 14using Newtonsoft.Json;
 15using SVETA.Api.ConfigureOptions;
 16using Serilog;
 17using System.Collections.Generic;
 18using CrmVtbc;
 19using SVETA.Api.Data.DTO;
 20using SVETA.Api.Data.Domain;
 21using SVETA.Api.Helpers;
 22using SVETA.Api.Helpers.Authorize;
 23using SVETA.Api.Services.Implements;
 24using SVETA.Api.Services.Interfaces;
 25using System;
 26using System.Linq;
 27using System.Globalization;
 28using System.IO;
 29using System.Reflection;
 30using System.Text;
 31using System.Threading.Tasks;
 32using IdentityModel;
 33using IdentityServer4.AccessTokenValidation;
 34using IdentityServer4.Models;
 35using Microsoft.AspNetCore.Http.Connections;
 36using Microsoft.AspNetCore.SignalR;
 37using SVETA.Api.Services;
 38using WinSolutions.Sveta.Server.Data.DataModel.Contexts;
 39using WinSolutions.Sveta.Server.Services.Implements;
 40using WinSolutions.Sveta.Server.Services.Interfaces;
 41using Wkhtmltopdf.NetCore;
 42using WinSolutions.Sveta.Common;
 43using WinSolutions.Sveta.Server.Data.DataModel.Entities;
 44using SVETA.Api.CustomMiddleware;
 45using SVETA.Api.Hubs;
 46using Microsoft.Extensions.DependencyInjection.Extensions;
 47using Serilog.Exceptions;
 48using Serilog.Formatting.Elasticsearch;
 49using Serilog.Formatting.Json;
 50using Serilog.Sinks.Elasticsearch;
 51using Serilog.Sinks.File;
 52using SVETA.Api.Services.Interfaces.ImportingExporting;
 53using SVETA.Api.Services.Implements.ImportingExporting;
 54using SVETA.Api.Services.Implements.ImportingExporting.Importers;
 55
 56namespace SVETA.Api
 57{
 58    public class Startup
 59    {
 060        public IConfiguration Configuration { get; }
 061        public Startup(IConfiguration configuration, IWebHostEnvironment env)
 062        {
 63
 64            //Configuration = configuration;
 065            Configuration = new ConfigurationBuilder()
 066                .SetBasePath(Environment.CurrentDirectory)
 067                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
 068                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
 069                .AddEnvironmentVariables()
 070                .Build();
 071            Log.Logger = new LoggerConfiguration()
 072                .Enrich.FromLogContext()
 073                .Enrich.WithExceptionDetails()
 074                .Enrich.WithMachineName()
 075                .WriteTo.ElasticCollector(Configuration["ElasticCollector:url"], Configuration["ElasticCollector:service
 076                .ReadFrom.Configuration(configuration)
 077                    .CreateLogger();
 78            //считываем основной ключ шифрования
 079            SymmetricCrypto.ProtectKey = Configuration.GetValue("CryptoKey", "");
 80
 081        }
 82
 83        // This method gets called by the runtime. Use this method to add services to the container.
 84        public void ConfigureServices(IServiceCollection services)
 085        {
 86            /**********Этот блок не переносить, так как он используется дальше****/
 087            services.AddEntityFrameworkNpgsql().AddDbContext<SvetaDbContext>(opt => opt.UseNpgsql(Configuration.GetConne
 088            //services.AddEntityFrameworkNpgsql().AddDbContext<SvetaDbContext>(opt => opt.UseNpgsql("Host=localhost;Port
 089            //services.AddEntityFrameworkNpgsql().AddDbContext<SvetaDbContext>(opt => opt.UseNpgsql("Host=localhost;Port
 090             b => b.MigrationsAssembly("SVETA.Api")));
 091            services.AddSingleton<IConfigureOptions<ConfigurationsSettings>, ConfigureConfigurationsOptions>();
 92            /*************************/
 93
 94            //Настройки отправки в Telegramm
 095            var _telegramSettings = new TelegramSettings();
 096            Configuration.GetSection("TelegramSettings").Bind(_telegramSettings);
 097            Telegram.ChatId = _telegramSettings.ChatId;
 098            Telegram.Token = _telegramSettings.Token.Encrypted
 099                    ? SymmetricCrypto.DecryptData(Convert.FromBase64String(_telegramSettings.Token.Value))
 0100                    : _telegramSettings.Token.Value;
 101
 102            /***********************Синхронизация с CRM VTB*************************/
 103            // ICrmService можно подключить и как Singltone и как Scoped
 0104            services.AddSingleton<ICrmService, CrmOData>(data =>
 0105            {
 0106                var _crmSettings = new CrmSettings();
 0107                Configuration.GetSection("CrmSettings").Bind(_crmSettings);
 0108                var crm = new CrmOData(
 0109                  new CreatioODataCredentials()
 0110                  {
 0111                      AuthServiceUri = _crmSettings.AuthServiceUri,
 0112                      ODataServiceAddr = _crmSettings.ODataServiceAddr,
 0113                      Username = _crmSettings.Username,
 0114                      Password = _crmSettings.Password.Encrypted ? SymmetricCrypto.DecryptData(Convert.FromBase64String(
 0115                      ForceUseSession = _crmSettings.ForceUseSession,
 0116                      DaDataServiceAddr = _crmSettings.DaDataServiceAddr
 0117                  },
 0118                  new CrmODataOptions()
 0119                  {
 0120                      IsTracingOn = true, // Вывод в консоль всех OData запросов
 0121                      IgnoreResourceNotFoundException = true, // Отключение назойливых уведомлений
 0122                      CollectionNamePattern = "{0}Collection" // Особенность именования коллекций BPMOnline
 0123                  });
 0124                if (crm != null)
 0125                {
 0126                    // Подгружаются метаданные OData для работы с CRM BPMOnline
 0127                    // Эта операция может работать исключительно долго - до 1 минуты
 0128                    // Подгруженные метададнные статически кешируются, при повторном создании
 0129                    // OData-клиента метаданные уже не скачиваются повторно
 0130                    // AsyncContext.Run() из пакета Nitro.AsyncEx позволяет нормально выполнять
 0131                    // асинхронные вызовы в не асинхронном методе
 0132                    //AsyncContext.Run(async () => { await crm.Init(); });
 0133                    System.Threading.Tasks.Task.Run(async () => { await crm.Init(); });
 0134                }
 0135                return crm;
 0136            });
 137            /********************************/
 0138            services.AddCors();
 0139            services.ConfigureOptions<ConfigureCorsOptions>();
 140
 0141            var guestPolicy = new AuthorizationPolicyBuilder()
 0142                .RequireAuthenticatedUser()
 0143                //.RequireClaim("scope", "dataEventRecords")
 0144                //.RequireClaim("", "dataEventRecords")
 0145                .Build();
 146
 0147            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
 0148                .AddIdentityServerAuthentication(options =>
 0149                {
 0150                    var _authSettings = new AuthorizationSettings();
 0151                    Configuration.GetSection("AuthorizationSettings").Bind(_authSettings);
 0152                    options.RequireHttpsMetadata = false;
 0153                    options.TokenRetriever = CustomTokenRetriever.FromHeaderAndQueryString;
 0154                    options.Authority = _authSettings.IdentityUrl;
 0155                    options.ApiName = _authSettings.ApiName;
 0156                    options.ApiSecret = _authSettings.ApiSecret.Encrypted ? SymmetricCrypto.DecryptData(Convert.FromBase
 0157                });
 158
 0159            services.AddAuthorization(options =>
 0160            {
 0161                //     "boss"     claims role=boss
 0162                //          API- /Who/boss
 0163                options.AddPolicy("boss", policyAdmin =>
 0164                {
 0165                    policyAdmin.RequireClaim("role", "boss");
 0166                });
 0167
 0168                //     "owner"     claims role=owner
 0169                options.AddPolicy("owner", policyUser =>
 0170                {
 0171                    policyUser.RequireClaim("role", "owner");
 0172                });
 0173                options.AddPolicy("svetaDDistr", policyUser =>
 0174                {
 0175                    policyUser.RequireClaim("scope", "svetaDDistr");
 0176                });
 0177                //     "policy3"     claims scope=ddistr
 0178                options.AddPolicy("policy3", policyUser =>
 0179                {
 0180                    policyUser.RequireClaim("scope", "ddistr");
 0181                });
 0182            });
 183
 0184            services.Replace(ServiceDescriptor.Transient<IAuthorizationService, CaptureAuthorizationService>());
 185
 0186            services.AddHttpContextAccessor();
 0187            services.AddScoped<IAuthenticationService, AuthenticationService>();
 188
 0189            services.AddScoped<IPhotoService, PhotoService>();
 0190            services.AddScoped<IDownloadGoodsImagesTaskService, DownloadGoodsImagesTaskService>();
 0191            services.AddScoped<IDownloadGoodsImagesWorker, DownloadGoodsImagesWorker>();
 0192            services.AddScoped<IDiskStorageService, DiskStorageService>();
 0193            services.AddScoped<IGoodService, GoodService>();
 0194            services.AddScoped<IDepartmentService, DepartmentService>();
 0195            services.AddScoped<IEventService, EventService>();
 0196            services.AddScoped<IIncidentService, IncidentService>();
 0197            services.AddScoped<IMovementService, MovementService>();
 0198            services.AddScoped<INotificationService, NotificationService>();
 0199            services.AddScoped<INotificationUsersService, NotificationUsersService>();
 0200            services.AddScoped<IPriceTrendService, PriceTrendService>();
 0201            services.AddScoped<IPromoBidService, PromoBidService>();
 0202            services.AddScoped<IPromoOfferService, PromoOfferService>();
 0203            services.AddScoped<IRestService, RestService>();
 0204            services.AddScoped<ISupplyContractService, SupplyContractService>();
 0205            services.AddScoped<IUserService, UserService>();
 0206            services.AddScoped<IGoodSettingService, GoodSettingService>();
 0207            services.AddScoped<IContragentService, ContragentService>();
 0208            services.AddScoped<ICategoryService, CategoryService>();
 0209            services.AddScoped<IBrandService, BrandService>();
 0210            services.AddScoped<ICountryService, CountryService>();
 0211            services.AddScoped<IClusterService, ClusterService>();
 0212            services.AddScoped<IMovementWorker, MovementWorker>();
 0213            services.AddScoped<IPriceWorker, PriceWorker>();
 0214            services.AddScoped<IEmailService, EmailService>();
 0215            services.AddScoped<IBarcodeService, BarcodeService>();
 0216            services.AddScoped<IAddressService, AddressService>();
 0217            services.AddScoped<IDirectoriesService, DirectoriesService>();
 0218            services.AddScoped<ICategoryRatioService, CategoryRatioService>();
 0219            services.AddScoped<IMovementTypeStatusService, MovementTypeStatusService>();
 0220            services.AddScoped<ITaxSystemService, TaxSystemService>();
 0221            services.AddSingleton<IAuthorizationPolicyProvider, MethodPolicyProvider>();
 0222            services.AddScoped<IMethodRolesService, MethodRolesService>();
 0223            services.AddScoped<IAuthorizationHandler, MethodAuthorizationHandler>();
 0224            services.AddScoped<IBankAccountService, BankAccountService>();
 0225            services.AddScoped<IUploadService, UploadService>();
 0226            services.AddScoped<IMovementStatusJournalService, MovementStatusJournalService>();
 0227            services.AddScoped<IShowcaseWorker, ShowcaseWorker>();
 0228            services.AddScoped<IWorkScheduleService, WorkScheduleService>();
 0229            services.AddScoped<IWalletService, WalletService>();
 0230            services.AddScoped<IWalletHttpClient, WalletHttpClient>();
 0231            services.AddScoped<IWalletPaymentService, WalletPaymentService>();
 0232            services.AddScoped<IMovementRouteService, MovementRouteService>();
 0233            services.AddScoped<IMovementStatusRouter, MovementStatusRouter>();
 0234            services.AddScoped<IMovementNotesService, MovementNotesService>();
 0235            services.AddScoped<ICommonUserService, CommonUserService>();
 0236            services.AddScoped<ICommonContragentService, CommonContragentService>();
 0237            services.AddScoped<ICrmSyncWorker, CrmSyncWorker>();
 0238            services.AddScoped<IControlsAccessService, ControlsAccessService>();
 0239            services.AddScoped<IJobService, JobService>();
 0240            services.AddScoped<IDiscountColorService, DiscountColorService>();
 0241            services.AddScoped<INotificationWorker, NotificationWorker>();
 0242            services.AddScoped<IExchangeTokenService, ExchangeTokenService>();
 0243            services.AddScoped<IFeedsWorker, FeedsWorker>();
 0244            services.AddScoped<IEmailWorker, EmailWorker>();
 0245            services.AddScoped<ICategoryWorker, CategoryWorker>();
 0246            services.AddScoped<IGoodWorker, GoodWorker>();
 0247            services.AddScoped<IRestHoldService, RestHoldService>();
 0248            services.AddScoped<IConfigurationService, ConfigurationService>();
 0249            services.AddScoped<IReportService, ReportService>();
 0250            services.AddSingleton<IUserIdProvider, CustomUserIdProvider>();
 0251            services.AddScoped<IUploadWorker, UploadWorker>();
 0252            services.AddScoped<IMovementRouteActionsService, MovementRouteActionsService>();
 0253            services.AddScoped<IGoodLabelService, GoodLabelService>();
 0254            services.AddScoped<IDepartmentWorker, DepartmentWorker>();
 0255            services.AddScoped<IAnonymousMovementService, AnonymousMovementService>();
 0256            services.AddScoped<ITelegramNotificationService, TelegramNotificationService>();
 0257            services.AddScoped<ISmsWorker, SmsWorker>();
 0258            services.AddScoped<ISmsHistoryService, SmsHistoryService>();
 0259            services.AddScoped<IEmailGateHistoryService, EmailGateHistoryService>();
 260
 0261            services.AddScoped<IRecordImporter<RestRecord>, RestImporter>();
 0262            services.AddScoped<IRecordImporter<GoodSettingRecord>, GoodSettingImporter>();
 0263            services.AddScoped<IImportService, ImportService>();
 264
 0265            services.Configure<CommonSettings>(Configuration.GetSection("CommonSettings"));
 0266            services.Configure<ImagesSettings>(Configuration.GetSection("ImageSettings"));
 0267            services.Configure<DaDataSettings>(Configuration.GetSection("DaDataSettings"));
 0268            services.Configure<UploadDownloadSettings>(Configuration.GetSection("UploadDownloadSettings"));
 0269            services.Configure<MigrateSettings>(Configuration.GetSection("MigrateSettings"));
 0270            services.Configure<WalletSettings>(Configuration.GetSection("WalletSettings"));
 0271            services.Configure<AuthorizationSettings>(Configuration.GetSection("AuthorizationSettings"));
 0272            services.Configure<EmailSettings>(Configuration.GetSection("EmailSettings"));
 0273            services.Configure<TelegramSettings>(Configuration.GetSection("TelegramSettings"));
 0274            services.Configure<SmsSettings>(Configuration.GetSection("SmsSettings"));
 275
 0276            services.AddHostedService<DownloadGoodsImagesTaskProcessor>();
 0277            services.AddHostedService<MovementStatusChecker>();
 0278            services.AddHostedService<SendEmailJob>();
 0279            services.AddHostedService<FeedGenerateJob>();
 0280            services.AddHostedService<AnonymousMovementJob>();
 0281            if (Configuration.GetValue<bool>("UseUpdatingLinkImagesJob"))
 0282                services.AddHostedService<UpdatingLinkImagesJob>();
 0283            services.AddWkhtmltopdf();
 284
 0285            services.AddControllers()
 0286                .AddNewtonsoftJson(options =>
 0287                {
 0288                    options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
 0289                    //options.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
 0290                    options.SerializerSettings.DateFormatString = "yyyy'-'MM'-'dd'T'HH':'mm':'ssZ";
 0291                });
 0292            services.AddSignalR(options =>
 0293            {
 0294                options.EnableDetailedErrors = true;
 0295            });
 296
 0297            services.AddSwaggerGen(c =>
 0298            {
 0299                c.SwaggerDoc("v1", new OpenApiInfo { Title = "SVETA API", Version = "v1" });
 0300                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
 0301                {
 0302                    In = ParameterLocation.Header,
 0303                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Bearer {token}\"",
 0304                    Name = "Authorization",
 0305                    BearerFormat = "JWT",
 0306                    Type = SecuritySchemeType.ApiKey,
 0307                    Scheme = "Bearer"
 0308                });
 0309                c.AddSecurityRequirement(new OpenApiSecurityRequirement
 0310                {
 0311                    {
 0312                        new OpenApiSecurityScheme
 0313                        {
 0314                            Reference = new OpenApiReference
 0315                            {
 0316                                Type = ReferenceType.SecurityScheme,
 0317                                Id = "Bearer",
 0318                            }
 0319                        },
 0320                        new string[] {}
 0321                    }
 0322                });
 0323                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
 0324                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
 0325                c.IncludeXmlComments(xmlPath);
 0326                c.EnableAnnotations();
 0327            });
 0328        }
 329
 330        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
 331        public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory, IHostApplicationLifetime appLifetim
 0332        {
 333
 0334            app.UseExceptionHandler("/api/v1/Error");
 0335            app.UseHsts();
 336
 0337            var supportedCultures = new[]
 0338            {
 0339                new CultureInfo("ru-RU"),
 0340                new CultureInfo("ru")
 0341            };
 0342            app.UseRequestLocalization(new RequestLocalizationOptions
 0343            {
 0344                DefaultRequestCulture = new RequestCulture("ru-RU"),
 0345                SupportedCultures = supportedCultures,
 0346                SupportedUICultures = supportedCultures
 0347            });
 0348            if (Configuration.GetValue<bool>("UseSwagger"))
 0349            {
 0350                app.UseSwagger();
 0351                app.UseSwaggerUI(c =>
 0352                {
 0353                    c.SwaggerEndpoint("/swagger/v1/swagger.json", "SVETA API v1");
 0354                });
 0355            }
 0356            app.ConfigureCustomExceptionMiddleware();
 0357            app.UseRouting();
 0358            app.UseCors();
 0359            app.UseAuthentication();
 0360            app.UseAuthorization();
 361
 0362            app.UseEndpoints(endpoints =>
 0363            {
 0364                endpoints.MapHub<SignalHub>("api/hubs/signal");
 0365                endpoints.MapHub<NotificationHub>("api/hubs/notification", options =>
 0366                {
 0367                    options.Transports = HttpTransportType.WebSockets;
 0368                });
 0369                endpoints.MapControllers();
 0370            });
 371
 0372            loggerFactory.AddSerilog();
 373
 0374            appLifetime.ApplicationStopping.Register(Shutdown);
 0375            appLifetime.ApplicationStopped.Register(Stopped);
 0376        }
 377
 378        private void Stopped()
 0379        {
 0380            Console.WriteLine("Application Stopped");
 0381        }
 382
 383        private void Shutdown()
 0384        {
 0385            Console.WriteLine("Shutdown application");
 0386        }
 387    }
 388}