diff --git a/Nbic.References/Controllers/ReferenceUsageController.cs b/Nbic.References/Controllers/ReferenceUsageController.cs index 8c1260a..dd30884 100644 --- a/Nbic.References/Controllers/ReferenceUsageController.cs +++ b/Nbic.References/Controllers/ReferenceUsageController.cs @@ -1,110 +1,106 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Swashbuckle.AspNetCore.Annotations; -namespace Nbic.References.Controllers +namespace Nbic.References.Controllers; + +using Microsoft.AspNetCore.Authorization; + +[Route("api/[controller]")] +[ApiController] +[SwaggerTag("Read, add or delete ReferencesUsages")] +public class ReferenceUsageController : ControllerBase { - using Microsoft.AspNetCore.Authorization; + private readonly IReferenceUsageRepository _referenceUsageRepository; - using EFCore; + public ReferenceUsageController(IReferenceUsageRepository referenceUsageRepository) + { + _referenceUsageRepository = referenceUsageRepository; + } - [Route("api/[controller]")] - [ApiController] - [SwaggerTag("Read, add or delete ReferencesUsages")] - public class ReferenceUsageController : ControllerBase + [HttpGet] + public async Task> GetAll(int offset = 0, int limit = 10) { - private readonly IReferenceUsageRepository _referenceUsageRepository; + return await _referenceUsageRepository.GetAll(offset, limit); + } + [HttpGet] + [Route("Reference/{id:guid}")] + public async Task> Get(Guid id) + { + return await _referenceUsageRepository.GetFromReferenceId(id); + } - public ReferenceUsageController(IReferenceUsageRepository referenceUsageRepository) - { - _referenceUsageRepository = referenceUsageRepository; - } + [HttpGet] + [Route("Count")] + public async Task> GetCount() + { + return await _referenceUsageRepository.CountAsync(); + } - [HttpGet] - public async Task> GetAll(int offset = 0, int limit = 10) + /// + /// Delete Usage for Reference + /// + /// Reference Id + /// + [Authorize("WriteAccess")] + [HttpDelete("{id:guid}")] + [ProducesResponseType(404)] + public Microsoft.AspNetCore.Mvc.ActionResult DeleteAllUsages(Guid id) + { + try { - return await _referenceUsageRepository.GetAll(offset, limit); + _referenceUsageRepository.DeleteForReference(id); } - [HttpGet] - [Route("Reference/{id}")] - public async Task> Get(Guid id) + catch (NotFoundException e) { - return await _referenceUsageRepository.GetFromReferenceId(id); + return NotFound(e); } + + return Ok(); + } - [HttpGet] - [Route("Count")] - public async Task> GetCount() + [Authorize("WriteAccess")] + [HttpDelete("{id:guid},{applicationId:int},{userId:guid}")] + public Microsoft.AspNetCore.Mvc.ActionResult DeleteUsage(Guid id, int applicationId, Guid userId) + { + try { - return await _referenceUsageRepository.CountAsync(); + _referenceUsageRepository.DeleteUsage(id, applicationId,userId); } - - /// - /// Delete Usage for Reference - /// - /// Reference Id - /// - [Authorize("WriteAccess")] - [HttpDelete("{id}")] - [ProducesResponseType(404)] - public Microsoft.AspNetCore.Mvc.ActionResult DeleteAllUsages(Guid id) + catch (NotFoundException e) { - try - { - _referenceUsageRepository.DeleteForReference(id); - } - catch (NotFoundException e) - { - return NotFound(e); - } - - return Ok(); + return NotFound(e); } - - [Authorize("WriteAccess")] - [HttpDelete("{id},{applicationId},{userId}")] - public Microsoft.AspNetCore.Mvc.ActionResult DeleteUsage(Guid id, int applicationId, Guid userId) - { - try - { - _referenceUsageRepository.DeleteUsage(id, applicationId,userId); - } - catch (NotFoundException e) - { - return NotFound(e); - } - return Ok(); + return Ok(); - } + } - [Authorize("WriteAccess")] - [HttpPost] - public async Task> Post([FromBody] ReferenceUsage value) + [Authorize("WriteAccess")] + [HttpPost] + public async Task> Post([FromBody] ReferenceUsage value) + { + if (value == null) { - if (value == null) - { - return BadRequest("No data posted"); - } + return BadRequest("No data posted"); + } - await _referenceUsageRepository.Add(value); + await _referenceUsageRepository.Add(value); - return value; - } + return value; + } - [Authorize("WriteAccess")] - [HttpPost("bulk")] - public async Task> Post(ReferenceUsage[] value) + [Authorize("WriteAccess")] + [HttpPost("bulk")] + public async Task> Post(ReferenceUsage[] value) + { + if (value == null) { - if (value == null) - { - return BadRequest("No data posted"); - } - - return await _referenceUsageRepository.AddRange(value); + return BadRequest("No data posted"); } + + return await _referenceUsageRepository.AddRange(value); } } \ No newline at end of file diff --git a/Nbic.References/Controllers/ReferencesController.cs b/Nbic.References/Controllers/ReferencesController.cs index ff96ba2..5893690 100644 --- a/Nbic.References/Controllers/ReferencesController.cs +++ b/Nbic.References/Controllers/ReferencesController.cs @@ -5,141 +5,140 @@ using Microsoft.AspNetCore.Mvc; using Swashbuckle.AspNetCore.Annotations; -namespace Nbic.References.Controllers +namespace Nbic.References.Controllers; + +[Route("api/[controller]")] +[ApiController] +[SwaggerTag("Create, read, update and delete References")] +public class ReferencesController : ControllerBase { - [Route("api/[controller]")] - [ApiController] - [SwaggerTag("Create, read, update and delete References")] - public class ReferencesController : ControllerBase + private readonly IReferencesRepository _referencesRepository; + + public ReferencesController(IReferencesRepository referencesRepository) { - private readonly IReferencesRepository _referencesRepository; + _referencesRepository = referencesRepository; + } - public ReferencesController(IReferencesRepository referencesRepository) - { - _referencesRepository = referencesRepository; - } + [HttpGet] + public async Task> GetAll(int offset = 0, int limit = 10, string search = null) + { + return await _referencesRepository.Search(search, offset, limit); + } + + [HttpGet] + [Route("Count")] + public async Task> GetCount() + { + return await _referencesRepository.CountAsync(); // _referencesDbContext.Reference.CountAsync().ConfigureAwait(false); + } + + [HttpGet] + [Authorize("WriteAccess")] + [Route("Reindex")] + public ActionResult DoReindex() + { + _referencesRepository.ReIndex(); + return true; + } + + [HttpGet("{id:guid}")] + public async Task> Get(Guid id) + { + var reference = await _referencesRepository.Get(id); + if (reference == null) return NotFound(); + + return reference; + } - [HttpGet] - public async Task> GetAll(int offset = 0, int limit = 10, string search = null) + [Authorize("WriteAccess")] + [HttpPost] + public async Task> Post([FromBody] Reference value) + { + if (value == null) { - return await _referencesRepository.Search(search, offset, limit); + return BadRequest("No data posted"); } - [HttpGet] - [Route("Count")] - public async Task> GetCount() + Reference newReference; + try { - return await _referencesRepository.CountAsync(); // _referencesDbContext.Reference.CountAsync().ConfigureAwait(false); + newReference = await _referencesRepository.Add(value); } - - [HttpGet] - [Authorize("WriteAccess")] - [Route("Reindex")] - public ActionResult DoReindex() + catch (BadRequestException e) { - _referencesRepository.ReIndex(); - return true; + return BadRequest(e); } - [HttpGet("{id}")] - public async Task> Get(Guid id) + return newReference; + } + + [Authorize("WriteAccess")] + [HttpPost] + [Route("Bulk")] + public async Task PostMany([FromBody] Reference[] values) + { + if (values == null || values.Length == 0) { - var reference = await _referencesRepository.Get(id); - if (reference == null) return NotFound(); - - return reference; + return BadRequest("No data posted"); } - - [Authorize("WriteAccess")] - [HttpPost] - public async Task> Post([FromBody] Reference value) + try { - if (value == null) - { - return BadRequest("No data posted"); - } - - Reference newReference; - try - { - newReference = await _referencesRepository.Add(value); - } - catch (BadRequestException e) - { - return BadRequest(e); - } - - return newReference; + await _referencesRepository.AddRange(values); } - - [Authorize("WriteAccess")] - [HttpPost] - [Route("Bulk")] - public async Task PostMany([FromBody] Reference[] values) + catch (BadRequestException e) { - if (values == null || values.Length == 0) - { - return BadRequest("No data posted"); - } - try - { - await _referencesRepository.AddRange(values); - } - catch (BadRequestException e) - { - return BadRequest(e); - } - - return Ok(); + return BadRequest(e); } + + return Ok(); + } - [Authorize("WriteAccess")] - [HttpPut("{id}")] - public async Task Put(Guid id, [FromBody] Reference value) + [Authorize("WriteAccess")] + [HttpPut("{id:guid}")] + public async Task Put(Guid id, [FromBody] Reference value) + { + if (value == null) { - if (value == null) - { - return BadRequest("No reference to put"); - } + return BadRequest("No reference to put"); + } - if (value.Id == Guid.Empty) - { - value.Id = id; - } + if (value.Id == Guid.Empty) + { + value.Id = id; + } - if (value.Id != id) - { - return BadRequest("Id on reference set and different..."); - } + if (value.Id != id) + { + return BadRequest("Id on reference set and different..."); + } - try - { - await _referencesRepository.Update(value); - } - catch (NotFoundException e) - { - return NotFound(e); - } - - return Ok(); + try + { + await _referencesRepository.Update(value); + } + catch (NotFoundException e) + { + return NotFound(e); } + + return Ok(); + } - [Authorize("WriteAccess")] - [HttpDelete("{id}")] - [System.Diagnostics.CodeAnalysis.SuppressMessage("Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "")] - public ActionResult Delete(Guid id) + [Authorize("WriteAccess")] + [HttpDelete("{id:guid}")] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "")] + public ActionResult Delete(Guid id) + { + try + { + _referencesRepository.Delete(id); + } + catch (NotFoundException e) { - try - { - _referencesRepository.Delete(id); - } - catch (NotFoundException e) - { - return NotFound(e); - } + return NotFound(e); + } - return Ok(); + return Ok(); - } } -} +} \ No newline at end of file diff --git a/Nbic.References/Program.cs b/Nbic.References/Program.cs index de2e30a..b1f31e8 100644 --- a/Nbic.References/Program.cs +++ b/Nbic.References/Program.cs @@ -1,20 +1,19 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; -namespace Nbic.References +namespace Nbic.References; + +public static class Program { - public static class Program + public static void Main(string[] args) { - public static void Main(string[] args) - { - CreateHostBuilder(args).Build().Run(); - } - - public static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup(); - }); + CreateHostBuilder(args).Build().Run(); } -} + + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup(); + }); +} \ No newline at end of file diff --git a/Nbic.References/Startup.cs b/Nbic.References/Startup.cs index 31eb4c1..1c5fc22 100644 --- a/Nbic.References/Startup.cs +++ b/Nbic.References/Startup.cs @@ -5,329 +5,325 @@ using Nbic.References.Infrastructure.Repositories.DbContext; using Nbic.References.Infrastructure.Services.Indexing; -namespace Nbic.References +namespace Nbic.References; + +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +using System.Threading.Tasks; + +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Microsoft.OpenApi.Models; +using Microsoft.IdentityModel.Logging; +using RobotsTxt; + +using Swagger; + +using Index = Index; + +public class Startup { - using System; - using System.Collections.Generic; - using System.Diagnostics.CodeAnalysis; - using System.IO; - using System.Linq; - using System.Threading.Tasks; - - using Microsoft.AspNetCore.Authentication.JwtBearer; - using Microsoft.AspNetCore.Builder; - using Microsoft.AspNetCore.Hosting; - using Microsoft.Data.Sqlite; - using Microsoft.EntityFrameworkCore; - using Microsoft.Extensions.Configuration; - using Microsoft.Extensions.DependencyInjection; - using Microsoft.Extensions.Hosting; - using Microsoft.Extensions.Logging; - using Microsoft.OpenApi.Models; - using Microsoft.IdentityModel.Logging; - - using EFCore; - - using RobotsTxt; - - using Swagger; - - using Index = Index; - - public class Startup - { - private readonly string apiName; - private readonly string authAuthority; - private readonly string authAuthorityEndPoint; - private readonly string connectionString; - private readonly string provider; - private readonly string writeAccessRole; - private readonly string swaggerClientId; + private readonly string apiName; + private readonly string authAuthority; + private readonly string authAuthorityEndPoint; + private readonly string connectionString; + private readonly string provider; + private readonly string writeAccessRole; + private readonly string swaggerClientId; - private ILogger logger; + private ILogger logger; - public Startup(IConfiguration configuration) - { - Configuration = configuration; + public Startup(IConfiguration configuration) + { + Configuration = configuration; - // configuration - authAuthority = Configuration.GetValue("AuthAuthority", "https://demo.identityserver.com"); - authAuthorityEndPoint = Configuration.GetValue( - "AuthAuthorityEndPoint", - "https://demo.identityserver.com/connect/authorize"); - apiName = Configuration.GetValue("ApiName", "api"); + // configuration + authAuthority = Configuration.GetValue("AuthAuthority", "https://demo.identityserver.com"); + authAuthorityEndPoint = Configuration.GetValue( + "AuthAuthorityEndPoint", + "https://demo.identityserver.com/connect/authorize"); + apiName = Configuration.GetValue("ApiName", "api"); - provider = Configuration.GetValue("DbProvider", "Sqlite"); - connectionString = Configuration.GetValue("DbConnectionString", "DataSource=:memory:"); + provider = Configuration.GetValue("DbProvider", "Sqlite"); + connectionString = Configuration.GetValue("DbConnectionString", "DataSource=:memory:"); - writeAccessRole = Configuration.GetValue("WriteAccessRole", "my_write_access_role"); - swaggerClientId = Configuration.GetValue("SwaggerClientId", "implicit"); - } + writeAccessRole = Configuration.GetValue("WriteAccessRole", "my_write_access_role"); + swaggerClientId = Configuration.GetValue("SwaggerClientId", "implicit"); + } - public IConfiguration Configuration { get; } + public IConfiguration Configuration { get; } - // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - [SuppressMessage("Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "")] - public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger log) + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + [SuppressMessage("Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "")] + public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger log) + { + logger = log; + app.UseResponseCompression(); + if (env.IsDevelopment()) { - logger = log; - app.UseResponseCompression(); - if (env.IsDevelopment()) - { - app.UseDeveloperExceptionPage(); - log.LogInformation("In Development environment"); + app.UseDeveloperExceptionPage(); + log.LogInformation("In Development environment"); - IdentityModelEventSource.ShowPII = true; - } + IdentityModelEventSource.ShowPII = true; + } - app.UseHttpsRedirection(); - app.UseStaticFiles(); - app.UseRobotsTxt(); - app.UseRouting(); + app.UseHttpsRedirection(); + app.UseStaticFiles(); + app.UseRobotsTxt(); + app.UseRouting(); - AddSwaggerMiddleware(app); + AddSwaggerMiddleware(app); - app.UseCors("AllowAll"); + app.UseCors("AllowAll"); - app.UseAuthentication(); - app.UseAuthorization(); + app.UseAuthentication(); + app.UseAuthorization(); - app.UseEndpoints(endpoints => - { - endpoints.MapControllers(); - }); - } - - // This method gets called by the runtime. Use this method to add services to the container. - [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", Justification = "")] - public void ConfigureServices(IServiceCollection services) + app.UseEndpoints(endpoints => { - services.AddResponseCompression(); - services.AddControllers(options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true); + endpoints.MapControllers(); + }); + } - // services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0); - AddIdentityServerAuthentication(services); - AddSwaggerGenerator(services); - switch (provider) - { - case "Sqlite": - AddSqliteContext(services); - break; - case "SqlServer": - AddSqlServerContext(services); - break; - } + // This method gets called by the runtime. Use this method to add services to the container. + [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", Justification = "")] + public void ConfigureServices(IServiceCollection services) + { + services.AddResponseCompression(); + services.AddControllers(options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true); - services.AddSingleton(new Index()); - services.AddScoped(); - services.AddScoped(); + // services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0); + AddIdentityServerAuthentication(services); + AddSwaggerGenerator(services); + switch (provider) + { + case "Sqlite": + AddSqliteContext(services); + break; + case "SqlServer": + AddSqlServerContext(services); + break; + } - services.AddCors( - options => + services.AddSingleton(new Index()); + services.AddScoped(); + services.AddScoped(); + + services.AddCors( + options => + { + options.AddPolicy( + "AllowAll", + builder => { - options.AddPolicy( - "AllowAll", - builder => - { - builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod() - .WithExposedHeaders("WWW-Authenticate"); - }); + builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod() + .WithExposedHeaders("WWW-Authenticate"); }); + }); - services.AddStaticRobotsTxt(builder => builder.DenyAll()); - } + services.AddStaticRobotsTxt(builder => builder.DenyAll()); + } - private void AddIdentityServerAuthentication(IServiceCollection services) - { - var roleClaim = "role"; - var roleClaimValue = writeAccessRole; + private void AddIdentityServerAuthentication(IServiceCollection services) + { + var roleClaim = "role"; + var roleClaimValue = writeAccessRole; - // Users defined at https://demo.identityserver.com has no roles. - // Using the Issuer-claim (iss) as a substitute to allow authorization with Swagger when testing - if (authAuthority == "https://demo.identityserver.com") - { - roleClaim = "iss"; - roleClaimValue = "https://demo.identityserver.com"; - } + // Users defined at https://demo.identityserver.com has no roles. + // Using the Issuer-claim (iss) as a substitute to allow authorization with Swagger when testing + if (authAuthority == "https://demo.identityserver.com") + { + roleClaim = "iss"; + roleClaimValue = "https://demo.identityserver.com"; + } - services.AddAuthorization(options => - options.AddPolicy("WriteAccess", policy => policy.RequireClaim(roleClaim, roleClaimValue))); + services.AddAuthorization(options => + options.AddPolicy("WriteAccess", policy => policy.RequireClaim(roleClaim, roleClaimValue))); - services.AddCors(); + services.AddCors(); - services.AddAuthentication("token") - .AddJwtBearer("Bearer", options => - { - options.Authority = authAuthority; - options.RequireHttpsMetadata = false; + services.AddAuthentication("token") + .AddJwtBearer("Bearer", options => + { + options.Authority = authAuthority; + options.RequireHttpsMetadata = false; - options.Audience = apiName; - //options.TokenValidationParameters.ValidAudiences = options.TokenValidationParameters.ValidAudiences.Append("fab4api"); - } - ) - .AddIdentityServerAuthentication( + options.Audience = apiName; + //options.TokenValidationParameters.ValidAudiences = options.TokenValidationParameters.ValidAudiences.Append("fab4api"); + } + ) + .AddIdentityServerAuthentication( "token", options => - { - options.Authority = authAuthority; - options.RequireHttpsMetadata = false; - - options.ApiName = apiName; - options.JwtBearerEvents = new JwtBearerEvents - { - OnMessageReceived = e => - { - // _logger.LogTrace("JWT: message received"); - return Task.CompletedTask; - }, - OnTokenValidated = e => - { - // _logger.LogTrace("JWT: token validated"); - return Task.CompletedTask; - }, - OnAuthenticationFailed = e => - { - // _logger.LogTrace("JWT: authentication failed"); - return Task.CompletedTask; - }, - OnChallenge = e => - { - // _logger.LogTrace("JWT: challenge"); - return Task.CompletedTask; - } - }; - }); - - Microsoft.IdentityModel.Logging.IdentityModelEventSource.ShowPII = true; - } - - [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", Justification = "")] - [SuppressMessage("Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "")] - private void AddSqliteContext(IServiceCollection services) - { - Console.WriteLine("Adding SqliteContext"); - if (connectionString == "DataSource=:memory:") - { - Console.WriteLine($"SqliteContext - ConnectionString:{connectionString}"); - var context = new SqliteReferencesDbContext(connectionString); - context.Database.OpenConnection(); - context.Database.Migrate(); - services.AddSingleton(context); // in memory version need this - Console.WriteLine("Added InMemoryDatabase"); - } - else - { - // if database is empty - initiate - if (!Directory.Exists("Data")) Directory.CreateDirectory("Data"); - var dbConnectionString = connectionString.Contains('/', StringComparison.InvariantCulture) - ? connectionString - : connectionString.Replace( - "Data Source=", - "Data Source=./Data/", - StringComparison.InvariantCulture); - Console.WriteLine($"SqliteContext - ConnectionString:{dbConnectionString}"); - using (var context = new SqliteReferencesDbContext(dbConnectionString)) { - try - { - var any = context.Reference.Any(); - } - catch (SqliteException ex) + options.Authority = authAuthority; + options.RequireHttpsMetadata = false; + + options.ApiName = apiName; + options.JwtBearerEvents = new JwtBearerEvents { - if (ex.Message.Contains("SQLite Error 1: 'no such table", StringComparison.CurrentCulture)) + OnMessageReceived = e => { - context.Database.Migrate(); - Console.WriteLine($"Empty Schema - initial create - after exception {ex.Message}"); - } - else + // _logger.LogTrace("JWT: message received"); + return Task.CompletedTask; + }, + OnTokenValidated = e => + { + // _logger.LogTrace("JWT: token validated"); + return Task.CompletedTask; + }, + OnAuthenticationFailed = e => + { + // _logger.LogTrace("JWT: authentication failed"); + return Task.CompletedTask; + }, + OnChallenge = e => { - throw; + // _logger.LogTrace("JWT: challenge"); + return Task.CompletedTask; } - } + }; + }); - Console.WriteLine("Added FileDatabase"); - } + Microsoft.IdentityModel.Logging.IdentityModelEventSource.ShowPII = true; + } - services.AddDbContext(options => options.UseSqlite(dbConnectionString)); - Console.WriteLine("Added SqliteContext"); - } + [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", Justification = "")] + [SuppressMessage("Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "")] + private void AddSqliteContext(IServiceCollection services) + { + Console.WriteLine("Adding SqliteContext"); + if (connectionString == "DataSource=:memory:") + { + Console.WriteLine($"SqliteContext - ConnectionString:{connectionString}"); + var context = new SqliteReferencesDbContext(connectionString); + context.Database.OpenConnection(); + context.Database.Migrate(); + services.AddSingleton(context); // in memory version need this + Console.WriteLine("Added InMemoryDatabase"); } - - [SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "")] - [SuppressMessage("Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "")] - private void AddSqlServerContext(IServiceCollection services) + else { - Console.WriteLine("Adding SqlServerContext"); - using (var context = new SqlServerReferencesDbContext(connectionString)) + // if database is empty - initiate + if (!Directory.Exists("Data")) Directory.CreateDirectory("Data"); + var dbConnectionString = connectionString.Contains('/', StringComparison.InvariantCulture) + ? connectionString + : connectionString.Replace( + "Data Source=", + "Data Source=./Data/", + StringComparison.InvariantCulture); + Console.WriteLine($"SqliteContext - ConnectionString:{dbConnectionString}"); + using (var context = new SqliteReferencesDbContext(dbConnectionString)) { try { var any = context.Reference.Any(); } - catch (Exception ex) + catch (SqliteException ex) { - Console.WriteLine($"Empty Schema - initial create - after error {ex.Message}"); - context.Database.Migrate(); + if (ex.Message.Contains("SQLite Error 1: 'no such table", StringComparison.CurrentCulture)) + { + context.Database.Migrate(); + Console.WriteLine($"Empty Schema - initial create - after exception {ex.Message}"); + } + else + { + throw; + } } + + Console.WriteLine("Added FileDatabase"); } - services.AddDbContext(options => options.UseSqlServer(connectionString)); - Console.WriteLine("Added SqlServerContext"); + services.AddDbContext(options => options.UseSqlite(dbConnectionString)); + Console.WriteLine("Added SqliteContext"); } + } - private void AddSwaggerGenerator(IServiceCollection services) + [SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "")] + [SuppressMessage("Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "")] + private void AddSqlServerContext(IServiceCollection services) + { + Console.WriteLine("Adding SqlServerContext"); + using (var context = new SqlServerReferencesDbContext(connectionString)) { - services.AddSwaggerGen( - c => - { - c.SwaggerDoc( - "v1", - new OpenApiInfo { Title = "Nbic References API via Swagger", Version = "v1" }); - - c.AddSecurityDefinition( - "oauth2", - new OpenApiSecurityScheme - { - Type = SecuritySchemeType.OAuth2, - Flows = new OpenApiOAuthFlows - { - Implicit = new OpenApiOAuthFlow - { - AuthorizationUrl = - new Uri( - authAuthorityEndPoint, - UriKind.Absolute), - Scopes = new Dictionary - { - { apiName, "Access Api" } - - // { "readAccess", "Access read operations" }, - // { "writeAccess", "Access write operations" } - } - } - } - }); - c.OperationFilter(); - c.EnableAnnotations(); - }); + try + { + var any = context.Reference.Any(); + } + catch (Exception ex) + { + Console.WriteLine($"Empty Schema - initial create - after error {ex.Message}"); + context.Database.Migrate(); + } } - private void AddSwaggerMiddleware(IApplicationBuilder app) - { - app.UseSwagger(); - app.UseSwaggerUI( - c => + services.AddDbContext(options => options.UseSqlServer(connectionString)); + Console.WriteLine("Added SqlServerContext"); + } + + private void AddSwaggerGenerator(IServiceCollection services) + { + services.AddSwaggerGen( + c => + { + c.SwaggerDoc( + "v1", + new OpenApiInfo { Title = "Nbic References API via Swagger", Version = "v1" }); + + c.AddSecurityDefinition( + "oauth2", + new OpenApiSecurityScheme { - c.SwaggerEndpoint("/swagger/v1/swagger.json", "Nbic References API V1"); - c.OAuthClientId(swaggerClientId); - c.OAuthAppName(apiName); - c.OAuthScopeSeparator(" "); - - // c.OAuthAdditionalQueryStringParams(new { foo = "bar" }); - c.OAuthUseBasicAuthenticationWithAccessCodeGrant(); - c.RoutePrefix = string.Empty; + Type = SecuritySchemeType.OAuth2, + Flows = new OpenApiOAuthFlows + { + Implicit = new OpenApiOAuthFlow + { + AuthorizationUrl = + new Uri( + authAuthorityEndPoint, + UriKind.Absolute), + Scopes = new Dictionary + { + { apiName, "Access Api" } + + // { "readAccess", "Access read operations" }, + // { "writeAccess", "Access write operations" } + } + } + } }); - } + c.OperationFilter(); + c.EnableAnnotations(); + }); + } + + private void AddSwaggerMiddleware(IApplicationBuilder app) + { + app.UseSwagger(); + app.UseSwaggerUI( + c => + { + c.SwaggerEndpoint("/swagger/v1/swagger.json", "Nbic References API V1"); + c.OAuthClientId(swaggerClientId); + c.OAuthAppName(apiName); + c.OAuthScopeSeparator(" "); + + // c.OAuthAdditionalQueryStringParams(new { foo = "bar" }); + c.OAuthUseBasicAuthenticationWithAccessCodeGrant(); + c.RoutePrefix = string.Empty; + }); } } \ No newline at end of file diff --git a/Nbic.References/Swagger/SecurityRequirementsOperationFilter.cs b/Nbic.References/Swagger/SecurityRequirementsOperationFilter.cs index 196aca3..62fa3ad 100644 --- a/Nbic.References/Swagger/SecurityRequirementsOperationFilter.cs +++ b/Nbic.References/Swagger/SecurityRequirementsOperationFilter.cs @@ -1,43 +1,41 @@ using System.Collections.Generic; using System.Linq; -using Microsoft.AspNetCore.Authorization; using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; -namespace Nbic.References.Swagger +namespace Nbic.References.Swagger; + +/// +/// Help swagger discover api operations that require authentication +/// +public class SecurityRequirementsOperationFilter : IOperationFilter { - /// - /// Help swagger discover api operations that require authentication - /// - public class SecurityRequirementsOperationFilter : IOperationFilter + [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1062:Validate arguments of public methods", Justification = "")] + public void Apply(OpenApiOperation operation, OperationFilterContext context) { - [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1062:Validate arguments of public methods", Justification = "")] - public void Apply(OpenApiOperation operation, OperationFilterContext context) - { - // Policy names map to scopes - var requiredScopes = context.MethodInfo - .GetCustomAttributes(true) - .OfType() - .Select(attr => attr.Policy) - .Distinct().ToList(); + // Policy names map to scopes + var requiredScopes = context.MethodInfo + .GetCustomAttributes(true) + .OfType() + .Select(attr => attr.Policy) + .Distinct().ToList(); - if (!requiredScopes.Any()) return; + if (requiredScopes.Count == 0) return; - operation.Responses.Add("401", new OpenApiResponse { Description = "Unauthorized" }); - operation.Responses.Add("403", new OpenApiResponse { Description = "Forbidden" }); + operation.Responses.Add("401", new() { Description = "Unauthorized" }); + operation.Responses.Add("403", new() { Description = "Forbidden" }); - var oAuthScheme = new OpenApiSecurityScheme - { - Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2" } - }; + var oAuthScheme = new OpenApiSecurityScheme + { + Reference = new() { Type = ReferenceType.SecurityScheme, Id = "oauth2" } + }; - operation.Security = new List + operation.Security = new List + { + new() { - new OpenApiSecurityRequirement - { - [ oAuthScheme ] = requiredScopes - } - }; - } + [ oAuthScheme ] = requiredScopes + } + }; } } \ No newline at end of file