Ejemplo n.º 1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers(mvcOptions => mvcOptions.EnableEndpointRouting = false);

            //A string az appsettings.Development.json fájlban van
            services.AddDbContextPool <ConcertManagerContext>(o =>
                                                                                                                               //o.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"]));    //LocalDB
                                                              o.UseMySql(Configuration["ConnectionStrings:MySqlConnString"])); //MySQL

            //A Startup osztályunk szerelvényében keresi a profilt a mapperhez
            services.AddAutoMapper(typeof(Startup));

            //Megadjuk az elemeink kiszolgálóinak az interface-ét, és ezek az implementálását
            services.AddTransient <IBandService, BandService>();
            services.AddTransient <IVenueService, VenueService>();
            services.AddTransient <IConcertService, ConcertService>();

            //Hiba kezelése
            services.AddProblemDetails(options =>
            {
                options.IncludeExceptionDetails = (context, exception) => false;
                options.Map <EntityNotFoundException>((context, exception) =>
                {
                    var pd   = StatusCodeProblemDetails.Create(StatusCodes.Status404NotFound);
                    pd.Title = exception.Message;
                    return(pd);
                });
            });

            services.AddOData();
        }
Ejemplo n.º 2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddProblemDetails(options =>
            {
                options.IncludeExceptionDetails = (ctx, ex) => false;
                options.Map <AuthorizationException>(
                    (ctx, ex) =>
                {
                    var pd   = StatusCodeProblemDetails.Create(StatusCodes.Status401Unauthorized);
                    pd.Title = ex.Message;
                    return(pd);
                }
                    );
            });
            services.Configure <FileStorageSettings>(
                Configuration.GetSection(nameof(FileStorageSettings)));
            services.AddSingleton <IFileStorageSettings>(sp =>
            {
                var logger = sp.GetRequiredService <ILogger <Startup> >();
                var fileStorageSettings = sp.GetRequiredService <IOptions <FileStorageSettings> >().Value;
                logger.LogInformation($"FileStorageSettings.DiskStorePath: {fileStorageSettings.DiskStorePath}");
                return(fileStorageSettings);
            });
            services.Configure <KestrelServerOptions>(options =>
            {
                options.Limits.MaxRequestBodySize = int.MaxValue; // if not set default value is: 30 MB
            });

            services.AddMassTransit(x =>
            {
                var config = Configuration.GetSection(nameof(MessageQueueSettings)).Get <MessageQueueSettings>();
                x.AddBus(context =>
                         Bus.Factory.CreateUsingRabbitMq(cfg =>
                {
                    cfg.Host(new Uri($"rabbitmq://{config.Hostname}:/"),
                             hostConfig =>
                    {
                        hostConfig.Username(config.Username);
                        hostConfig.Password(config.Password);
                    });
                })
                         );
                EndpointConvention.Map <IVideoUploadedEvent>(new Uri($"rabbitmq://{config.Hostname}:/VideoUploaded"));
                EndpointConvention.Map <IVideoUploadedForCatalogEvent>(new Uri($"rabbitmq://{config.Hostname}:/VideoUploadedForCatalog"));
            });

            services.AddTransient <ITusService, TusService>();
            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "UploadService", Version = "v1"
                });
            });
        }
Ejemplo n.º 3
0
 private static void MapExceptions(ProblemDetailsOptions opt)
 {
     opt.Map <ProxyErrorException>((ctx, ex) =>
     {
         var details = new StatusCodeProblemDetails(ctx.Response.StatusCode)
         {
             Detail = ex.Message
         };
         details.Extensions["errorType"]        = ex.ErrorType;
         details.Extensions["exceptionMessage"] = ex.InnerException?.Message ?? string.Empty;
         return(details);
     });
     opt.MapToStatusCode <NotFoundException>(StatusCodes.Status404NotFound);
 }
Ejemplo n.º 4
0
        // This will map Exceptions to the corresponding Conflict status code.
        private void _configureExceptionProblemDetails(ProblemDetailsOptions options)
        {
            options.MapToStatusCode <EntityNotFoundException>(StatusCodes.Status404NotFound);

            options.MapToStatusCode <NotImplementedException>(StatusCodes.Status501NotImplemented);

            options.MapToStatusCode <HttpRequestException>(StatusCodes.Status503ServiceUnavailable);

            options.MapToStatusCode <UnauthorizedAccessException>(StatusCodes.Status403Forbidden);

            options.MapToStatusCode <EntityTagMismatchException>(StatusCodes.Status412PreconditionFailed);

            options.MapToStatusCode <OptimisticConcurrencyException>(StatusCodes.Status409Conflict);

            options.Map <SqlException>(ex => SqlExceptionHandler.IsPrimaryKeyOrUniqueKeyViolation(ex)
                ? StatusCodeProblemDetails.Create(StatusCodes.Status409Conflict)
                : StatusCodeProblemDetails.Create(StatusCodes.Status500InternalServerError));

            options.Map <FluentValidation.ValidationException>(ex => new FluentValidationProblemDetails(ex, StatusCodes.Status400BadRequest));

            options.Map <BusinessRuleViolationException>(ex => new BusinessRuleProblemDetails(ex.BusinessRuleViolation));
        }
Ejemplo n.º 5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddProblemDetails(options =>
            {
                options.IncludeExceptionDetails = (ctx, ex) => false;
                options.Map <LoginFailedException>(
                    (ctx, ex) =>
                {
                    var pd   = StatusCodeProblemDetails.Create(StatusCodes.Status401Unauthorized);
                    pd.Title = ex.Message;
                    return(pd);
                }
                    );
                options.Map <AuthorizationException>(
                    (ctx, ex) =>
                {
                    var pd   = StatusCodeProblemDetails.Create(StatusCodes.Status401Unauthorized);
                    pd.Title = ex.Message;
                    return(pd);
                }
                    );
                options.Map <BadRequestException>(
                    (ctx, ex) =>
                {
                    var pd   = StatusCodeProblemDetails.Create(StatusCodes.Status400BadRequest);
                    pd.Title = ex.Message;
                    return(pd);
                }
                    );
            });
            services.AddDbContext <CaffStoreDbContext>(o =>
                                                       o.UseSqlServer(Configuration.GetConnectionString("LocalConnection")));

            var tokenSettings = Configuration.GetSection(nameof(TokenSettings));

            services.Configure <TokenSettings>(
                tokenSettings);
            services.AddSingleton <ITokenSettings>(sp =>
                                                   sp.GetRequiredService <IOptions <TokenSettings> >().Value);

            var fileSettings = Configuration.GetSection(nameof(FileSettings));

            services.Configure <FileSettings>(
                fileSettings);
            services.AddSingleton <IFileSettings>(sp =>
                                                  sp.GetRequiredService <IOptions <FileSettings> >().Value);

            var caffparserSettings = Configuration.GetSection(nameof(CAFFparserSettings));

            services.Configure <CAFFparserSettings>(
                caffparserSettings);
            services.AddSingleton <ICAFFparserSettings>(sp =>
                                                        sp.GetRequiredService <IOptions <CAFFparserSettings> >().Value);


            services.AddIdentity <User, Role>(o =>
            {
                o.Password.RequireDigit           = true;
                o.Password.RequireLowercase       = true;
                o.Password.RequireUppercase       = true;
                o.Password.RequireNonAlphanumeric = true;
                o.Password.RequiredLength         = 7;
            })
            .AddEntityFrameworkStores <CaffStoreDbContext>()
            .AddDefaultTokenProviders();

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.SaveToken                 = true;
                options.RequireHttpsMetadata      = false;
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateLifetime         = true,
                    ValidIssuer              = tokenSettings["Issuer"],
                    ValidAudience            = tokenSettings["Audience"],
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenSettings["Secret"])),
                    ClockSkew = TimeSpan.Zero
                };
                options.Events = new JwtBearerEvents()
                {
                    OnTokenValidated = async context =>
                    {
                        var userService = context.HttpContext.RequestServices.GetRequiredService <IUserService>();
                        try
                        {
                            var userid = context.Principal.UserId();
                            var user   = await userService.GetByIdAsync(Convert.ToInt64(userid));
                            if (context.Principal.IsAdmin() && !user.IsAdmin())
                            {
                                context.Fail("invaild token");
                            }
                        } catch
                        {
                            context.Fail("invaild token");
                        }
                    },
                };
            });

            services.AddTransient <ITokenService, TokenService>();
            services.AddTransient <IUserService, UserService>();
            services.AddTransient <ICommentService, CommentService>();
            services.AddTransient <ICaffService, CaffService>();

            services.AddAutoMapper(typeof(Startup));

            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "CaffStoreServer webAPI", Version = "v1"
                });
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description = @"JWT Authorization header using the Bearer scheme. \r\n\r\n 
                      Enter 'Bearer' [space] and then your token in the text input below.
                      \r\n\r\nExample: 'Bearer 12345abcdef'",
                    Name        = "Authorization",
                    In          = ParameterLocation.Header,
                    Type        = SecuritySchemeType.ApiKey,
                    Scheme      = "Bearer"
                });
                c.AddSecurityRequirement(new OpenApiSecurityRequirement()
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id   = "Bearer"
                            },
                            Scheme = "oauth2",
                            Name   = "Bearer",
                            In     = ParameterLocation.Header,
                        },
                        new List <string>()
                    }
                });
            });

            services.AddMvc();
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Ez a metódus futási időben hívódik meg. A szolgáltatások beregisztrálására használatos.
        /// </summary>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(
                                                             Configuration.GetConnectionString("DefaultConnection")));

            services.AddControllers();

            services.AddAuthentication("Bearer")
            .AddJwtBearer("Bearer", options =>
            {
                options.Audience  = Configuration.GetSection("IRestaurantWebAPI:Audience").Value;
                options.Authority = Configuration.GetSection("IRestaurantWebAPI:Authority").Value;
            });

            //Scope és szerepkör szerinti policy létrehozása.
            services.AddAuthorization(options =>
            {
                options.AddPolicy(IRESTAURANT_API_SCOPE, policy => {
                    policy.RequireClaim("scope", Configuration.GetSection("IRestaurantWebAPI:Scope").Value);
                });
                options.AddPolicy(UserRoles.Restaurant, policy =>
                                  policy.RequireClaim(ClaimTypes.Role, UserRoles.Restaurant
                                                      ));
                options.AddPolicy(UserRoles.Guest, policy =>
                                  policy.RequireClaim(ClaimTypes.Role, UserRoles.Guest
                                                      ));
            });

            services.AddCors(options =>
            {
                options.AddPolicy(DEFAULT_CORS_POLICY, policy =>
                {
                    policy.WithOrigins(Configuration.GetSection("IRestaurantWebAPI:AllowedCorsOrigins").Get <string[]>())
                    .AllowAnyHeader()
                    .AllowAnyMethod();
                });
            });

            // A Swagger szolgáltatás beregisztrálása a Swagger middleware használatához OAuth2 authentikációval.
            services.AddOpenApiDocument(c =>
            {
                c.Version     = "v1";
                c.Title       = "Restaurant API";
                c.Description = "Egy étterem kezelő ASP.NET Core webalkalmazás REST API leírása.";
                c.AddSecurity("OAuth2", Configuration.GetSection("Swagger:OpenApiSecurityScheme").Get <NSwag.OpenApiSecurityScheme>());
                c.OperationProcessors.Add(new AspNetCoreOperationSecurityScopeProcessor("OAuth2"));
            });

            //ProblemDetails Middleware-hez szükséges szolgáltatások hozzáadása, és konfigurálása.
            services.AddProblemDetails(options => {
                // Ez 404 Not Found státusz kódra cseréli EntityNotFoundException-t.
                options.Map <EntityNotFoundException>((context, exception) => {
                    var problemDetails   = StatusCodeProblemDetails.Create(StatusCodes.Status404NotFound);
                    problemDetails.Title = exception.Message;
                    return(problemDetails);
                });
                // Ez 400 Bad Request státusz kódra cseréli EntityAlreadyExistsException-t.
                options.Map <EntityAlreadyExistsException>((context, exception) => {
                    var problemDetails   = StatusCodeProblemDetails.Create(StatusCodes.Status400BadRequest);
                    problemDetails.Title = exception.Message;
                    return(problemDetails);
                });
            });

            //Az adatbázist inicializáló adatokat tartalmazó osztály beregisztrálása.
            services.AddScoped <IApplicationSeedData, ApplicationSeedData>();

            //A HttpContext-hez való hozzáférés miatt(pl.: a jelenlegi felhasználó lekérése).
            services.AddHttpContextAccessor();

            //A DAL rétegbeli repository osztályok beregisztrálása.
            services.AddTransient <IRestaurantRepository, RestaurantRepository>();
            services.AddTransient <IFoodRepository, FoodRepository>();
            services.AddTransient <IReviewRepository, ReviewRepository>();
            services.AddTransient <IUserRepository, UserRepository>();
            services.AddTransient <IOrderRepository, OrderRepository>();
            services.AddTransient <IInvoiceRepository, InvoiceRepository>();
            services.AddTransient <IImageRepository, ImageRepository>();

            //A BL rétegbeli manager osztályok beregisztrálása.
            services.AddTransient <RestaurantManager>();
            services.AddTransient <ReviewManager>();
            services.AddTransient <FoodManager>();
            services.AddTransient <OrderManager>();
            services.AddTransient <ApplicationUserManager>();
        }
Ejemplo n.º 7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddProblemDetails(options =>
            {
                options.IncludeExceptionDetails = (ctx, ex) => false;
                options.Map <AuthorizationException>(
                    (ctx, ex) =>
                {
                    var pd   = StatusCodeProblemDetails.Create(StatusCodes.Status401Unauthorized);
                    pd.Title = ex.Message;
                    return(pd);
                }
                    );
                options.Map <ForbiddenException>(
                    (ctx, ex) =>
                {
                    var pd   = StatusCodeProblemDetails.Create(StatusCodes.Status403Forbidden);
                    pd.Title = ex.Message;
                    return(pd);
                }
                    );
            });
            services.Configure <FileStorageSettings>(
                Configuration.GetSection(nameof(FileStorageSettings)));
            services.AddSingleton <IFileStorageSettings>(sp =>
                                                         sp.GetRequiredService <IOptions <FileStorageSettings> >().Value);
            services.AddDbContext <CatalogDbContext>(o =>
                                                     o.UseSqlServer(Configuration.GetConnectionString("CatalogDb"), options => options.EnableRetryOnFailure())
                                                     );

            services.AddMassTransit(x =>
            {
                var config = Configuration.GetSection(nameof(MessageQueueSettings)).Get <MessageQueueSettings>();
                x.AddConsumer <VideoUploadedForCatalogEventHandler>();
                x.AddConsumer <VideoConvertedEventHandler>();
                x.AddBus(context =>
                         Bus.Factory.CreateUsingRabbitMq(cfg =>
                {
                    cfg.Host(new Uri($"rabbitmq://{config.Hostname}:/"),
                             hostConfig =>
                    {
                        hostConfig.Username(config.Username);
                        hostConfig.Password(config.Password);
                    });
                    cfg.ReceiveEndpoint("VideoConverted", ep =>
                    {
                        ep.ConfigureConsumer <VideoConvertedEventHandler>(context);
                    });
                    cfg.ReceiveEndpoint("VideoUploadedForCatalog", ep =>
                    {
                        ep.ConfigureConsumer <VideoUploadedForCatalogEventHandler>(context);
                    });
                })
                         );
                EndpointConvention.Map <IVideoConvertedEvent>(new Uri($"rabbitmq://{config.Hostname}:/VideoConverted"));
                EndpointConvention.Map <IVideoUploadedForCatalogEvent>(new Uri($"rabbitmq://{config.Hostname}:/VideoUploadedForCatalog"));
            });

            services.AddTransient <IVideoCatalogService, VideoCatalogService>();

            services.AddControllers().AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.Converters.Add(new GuidConverter());
            });
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "CatalogService", Version = "v1"
                });
            });
        }
Ejemplo n.º 8
0
 public void PostConfigure(string name, ProblemDetailsOptions options)
 {
     // If an exception other than above specified is thrown, this will handle it.
     options.Map <Exception>(ex => StatusCodeProblemDetails.Create(StatusCodes.Status500InternalServerError));
 }