Правки и рефакторинг
This commit is contained in:
parent
c3c04f9c66
commit
e98cd7d6e9
@ -29,24 +29,25 @@ public class ChangeLogController : ControllerBase, IChangeLogApi
|
|||||||
var userId = User.GetUserId<Guid>();
|
var userId = User.GetUserId<Guid>();
|
||||||
var result = await repository.InsertRange(userId, idDiscriminator, [dto], token);
|
var result = await repository.InsertRange(userId, idDiscriminator, [dto], token);
|
||||||
|
|
||||||
return Ok(result);
|
return CreatedAtAction(nameof(Add), result);
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpPost("range")]
|
[HttpPost("range")]
|
||||||
[ProducesResponseType(typeof(int), (int)HttpStatusCode.OK)]
|
[ProducesResponseType(typeof(int), (int)HttpStatusCode.OK)]
|
||||||
public async Task<IActionResult> AddRange(
|
public async Task<IActionResult> AddRange(
|
||||||
Guid idDiscriminator,
|
Guid idDiscriminator,
|
||||||
[FromBody] IEnumerable<DataWithWellDepthAndSectionDto> dtos, CancellationToken token)
|
[FromBody] IEnumerable<DataWithWellDepthAndSectionDto> dtos,
|
||||||
|
CancellationToken token = default)
|
||||||
{
|
{
|
||||||
var userId = User.GetUserId<Guid>();
|
var userId = User.GetUserId<Guid>();
|
||||||
var result = await repository.InsertRange(userId, idDiscriminator, dtos, token);
|
var result = await repository.InsertRange(userId, idDiscriminator, dtos, token);
|
||||||
|
|
||||||
return Ok(result);
|
return CreatedAtAction(nameof(AddRange), result);
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpDelete]
|
[HttpDelete]
|
||||||
[ProducesResponseType(typeof(int), (int)HttpStatusCode.OK)]
|
[ProducesResponseType(typeof(int), (int)HttpStatusCode.OK)]
|
||||||
public async Task<IActionResult> Delete(Guid id, CancellationToken token)
|
public async Task<IActionResult> Delete(Guid id, CancellationToken token = default)
|
||||||
{
|
{
|
||||||
var userId = User.GetUserId<Guid>();
|
var userId = User.GetUserId<Guid>();
|
||||||
var result = await repository.MarkAsDeleted(userId, [id], token);
|
var result = await repository.MarkAsDeleted(userId, [id], token);
|
||||||
@ -56,7 +57,7 @@ public class ChangeLogController : ControllerBase, IChangeLogApi
|
|||||||
|
|
||||||
[HttpDelete("range")]
|
[HttpDelete("range")]
|
||||||
[ProducesResponseType(typeof(int), (int)HttpStatusCode.OK)]
|
[ProducesResponseType(typeof(int), (int)HttpStatusCode.OK)]
|
||||||
public async Task<IActionResult> DeleteRange(IEnumerable<Guid> ids, CancellationToken token)
|
public async Task<IActionResult> DeleteRange(IEnumerable<Guid> ids, CancellationToken token = default)
|
||||||
{
|
{
|
||||||
var userId = User.GetUserId<Guid>();
|
var userId = User.GetUserId<Guid>();
|
||||||
var result = await repository.MarkAsDeleted(userId, ids, token);
|
var result = await repository.MarkAsDeleted(userId, ids, token);
|
||||||
@ -69,7 +70,7 @@ public class ChangeLogController : ControllerBase, IChangeLogApi
|
|||||||
public async Task<IActionResult> ClearAndInsertRange(
|
public async Task<IActionResult> ClearAndInsertRange(
|
||||||
Guid idDiscriminator,
|
Guid idDiscriminator,
|
||||||
IEnumerable<DataWithWellDepthAndSectionDto> dtos,
|
IEnumerable<DataWithWellDepthAndSectionDto> dtos,
|
||||||
CancellationToken token)
|
CancellationToken token = default)
|
||||||
{
|
{
|
||||||
var userId = User.GetUserId<Guid>();
|
var userId = User.GetUserId<Guid>();
|
||||||
var result = await repository.ClearAndInsertRange(userId, idDiscriminator, dtos, token);
|
var result = await repository.ClearAndInsertRange(userId, idDiscriminator, dtos, token);
|
||||||
@ -81,7 +82,7 @@ public class ChangeLogController : ControllerBase, IChangeLogApi
|
|||||||
public async Task<IActionResult> Update(
|
public async Task<IActionResult> Update(
|
||||||
Guid idDiscriminator,
|
Guid idDiscriminator,
|
||||||
DataWithWellDepthAndSectionDto dto,
|
DataWithWellDepthAndSectionDto dto,
|
||||||
CancellationToken token)
|
CancellationToken token = default)
|
||||||
{
|
{
|
||||||
var userId = User.GetUserId<Guid>();
|
var userId = User.GetUserId<Guid>();
|
||||||
var result = await repository.UpdateRange(userId, idDiscriminator, [dto], token);
|
var result = await repository.UpdateRange(userId, idDiscriminator, [dto], token);
|
||||||
@ -94,7 +95,7 @@ public class ChangeLogController : ControllerBase, IChangeLogApi
|
|||||||
public async Task<IActionResult> UpdateRange(
|
public async Task<IActionResult> UpdateRange(
|
||||||
Guid idDiscriminator,
|
Guid idDiscriminator,
|
||||||
IEnumerable<DataWithWellDepthAndSectionDto> dtos,
|
IEnumerable<DataWithWellDepthAndSectionDto> dtos,
|
||||||
CancellationToken token)
|
CancellationToken token = default)
|
||||||
{
|
{
|
||||||
var userId = User.GetUserId<Guid>();
|
var userId = User.GetUserId<Guid>();
|
||||||
var result = await repository.UpdateRange(userId, idDiscriminator, dtos, token);
|
var result = await repository.UpdateRange(userId, idDiscriminator, dtos, token);
|
||||||
@ -107,7 +108,7 @@ public class ChangeLogController : ControllerBase, IChangeLogApi
|
|||||||
public async Task<IActionResult> GetCurrent(
|
public async Task<IActionResult> GetCurrent(
|
||||||
Guid idDiscriminator,
|
Guid idDiscriminator,
|
||||||
[FromQuery]SectionPartRequest request,
|
[FromQuery]SectionPartRequest request,
|
||||||
CancellationToken token)
|
CancellationToken token = default)
|
||||||
{
|
{
|
||||||
var moment = new DateTimeOffset(3000, 1, 1, 0, 0, 0, TimeSpan.Zero);
|
var moment = new DateTimeOffset(3000, 1, 1, 0, 0, 0, TimeSpan.Zero);
|
||||||
var result = await repository.GetByDate(idDiscriminator, moment, request, token);
|
var result = await repository.GetByDate(idDiscriminator, moment, request, token);
|
||||||
@ -121,7 +122,7 @@ public class ChangeLogController : ControllerBase, IChangeLogApi
|
|||||||
Guid idDiscriminator,
|
Guid idDiscriminator,
|
||||||
DateTimeOffset moment,
|
DateTimeOffset moment,
|
||||||
[FromQuery] SectionPartRequest request,
|
[FromQuery] SectionPartRequest request,
|
||||||
CancellationToken token)
|
CancellationToken token = default)
|
||||||
{
|
{
|
||||||
var result = await repository.GetByDate(idDiscriminator, moment, request, token);
|
var result = await repository.GetByDate(idDiscriminator, moment, request, token);
|
||||||
|
|
||||||
@ -130,7 +131,11 @@ public class ChangeLogController : ControllerBase, IChangeLogApi
|
|||||||
|
|
||||||
[HttpGet("history")]
|
[HttpGet("history")]
|
||||||
[ProducesResponseType(typeof(IEnumerable<ChangeLogDto>), (int)HttpStatusCode.OK)]
|
[ProducesResponseType(typeof(IEnumerable<ChangeLogDto>), (int)HttpStatusCode.OK)]
|
||||||
public async Task<IActionResult> GetChangeLogForDate(Guid idDiscriminator, DateTimeOffset dateBegin, DateTimeOffset dateEnd, CancellationToken token)
|
public async Task<IActionResult> GetChangeLogForDate(
|
||||||
|
Guid idDiscriminator,
|
||||||
|
DateTimeOffset dateBegin,
|
||||||
|
DateTimeOffset dateEnd,
|
||||||
|
CancellationToken token = default)
|
||||||
{
|
{
|
||||||
var result = await repository.GetChangeLogForDate(idDiscriminator, dateBegin, dateEnd, token);
|
var result = await repository.GetChangeLogForDate(idDiscriminator, dateBegin, dateEnd, token);
|
||||||
|
|
||||||
@ -139,7 +144,7 @@ public class ChangeLogController : ControllerBase, IChangeLogApi
|
|||||||
|
|
||||||
[HttpGet("datesChange")]
|
[HttpGet("datesChange")]
|
||||||
[ProducesResponseType(typeof(IEnumerable<DateOnly>), (int)HttpStatusCode.OK)]
|
[ProducesResponseType(typeof(IEnumerable<DateOnly>), (int)HttpStatusCode.OK)]
|
||||||
public async Task<IActionResult> GetDatesChange(Guid idDiscriminator, CancellationToken token)
|
public async Task<IActionResult> GetDatesChange(Guid idDiscriminator, CancellationToken token = default)
|
||||||
{
|
{
|
||||||
var result = await repository.GetDatesChange(idDiscriminator, token);
|
var result = await repository.GetDatesChange(idDiscriminator, token);
|
||||||
|
|
||||||
@ -157,10 +162,13 @@ public class ChangeLogController : ControllerBase, IChangeLogApi
|
|||||||
|
|
||||||
[HttpGet("datesRange")]
|
[HttpGet("datesRange")]
|
||||||
[ProducesResponseType(typeof(DatesRangeDto), (int)HttpStatusCode.OK)]
|
[ProducesResponseType(typeof(DatesRangeDto), (int)HttpStatusCode.OK)]
|
||||||
public async Task<IActionResult> GetDatesRangeAsync(Guid idDiscriminator, CancellationToken token)
|
public async Task<IActionResult> GetDatesRangeAsync(Guid idDiscriminator, CancellationToken token = default)
|
||||||
{
|
{
|
||||||
var result = await repository.GetDatesRange(idDiscriminator, token);
|
var result = await repository.GetDatesRange(idDiscriminator, token);
|
||||||
|
|
||||||
|
if(result is null)
|
||||||
|
return NoContent();
|
||||||
|
|
||||||
return Ok(result);
|
return Ok(result);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,12 +1,10 @@
|
|||||||
using System.Security.Claims;
|
|
||||||
using System.Text.Json.Nodes;
|
|
||||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
|
||||||
using Microsoft.IdentityModel.Tokens;
|
using Microsoft.IdentityModel.Tokens;
|
||||||
using Microsoft.OpenApi.Any;
|
using Microsoft.OpenApi.Any;
|
||||||
using Microsoft.OpenApi.Models;
|
using Microsoft.OpenApi.Models;
|
||||||
using Persistence.Models.Configurations;
|
using Persistence.Models.Configurations;
|
||||||
using Swashbuckle.AspNetCore.SwaggerGen;
|
using Swashbuckle.AspNetCore.SwaggerGen;
|
||||||
|
using System.Text.Json.Nodes;
|
||||||
|
|
||||||
namespace Persistence.API;
|
namespace Persistence.API;
|
||||||
|
|
||||||
@ -35,169 +33,163 @@ public static class DependencyInjection
|
|||||||
|
|
||||||
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Persistence web api", Version = "v1" });
|
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Persistence web api", Version = "v1" });
|
||||||
|
|
||||||
var needUseKeyCloak = configuration.GetSection("NeedUseKeyCloak").Get<bool>();
|
var needUseKeyCloak = configuration.GetSection("NeedUseKeyCloak").Get<bool>();
|
||||||
if (needUseKeyCloak)
|
if (needUseKeyCloak)
|
||||||
c.AddKeycloackSecurity(configuration);
|
c.AddKeycloackSecurity(configuration);
|
||||||
else c.AddDefaultSecurity(configuration);
|
else c.AddDefaultSecurity(configuration);
|
||||||
|
|
||||||
//var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
|
//var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
|
||||||
//var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
|
//var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
|
||||||
//var includeControllerXmlComment = true;
|
//var includeControllerXmlComment = true;
|
||||||
//options.IncludeXmlComments(xmlPath, includeControllerXmlComment);
|
//c.IncludeXmlComments(xmlPath, includeControllerXmlComment);
|
||||||
//options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "AsbCloudApp.xml"), includeControllerXmlComment);
|
//c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "AsbCloudApp.xml"), includeControllerXmlComment);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
#region Authentication
|
#region Authentication
|
||||||
public static void AddJWTAuthentication(this IServiceCollection services, IConfiguration configuration)
|
public static void AddJWTAuthentication(this IServiceCollection services, IConfiguration configuration)
|
||||||
{
|
{
|
||||||
var needUseKeyCloak = configuration
|
var needUseKeyCloak = configuration
|
||||||
.GetSection("NeedUseKeyCloak")
|
.GetSection("NeedUseKeyCloak")
|
||||||
.Get<bool>();
|
.Get<bool>();
|
||||||
if (needUseKeyCloak)
|
if (needUseKeyCloak)
|
||||||
services.AddKeyCloakAuthentication(configuration);
|
services.AddKeyCloakAuthentication(configuration);
|
||||||
else services.AddDefaultAuthentication(configuration);
|
else services.AddDefaultAuthentication(configuration);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void AddKeyCloakAuthentication(this IServiceCollection services, IConfiguration configuration)
|
private static void AddKeyCloakAuthentication(this IServiceCollection services, IConfiguration configuration)
|
||||||
{
|
{
|
||||||
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||||
.AddJwtBearer(options =>
|
.AddJwtBearer(options =>
|
||||||
{
|
{
|
||||||
options.RequireHttpsMetadata = false;
|
options.RequireHttpsMetadata = false;
|
||||||
options.Audience = configuration["Authentication:Audience"];
|
options.Audience = configuration["Authentication:Audience"];
|
||||||
options.MetadataAddress = configuration["Authentication:MetadataAddress"]!;
|
options.MetadataAddress = configuration["Authentication:MetadataAddress"]!;
|
||||||
options.TokenValidationParameters = new TokenValidationParameters
|
options.TokenValidationParameters = new TokenValidationParameters
|
||||||
{
|
{
|
||||||
ValidIssuer = configuration["Authentication:ValidIssuer"],
|
ValidIssuer = configuration["Authentication:ValidIssuer"],
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void AddDefaultAuthentication(this IServiceCollection services, IConfiguration configuration)
|
private static void AddDefaultAuthentication(this IServiceCollection services, IConfiguration configuration)
|
||||||
{
|
{
|
||||||
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||||
.AddJwtBearer(options =>
|
.AddJwtBearer(options =>
|
||||||
{
|
{
|
||||||
options.RequireHttpsMetadata = false;
|
options.RequireHttpsMetadata = false;
|
||||||
options.TokenValidationParameters = new TokenValidationParameters
|
options.TokenValidationParameters = new TokenValidationParameters
|
||||||
{
|
{
|
||||||
ValidateIssuer = true,
|
ValidateIssuer = true,
|
||||||
ValidIssuer = JwtParams.Issuer,
|
ValidIssuer = JwtParams.Issuer,
|
||||||
ValidateAudience = true,
|
ValidateAudience = true,
|
||||||
ValidAudience = JwtParams.Audience,
|
ValidAudience = JwtParams.Audience,
|
||||||
ValidateLifetime = true,
|
ValidateLifetime = true,
|
||||||
IssuerSigningKey = JwtParams.SecurityKey,
|
IssuerSigningKey = JwtParams.SecurityKey,
|
||||||
ValidateIssuerSigningKey = false,
|
ValidateIssuerSigningKey = false,
|
||||||
};
|
};
|
||||||
options.Events = new JwtBearerEvents
|
options.Events = new JwtBearerEvents
|
||||||
{
|
{
|
||||||
OnMessageReceived = context =>
|
OnMessageReceived = context =>
|
||||||
{
|
{
|
||||||
var accessToken = context.Request.Headers["Authorization"]
|
var accessToken = context.Request.Headers["Authorization"]
|
||||||
.ToString()
|
.ToString()
|
||||||
.Replace(JwtBearerDefaults.AuthenticationScheme, string.Empty)
|
.Replace(JwtBearerDefaults.AuthenticationScheme, string.Empty)
|
||||||
.Trim();
|
.Trim();
|
||||||
|
|
||||||
context.Token = accessToken;
|
context.Token = accessToken;
|
||||||
|
|
||||||
return Task.CompletedTask;
|
return Task.CompletedTask;
|
||||||
},
|
},
|
||||||
OnTokenValidated = context =>
|
OnTokenValidated = context =>
|
||||||
{
|
{
|
||||||
if(context.Principal != null && context.Principal.HasClaim(x => x.Type != ClaimTypes.NameIdentifier))
|
var username = context.Principal?.Claims
|
||||||
{
|
.FirstOrDefault(e => e.Type == "username")?.Value;
|
||||||
var claim = new Claim(ClaimTypes.NameIdentifier.ToString(), Guid.NewGuid().ToString());
|
|
||||||
(context.Principal.Identity as ClaimsIdentity)!.AddClaim(claim);
|
var password = context.Principal?.Claims
|
||||||
|
.FirstOrDefault(e => e.Type == "password")?.Value;
|
||||||
|
|
||||||
|
var keyCloakUser = configuration
|
||||||
|
.GetSection(nameof(AuthUser))
|
||||||
|
.Get<AuthUser>()!;
|
||||||
|
|
||||||
|
if (username != keyCloakUser.Username || password != keyCloakUser.Password)
|
||||||
|
{
|
||||||
|
context.Fail("username or password did not match");
|
||||||
}
|
}
|
||||||
|
|
||||||
var username = context.Principal?.Claims
|
return Task.CompletedTask;
|
||||||
.FirstOrDefault(e => e.Type == "username")?.Value;
|
}
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
#endregion
|
||||||
|
|
||||||
var password = context.Principal?.Claims
|
#region Security (Swagger)
|
||||||
.FirstOrDefault(e => e.Type == "password")?.Value;
|
private static void AddKeycloackSecurity(this SwaggerGenOptions options, IConfiguration configuration)
|
||||||
|
{
|
||||||
|
options.AddSecurityDefinition("Keycloack", new OpenApiSecurityScheme
|
||||||
|
{
|
||||||
|
Description = @"JWT Authorization header using the Bearer scheme. Enter 'Bearer' [space] and then your token in the text input below. Example: 'Bearer 12345abcdef'",
|
||||||
|
Name = "Authorization",
|
||||||
|
In = ParameterLocation.Header,
|
||||||
|
Type = SecuritySchemeType.OAuth2,
|
||||||
|
Flows = new OpenApiOAuthFlows
|
||||||
|
{
|
||||||
|
Implicit = new OpenApiOAuthFlow
|
||||||
|
{
|
||||||
|
AuthorizationUrl = new Uri(configuration["Authentication:AuthorizationUrl"]),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
var keyCloakUser = configuration
|
options.AddSecurityRequirement(new OpenApiSecurityRequirement()
|
||||||
.GetSection(nameof(AuthUser))
|
{
|
||||||
.Get<AuthUser>()!;
|
{
|
||||||
|
new OpenApiSecurityScheme
|
||||||
|
{
|
||||||
|
Reference = new OpenApiReference
|
||||||
|
{
|
||||||
|
Type = ReferenceType.SecurityScheme,
|
||||||
|
Id = "Keycloack"
|
||||||
|
},
|
||||||
|
Scheme = "Bearer",
|
||||||
|
Name = "Bearer",
|
||||||
|
In = ParameterLocation.Header,
|
||||||
|
},
|
||||||
|
new List<string>()
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
if (username != keyCloakUser.Username || password != keyCloakUser.Password)
|
private static void AddDefaultSecurity(this SwaggerGenOptions options, IConfiguration configuration)
|
||||||
{
|
{
|
||||||
context.Fail("username or password did not match");
|
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
|
||||||
}
|
{
|
||||||
|
Description = @"JWT Authorization header using the Bearer scheme. Enter 'Bearer' [space] and then your token in the text input below. Example: 'Bearer 12345abcdef'",
|
||||||
|
Name = "Authorization",
|
||||||
|
In = ParameterLocation.Header,
|
||||||
|
Type = SecuritySchemeType.ApiKey,
|
||||||
|
Scheme = "Bearer",
|
||||||
|
});
|
||||||
|
|
||||||
return Task.CompletedTask;
|
options.AddSecurityRequirement(new OpenApiSecurityRequirement()
|
||||||
}
|
{
|
||||||
};
|
{
|
||||||
});
|
new OpenApiSecurityScheme
|
||||||
}
|
{
|
||||||
#endregion
|
Reference = new OpenApiReference
|
||||||
|
{
|
||||||
#region Security (Swagger)
|
Type = ReferenceType.SecurityScheme,
|
||||||
private static void AddKeycloackSecurity(this SwaggerGenOptions options, IConfiguration configuration)
|
Id = "Bearer"
|
||||||
{
|
},
|
||||||
options.AddSecurityDefinition("Keycloack", new OpenApiSecurityScheme
|
Scheme = "oauth2",
|
||||||
{
|
Name = "Bearer",
|
||||||
Description = @"JWT Authorization header using the Bearer scheme. Enter 'Bearer' [space] and then your token in the text input below. Example: 'Bearer 12345abcdef'",
|
In = ParameterLocation.Header,
|
||||||
Name = "Authorization",
|
},
|
||||||
In = ParameterLocation.Header,
|
new List<string>()
|
||||||
Type = SecuritySchemeType.OAuth2,
|
}
|
||||||
Flows = new OpenApiOAuthFlows
|
});
|
||||||
{
|
}
|
||||||
Implicit = new OpenApiOAuthFlow
|
#endregion
|
||||||
{
|
|
||||||
AuthorizationUrl = new Uri(configuration["Authentication:AuthorizationUrl"]),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
options.AddSecurityRequirement(new OpenApiSecurityRequirement()
|
|
||||||
{
|
|
||||||
{
|
|
||||||
new OpenApiSecurityScheme
|
|
||||||
{
|
|
||||||
Reference = new OpenApiReference
|
|
||||||
{
|
|
||||||
Type = ReferenceType.SecurityScheme,
|
|
||||||
Id = "Keycloack"
|
|
||||||
},
|
|
||||||
Scheme = "Bearer",
|
|
||||||
Name = "Bearer",
|
|
||||||
In = ParameterLocation.Header,
|
|
||||||
},
|
|
||||||
new List<string>()
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void AddDefaultSecurity(this SwaggerGenOptions options, IConfiguration configuration)
|
|
||||||
{
|
|
||||||
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
|
|
||||||
{
|
|
||||||
Description = @"JWT Authorization header using the Bearer scheme. Enter 'Bearer' [space] and then your token in the text input below. Example: 'Bearer 12345abcdef'",
|
|
||||||
Name = "Authorization",
|
|
||||||
In = ParameterLocation.Header,
|
|
||||||
Type = SecuritySchemeType.ApiKey,
|
|
||||||
Scheme = "Bearer",
|
|
||||||
});
|
|
||||||
|
|
||||||
options.AddSecurityRequirement(new OpenApiSecurityRequirement()
|
|
||||||
{
|
|
||||||
{
|
|
||||||
new OpenApiSecurityScheme
|
|
||||||
{
|
|
||||||
Reference = new OpenApiReference
|
|
||||||
{
|
|
||||||
Type = ReferenceType.SecurityScheme,
|
|
||||||
Id = "Bearer"
|
|
||||||
},
|
|
||||||
Scheme = "oauth2",
|
|
||||||
Name = "Bearer",
|
|
||||||
In = ParameterLocation.Header,
|
|
||||||
},
|
|
||||||
new List<string>()
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
#endregion
|
|
||||||
}
|
}
|
||||||
|
@ -11,12 +11,8 @@ public static class DependencyInjection
|
|||||||
{
|
{
|
||||||
string connectionStringName = "DefaultConnection";
|
string connectionStringName = "DefaultConnection";
|
||||||
|
|
||||||
services.AddDbContext<PersistenceDbContext>(options =>
|
services.AddDbContext<PersistenceDbContext>(options =>
|
||||||
{
|
options.UseNpgsql(configuration.GetConnectionString(connectionStringName)));
|
||||||
var dataSourceBuilder = new NpgsqlDataSourceBuilder(configuration.GetConnectionString(connectionStringName));
|
|
||||||
dataSourceBuilder.EnableDynamicJson();
|
|
||||||
options.UseNpgsql(dataSourceBuilder.Build());
|
|
||||||
});
|
|
||||||
|
|
||||||
services.AddScoped<DbContext>(provider => provider.GetRequiredService<PersistenceDbContext>());
|
services.AddScoped<DbContext>(provider => provider.GetRequiredService<PersistenceDbContext>());
|
||||||
|
|
||||||
|
@ -78,39 +78,46 @@ public class ChangeLogControllerTest : BaseIntegrationTest
|
|||||||
var idDiscriminator = Guid.NewGuid();
|
var idDiscriminator = Guid.NewGuid();
|
||||||
var dtos = Generate(1, DateTimeOffset.UtcNow);
|
var dtos = Generate(1, DateTimeOffset.UtcNow);
|
||||||
var dto = dtos.FirstOrDefault()!;
|
var dto = dtos.FirstOrDefault()!;
|
||||||
var entity = dto.Adapt<ChangeLog>();
|
var result = await client.Add(idDiscriminator, dto);
|
||||||
dbContext.ChangeLog.Add(entity);
|
Assert.Equal(HttpStatusCode.OK, result.StatusCode);
|
||||||
dbContext.SaveChanges();
|
|
||||||
|
|
||||||
dto.Id = entity.Id;
|
var entity = dbContext.ChangeLog
|
||||||
dto.DepthStart = dto.DepthStart + 10;
|
.Where(x => x.IdDiscriminator == idDiscriminator)
|
||||||
|
.FirstOrDefault();
|
||||||
|
dto = entity.Adapt<DataWithWellDepthAndSectionDto>();
|
||||||
dto.DepthEnd = dto.DepthEnd + 10;
|
dto.DepthEnd = dto.DepthEnd + 10;
|
||||||
|
|
||||||
// act
|
// act
|
||||||
var result = await client.Update(idDiscriminator, dto);
|
result = await client.Update(idDiscriminator, dto);
|
||||||
|
|
||||||
// assert
|
// assert
|
||||||
Assert.Equal(HttpStatusCode.OK, result.StatusCode);
|
Assert.Equal(HttpStatusCode.OK, result.StatusCode);
|
||||||
Assert.Equal(2, result.Content);
|
Assert.Equal(2, result.Content);
|
||||||
|
|
||||||
//var entities = dbContext.ChangeLog
|
var dateBegin = DateTimeOffset.UtcNow.AddDays(-1);
|
||||||
// .Where(e => e.IdDiscriminator == idDiscriminator)
|
var dateEnd = DateTimeOffset.UtcNow.AddDays(1);
|
||||||
// .ToArray();
|
|
||||||
//var obsoleteEntity = entities
|
|
||||||
// .Where(e => e.Obsolete.HasValue)
|
|
||||||
// .FirstOrDefault();
|
|
||||||
|
|
||||||
//var activeEntity = entities
|
var changeLogResult = await client.GetChangeLogForDate(idDiscriminator, dateBegin, dateEnd);
|
||||||
// .Where(e => !e.Obsolete.HasValue)
|
Assert.Equal(HttpStatusCode.OK, changeLogResult.StatusCode);
|
||||||
// .FirstOrDefault();
|
Assert.NotNull(changeLogResult.Content);
|
||||||
|
|
||||||
//if (obsoleteEntity == null || activeEntity == null)
|
var changeLogDtos = changeLogResult.Content;
|
||||||
//{
|
|
||||||
// Assert.Fail();
|
|
||||||
// return;
|
|
||||||
//}
|
|
||||||
|
|
||||||
//Assert.Equal(activeEntity.IdNext, obsoleteEntity.Id);
|
var obsoleteDto = changeLogDtos
|
||||||
|
.Where(e => e.Obsolete.HasValue)
|
||||||
|
.FirstOrDefault();
|
||||||
|
|
||||||
|
var activeDto = changeLogDtos
|
||||||
|
.Where(e => !e.Obsolete.HasValue)
|
||||||
|
.FirstOrDefault();
|
||||||
|
|
||||||
|
if (obsoleteDto == null || activeDto == null)
|
||||||
|
{
|
||||||
|
Assert.Fail();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.Equal(activeDto.Id, obsoleteDto.IdNext);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -185,11 +192,7 @@ public class ChangeLogControllerTest : BaseIntegrationTest
|
|||||||
// arrange
|
// arrange
|
||||||
var changeLogItems = CreateChangeLogItems(3, (-15, 15));
|
var changeLogItems = CreateChangeLogItems(3, (-15, 15));
|
||||||
var idDiscriminator = changeLogItems.Item1;
|
var idDiscriminator = changeLogItems.Item1;
|
||||||
var entities = changeLogItems.Item2;
|
var entities = changeLogItems.Item2.OrderBy(e => e.Creation);
|
||||||
|
|
||||||
var orderedEntities = entities.OrderBy(e => e.Creation);
|
|
||||||
var minDate = orderedEntities.First().Creation;
|
|
||||||
var maxDate = orderedEntities.Last().Creation;
|
|
||||||
|
|
||||||
// act
|
// act
|
||||||
var result = await client.GetDatesRange(idDiscriminator);
|
var result = await client.GetDatesRange(idDiscriminator);
|
||||||
@ -198,12 +201,15 @@ public class ChangeLogControllerTest : BaseIntegrationTest
|
|||||||
Assert.Equal(HttpStatusCode.OK, result.StatusCode);
|
Assert.Equal(HttpStatusCode.OK, result.StatusCode);
|
||||||
Assert.NotNull(result.Content);
|
Assert.NotNull(result.Content);
|
||||||
|
|
||||||
|
var minDate = entities.First().Creation;
|
||||||
|
var maxDate = entities.Last().Creation;
|
||||||
|
|
||||||
var expectedMinDate = minDate.ToUniversalTime().ToString();
|
var expectedMinDate = minDate.ToUniversalTime().ToString();
|
||||||
var actualMinDate = result.Content!.From.ToUniversalTime().ToString();
|
var actualMinDate = result.Content.From.ToUniversalTime().ToString();
|
||||||
Assert.Equal(expectedMinDate, actualMinDate);
|
Assert.Equal(expectedMinDate, actualMinDate);
|
||||||
|
|
||||||
var expectedMaxDate = maxDate.ToUniversalTime().ToString();
|
var expectedMaxDate = maxDate.ToUniversalTime().ToString();
|
||||||
var actualMaxDate = result.Content!.To.ToUniversalTime().ToString();
|
var actualMaxDate = result.Content.To.ToUniversalTime().ToString();
|
||||||
Assert.Equal(expectedMaxDate, actualMaxDate);
|
Assert.Equal(expectedMaxDate, actualMaxDate);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -232,11 +232,6 @@ public class ChangeLogRepository : IChangeLogRepository
|
|||||||
return datesOnly;
|
return datesOnly;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Task<IEnumerable<IDictionary<string, object>>> GetGtDate(DateTimeOffset dateBegin, CancellationToken token)
|
|
||||||
{
|
|
||||||
throw new NotImplementedException();
|
|
||||||
}
|
|
||||||
|
|
||||||
private ChangeLog CreateEntityFromDto(Guid idUser, Guid idDiscriminator, DataWithWellDepthAndSectionDto dto)
|
private ChangeLog CreateEntityFromDto(Guid idUser, Guid idDiscriminator, DataWithWellDepthAndSectionDto dto)
|
||||||
{
|
{
|
||||||
var entity = new ChangeLog()
|
var entity = new ChangeLog()
|
||||||
@ -273,17 +268,25 @@ public class ChangeLogRepository : IChangeLogRepository
|
|||||||
public async Task<DatesRangeDto?> GetDatesRange(Guid idDiscriminator, CancellationToken token)
|
public async Task<DatesRangeDto?> GetDatesRange(Guid idDiscriminator, CancellationToken token)
|
||||||
{
|
{
|
||||||
var query = db.Set<ChangeLog>()
|
var query = db.Set<ChangeLog>()
|
||||||
.Where(e => e.IdDiscriminator == idDiscriminator);
|
.Where(e => e.IdDiscriminator == idDiscriminator)
|
||||||
var test = db.Set<ChangeLog>().ToArray();
|
.GroupBy(e => 1)
|
||||||
var test2 = query.ToArray();
|
.Select(group => new
|
||||||
|
{
|
||||||
|
Min = group.Min(e => e.Creation),
|
||||||
|
Max = group.Max(e => e.Creation),
|
||||||
|
});
|
||||||
|
|
||||||
var minDate = await query.MinAsync(o => o.Creation, token);
|
var values = await query.FirstOrDefaultAsync(token);
|
||||||
var maxDate = await query.MaxAsync(o => o.Creation, token);
|
|
||||||
|
if(values is null)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
return new DatesRangeDto
|
return new DatesRangeDto
|
||||||
{
|
{
|
||||||
From = minDate,
|
From = values.Min,
|
||||||
To = maxDate
|
To = values.Max,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -10,6 +10,11 @@ public class ChangeLogDto
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Ключ записи
|
||||||
|
/// </summary>
|
||||||
|
public Guid Id { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Создатель записи
|
/// Создатель записи
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@ -38,5 +43,5 @@ public class ChangeLogDto
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Объект записи
|
/// Объект записи
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public DataWithWellDepthAndSectionDto Value { get; set; }
|
public DataWithWellDepthAndSectionDto Value { get; set; } = default!;
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user