diff options
| author | Kamen Mladenov <kamen.d.mladenov@protonmail.com> | 2021-04-09 19:51:35 +0300 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2021-04-09 19:51:35 +0300 |
| commit | 233f38915ba0079079233eff55434ef349c05c45 (patch) | |
| tree | 6c5f69017865bcab87355e910c87339453da1406 /src/Web/DevHive.Web/Configurations/Extensions | |
| parent | f4a70c6430db923af9fa9958a11c2d6612cb52cc (diff) | |
| parent | a992357efcf1bc1ece81b95ecee5e05a0b73bfdc (diff) | |
| download | DevHive-0.2.tar DevHive-0.2.tar.gz DevHive-0.2.zip | |
Merge pull request #28 from Team-Kaleidoscope/devHEADv0.2mainheroku/main
Second stage: Complete
Diffstat (limited to 'src/Web/DevHive.Web/Configurations/Extensions')
6 files changed, 322 insertions, 0 deletions
diff --git a/src/Web/DevHive.Web/Configurations/Extensions/ConfigureAutoMapper.cs b/src/Web/DevHive.Web/Configurations/Extensions/ConfigureAutoMapper.cs new file mode 100644 index 0000000..cd5679f --- /dev/null +++ b/src/Web/DevHive.Web/Configurations/Extensions/ConfigureAutoMapper.cs @@ -0,0 +1,26 @@ +using System; +using System.Linq; +using System.Reflection; +using System.Reflection.Emit; +using AutoMapper; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; + +namespace DevHive.Web.Configurations.Extensions +{ + public static class ConfigureAutoMapper + { + public static void AutoMapperConfiguration(this IServiceCollection services) + { + services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); + } + + public static void UseAutoMapperConfiguration(this IApplicationBuilder app) + { + _ = new MapperConfiguration(cfg => + { + cfg.AllowNullCollections = true; + }); + } + } +} diff --git a/src/Web/DevHive.Web/Configurations/Extensions/ConfigureDatabase.cs b/src/Web/DevHive.Web/Configurations/Extensions/ConfigureDatabase.cs new file mode 100644 index 0000000..b4c49b4 --- /dev/null +++ b/src/Web/DevHive.Web/Configurations/Extensions/ConfigureDatabase.cs @@ -0,0 +1,98 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using DevHive.Data.Models; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Builder; +using System; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using DevHive.Data; +using System.Linq; +using System.Threading.Tasks; + +namespace DevHive.Web.Configurations.Extensions +{ + public static class DatabaseExtensions + { + public static void DatabaseConfiguration(this IServiceCollection services, IConfiguration configuration) + { + services.AddDbContext<DevHiveContext>(options => + { + // options.EnableSensitiveDataLogging(true); + options.UseNpgsql(configuration.GetConnectionString("DEV"), options => + { + options.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery); + }); + }); + + services.AddIdentity<User, Role>() + .AddRoles<Role>() + .AddEntityFrameworkStores<DevHiveContext>(); + + services.Configure<IdentityOptions>(options => + { + options.User.RequireUniqueEmail = true; + + options.Password.RequireDigit = true; + options.Password.RequiredLength = 5; + options.Password.RequiredUniqueChars = 0; + options.Password.RequireLowercase = false; + options.Password.RequireNonAlphanumeric = false; + options.Password.RequireUppercase = false; + + options.Lockout.AllowedForNewUsers = true; + options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5); + options.Lockout.MaxFailedAccessAttempts = 5; + }); + + services.AddAuthorization(options => + { + options.AddPolicy("User", options => + { + options.RequireAuthenticatedUser(); + options.AuthenticationSchemes.Add(JwtBearerDefaults.AuthenticationScheme); + options.RequireRole("User"); + }); + + options.AddPolicy("Administrator", options => + { + options.RequireAuthenticatedUser(); + options.AuthenticationSchemes.Add(JwtBearerDefaults.AuthenticationScheme); + options.RequireRole("Admin"); + }); + }); + } + + public static void UseDatabaseConfiguration(this IApplicationBuilder app) + { + app.UseHttpsRedirection(); + app.UseRouting(); + + app.UseAuthentication(); + app.UseAuthorization(); + + using var serviceScope = app.ApplicationServices.CreateScope(); + using var dbContext = serviceScope.ServiceProvider.GetRequiredService<DevHiveContext>(); + + dbContext.Database.Migrate(); + + var roleManager = (RoleManager<Role>)serviceScope.ServiceProvider.GetService(typeof(RoleManager<Role>)); + + if (!dbContext.Roles.Any(x => x.Name == Role.DefaultRole)) + { + Role defaultRole = new() { Name = Role.DefaultRole }; + + roleManager.CreateAsync(defaultRole).Wait(); + } + + if (!dbContext.Roles.Any(x => x.Name == Role.AdminRole)) + { + Role adminRole = new() { Name = Role.AdminRole }; + + roleManager.CreateAsync(adminRole).Wait(); + } + + dbContext.SaveChanges(); + } + } +} diff --git a/src/Web/DevHive.Web/Configurations/Extensions/ConfigureDependencyInjection.cs b/src/Web/DevHive.Web/Configurations/Extensions/ConfigureDependencyInjection.cs new file mode 100644 index 0000000..f49a335 --- /dev/null +++ b/src/Web/DevHive.Web/Configurations/Extensions/ConfigureDependencyInjection.cs @@ -0,0 +1,51 @@ +using System.Text; +using DevHive.Common.Jwt; +using DevHive.Common.Jwt.Interfaces; +using DevHive.Data.Interfaces; +using DevHive.Data.Repositories; +using DevHive.Services.Interfaces; +using DevHive.Services.Services; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; + +namespace DevHive.Web.Configurations.Extensions +{ + public static class ConfigureDependencyInjection + { + public static void DependencyInjectionConfiguration(this IServiceCollection services, IConfiguration configuration) + { + services.AddTransient<ILanguageRepository, LanguageRepository>(); + services.AddTransient<IRoleRepository, RoleRepository>(); + services.AddTransient<ITechnologyRepository, TechnologyRepository>(); + services.AddTransient<IPostRepository, PostRepository>(); + services.AddTransient<ICommentRepository, CommentRepository>(); + services.AddTransient<IFeedRepository, FeedRepository>(); + services.AddTransient<IRatingRepository, RatingRepository>(); + services.AddTransient<IProfilePictureRepository, ProfilePictureRepository>(); + services.AddTransient<IUserRepository, UserRepository>(); + + services.AddTransient<ILanguageService, LanguageService>(); + services.AddTransient<IRoleService, RoleService>(); + services.AddTransient<ITechnologyService, TechnologyService>(); + services.AddTransient<IPostService, PostService>(); + services.AddTransient<ICommentService, CommentService>(); + services.AddTransient<IFeedService, FeedService>(); + services.AddTransient<IRatingService, RatingService>(); + services.AddTransient<IProfilePictureService, ProfilePictureService>(); + services.AddTransient<IUserService, UserService>(); + services.AddTransient<IFriendsService, FriendsService>(); + + services.AddTransient<ICloudService, CloudinaryService>(options => + new CloudinaryService( + cloudName: configuration.GetSection("Cloud").GetSection("cloudName").Value, + apiKey: configuration.GetSection("Cloud").GetSection("apiKey").Value, + apiSecret: configuration.GetSection("Cloud").GetSection("apiSecret").Value)); + + services.AddSingleton<IJwtService, JwtService>(options => + new JwtService( + signingKey: Encoding.ASCII.GetBytes(configuration.GetSection("Jwt").GetSection("signingKey").Value), + validationIssuer: configuration.GetSection("Jwt").GetSection("validationIssuer").Value, + audience: configuration.GetSection("Jwt").GetSection("audience").Value)); + } + } +} diff --git a/src/Web/DevHive.Web/Configurations/Extensions/ConfigureExceptionHandlerMiddleware.cs b/src/Web/DevHive.Web/Configurations/Extensions/ConfigureExceptionHandlerMiddleware.cs new file mode 100644 index 0000000..6885f84 --- /dev/null +++ b/src/Web/DevHive.Web/Configurations/Extensions/ConfigureExceptionHandlerMiddleware.cs @@ -0,0 +1,36 @@ +using DevHive.Web.Middleware; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Configuration; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Http; + +namespace DevHive.Web.Configurations.Extensions +{ + public static class ConfigureExceptionHandlerMiddleware + { + public static void ConfigureExceptionHandler(this IServiceCollection services, IConfiguration configuration) + { + services.Configure<ApiBehaviorOptions>(o => + { + o.InvalidModelStateResponseFactory = actionContext => + { + var problemDetails = new ValidationProblemDetails(actionContext.ModelState) + { + Status = StatusCodes.Status422UnprocessableEntity + }; + + return new UnprocessableEntityObjectResult(problemDetails) + { + ContentTypes = { "application/problem+json" } + }; + }; + }); + } + + public static void UseExceptionHandlerMiddlewareConfiguration(this IApplicationBuilder app) + { + app.UseMiddleware<ExceptionMiddleware>(); + } + } +} diff --git a/src/Web/DevHive.Web/Configurations/Extensions/ConfigureJwt.cs b/src/Web/DevHive.Web/Configurations/Extensions/ConfigureJwt.cs new file mode 100644 index 0000000..18127bc --- /dev/null +++ b/src/Web/DevHive.Web/Configurations/Extensions/ConfigureJwt.cs @@ -0,0 +1,46 @@ +using System.Text; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.IdentityModel.Tokens; + +namespace DevHive.Web.Configurations.Extensions +{ + public static class ConfigureJwt + { + public static void JWTConfiguration(this IServiceCollection services, IConfiguration configuration) + { + // Get key from appsettings.json + var signingKey = Encoding.ASCII.GetBytes(configuration + .GetSection("Jwt") + .GetSection("signingKey") + .Value); + + // Setup Jwt Authentication + services.AddAuthentication(x => + { + x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; + x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; + }) + .AddJwtBearer(x => + { + x.Events = new JwtBearerEvents + { + OnTokenValidated = context => + { + return Task.CompletedTask; + } + }; + x.RequireHttpsMetadata = false; + x.SaveToken = true; + x.TokenValidationParameters = new TokenValidationParameters + { + IssuerSigningKey = new SymmetricSecurityKey(signingKey), + ValidateIssuer = false, + ValidateAudience = false + }; + }); + } + } +} diff --git a/src/Web/DevHive.Web/Configurations/Extensions/ConfigureSwagger.cs b/src/Web/DevHive.Web/Configurations/Extensions/ConfigureSwagger.cs new file mode 100644 index 0000000..1b7182c --- /dev/null +++ b/src/Web/DevHive.Web/Configurations/Extensions/ConfigureSwagger.cs @@ -0,0 +1,65 @@ +using System.Linq; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; +using NSwag; +using NSwag.Generation.Processors.Security; + +namespace DevHive.Web.Configurations.Extensions +{ + public static class SwaggerExtensions + { +#pragma warning disable S1075 + private const string LicenseName = "GPL-3.0 License"; + private const string LicenseUri = "https://github.com/Team-Kaleidoscope/DevHive/blob/main/LICENSE"; + private const string TermsOfServiceUri = "https://example.com/terms"; +#pragma warning restore S1075 + + public static void SwaggerConfiguration(this IServiceCollection services) + { + services.AddOpenApiDocument(c => + { + c.GenerateXmlObjects = true; + c.UseControllerSummaryAsTagDescription = true; + + c.AllowNullableBodyParameters = false; + c.Description = "DevHive Social Media's API Endpoints"; + + c.PostProcess = doc => + { + doc.Info.Version = "v0.1"; + doc.Info.Title = "API"; + doc.Info.Description = "DevHive Social Media's first official API release"; + doc.Info.TermsOfService = TermsOfServiceUri; + doc.Info.License = new() + { + Name = LicenseName, + Url = LicenseUri + }; + }; + + c.AddSecurity("Bearer", Enumerable.Empty<string>(), new() + { + Type = OpenApiSecuritySchemeType.ApiKey, + Name = "Authorization", + In = OpenApiSecurityApiKeyLocation.Header, + Description = "Type into the textbox: Bearer {your JWT token}." + }); + c.OperationProcessors.Add(new AspNetCoreOperationSecurityScopeProcessor("Bearer")); + }); + } + + public static void UseSwaggerConfiguration(this IApplicationBuilder app) + { + app.UseOpenApi(c => + { + c.DocumentName = "v0.1"; + }); + app.UseSwaggerUi3(c => + { + c.DocumentTitle = "DevHive API"; + c.EnableTryItOut = false; + c.DocExpansion = "list"; + }); + } + } +} |
