WebApi + ClientApp, GraphQL, Reflection
This commit is contained in:
6
Events-WebApi/Events.WebAPI/Constants.cs
Normal file
6
Events-WebApi/Events.WebAPI/Constants.cs
Normal file
@@ -0,0 +1,6 @@
|
||||
namespace Events.WebAPI;
|
||||
|
||||
public class Constants
|
||||
{
|
||||
public static string ApiVersion => "1.0.0";
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
using Events.WebAPI.Contract.DTOs;
|
||||
using Events.WebAPI.Controllers.Generic;
|
||||
|
||||
namespace Events.WebAPI.Controllers;
|
||||
|
||||
public class EventsController : CrudController<EventDTO, int>
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
using Events.WebAPI.Contract.Command;
|
||||
using Events.WebAPI.Contract.DTOs;
|
||||
using Events.WebAPI.Contract.Queries.Generic;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.JsonPatch;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using MobilityOne.Common.Commands;
|
||||
|
||||
namespace Events.WebAPI.Controllers.Generic;
|
||||
|
||||
|
||||
public abstract class CrudController<TDto, TPK> : GetController<TDto, TPK>
|
||||
where TDto : class, IHasIdAsPK<TPK>
|
||||
where TPK : IEquatable<TPK>
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new item.
|
||||
/// </summary>
|
||||
/// <param name="model">id does not have to be sent (if sent it would be ignored)</param>
|
||||
/// <param name="mediator"></param>
|
||||
/// <returns>A newly created item</returns>
|
||||
/// <response code="201">Returns the newly created item (route to the item, and the item in the body)</response>
|
||||
/// <response code="400">If the model is null or not valid</response>
|
||||
[HttpPost]
|
||||
[ProducesResponseType(StatusCodes.Status201Created)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[Authorize(Policy = nameof(Policies.EditData))]
|
||||
public virtual async Task<ActionResult<TDto>> Create(TDto model, [FromServices] IMediator mediator)
|
||||
{
|
||||
//Note: It never produce ActionResult<TDto> but we need this because of Swagger description
|
||||
//We cannot user generic type in attributes (i.e. in ProducesResponseType)
|
||||
//if successful it returns ActionResult with Value:null and Result:CreatedAtAction
|
||||
//Thus result.Result.Value is TDto
|
||||
|
||||
var command = new AddCommand<TDto, TPK>(model);
|
||||
TPK id = await mediator.Send(command);
|
||||
|
||||
var query = new GetSingleItemQuery<TDto, TPK>(id);
|
||||
|
||||
var item = await mediator.Send(query);
|
||||
var action = CreatedAtAction(nameof(Get), new { id }, item);
|
||||
|
||||
return action;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Update the item
|
||||
/// </summary>
|
||||
/// <param name="id"></param>
|
||||
/// <param name="model"></param>
|
||||
/// <param name="mediator"></param>
|
||||
/// <returns></returns>
|
||||
/// <response code="204">if the update was successful</response>
|
||||
/// <response code="404">if there is no item with sent id, or if a user does not have a permission to update the item</response>
|
||||
/// <response code="400">If the model is not valid</response>
|
||||
[HttpPut("{id}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[Authorize(Policy = nameof(Policies.EditData))]
|
||||
public virtual async Task<IActionResult> Update(TPK id, TDto model, [FromServices] IMediator mediator)
|
||||
{
|
||||
if (!model.Id.Equals(id)) //ModelState.IsValid & model != null checked automatically due to [ApiController]
|
||||
{
|
||||
return Problem(statusCode: StatusCodes.Status400BadRequest, detail: $"Different ids: {id} vs {model.Id}");
|
||||
}
|
||||
else
|
||||
{
|
||||
var query = new GetSingleItemQuery<TDto, TPK>(id);
|
||||
var item = await mediator.Send(query);
|
||||
if (item == null)
|
||||
{
|
||||
return Problem(statusCode: StatusCodes.Status404NotFound, detail: $"Invalid id = {id}");
|
||||
}
|
||||
|
||||
await DoUpdate(model, mediator);
|
||||
|
||||
return NoContent();
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task DoUpdate(TDto model, IMediator mediator)
|
||||
{
|
||||
var command = new UpdateCommand<TDto>(model);
|
||||
await mediator.Send(command);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Partially update the item
|
||||
/// </summary>
|
||||
/// <param name="id"></param>
|
||||
/// <param name="delta">RFC 6902 formatted json</param>
|
||||
/// <param name="mediator"></param>
|
||||
/// <returns></returns>
|
||||
/// <response code="204">if the update was successful</response>
|
||||
/// <response code="404">if there is no item with sent id, or if a user does not have a permission to update the item</response>
|
||||
/// <response code="400">If the patched model is not valid</response>
|
||||
[HttpPatch("{id}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[Authorize(Policy = nameof(Policies.EditData))]
|
||||
public virtual async Task<IActionResult> UpdatePartially(TPK id,
|
||||
JsonPatchDocument<TDto> delta,
|
||||
[FromServices] IMediator mediator)
|
||||
{
|
||||
//Get current DTO based on id (Get will also check for permission to run patch in contrast to direct retrieval)(
|
||||
var getResult = await base.Get(id, mediator);
|
||||
if (getResult.Value != null)
|
||||
{
|
||||
string problem = string.Empty;
|
||||
bool ok = true;
|
||||
TDto dto = getResult.Value;
|
||||
delta.ApplyTo(dto, patchError =>
|
||||
{
|
||||
ok = false;
|
||||
problem = $"{patchError.Operation} causing error: {patchError.ErrorMessage}";
|
||||
});
|
||||
if (ok)
|
||||
{
|
||||
if (!dto.Id.Equals(id)) //ensures that id has not been changed
|
||||
{
|
||||
problem = $"Id mismatch after patching {id} <> {dto.Id}";
|
||||
return Problem(detail: problem, statusCode: StatusCodes.Status400BadRequest);
|
||||
}
|
||||
else
|
||||
{
|
||||
await DoUpdate(dto, mediator);
|
||||
return NoContent();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
return Problem(detail: problem, statusCode: StatusCodes.Status400BadRequest);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
return getResult.Result;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Delete the item base on primary key value (id)
|
||||
/// </summary>
|
||||
/// <param name="id">Primary key value</param>
|
||||
/// <param name="mediator">Query/Command (Request) mediator. (Obtained using Dependency Injection from services)</param>
|
||||
/// <returns></returns>
|
||||
/// <response code="204">If the item is deleted</response>
|
||||
/// <response code="404">If the item with id does not exist</response>
|
||||
/// <response code="400">If the valiation exists, and fails</response>
|
||||
[HttpDelete("{id}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[Authorize(Policy = nameof(Policies.EditData))]
|
||||
public virtual async Task<IActionResult> Delete(TPK id, [FromServices] IMediator mediator)
|
||||
{
|
||||
var query = new GetSingleItemQuery<TDto, TPK>(id);
|
||||
var item = await mediator.Send(query);
|
||||
if (item == null)
|
||||
{
|
||||
return Problem(statusCode: StatusCodes.Status404NotFound, detail: $"Invalid id = {id}");
|
||||
}
|
||||
|
||||
var command = new DeleteCommand<TDto, TPK>(id);
|
||||
await mediator.Send(command);
|
||||
return NoContent();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
using AutoMapper;
|
||||
using Events.WebAPI.Contract.DTOs;
|
||||
using Events.WebAPI.Contract.Queries.Generic;
|
||||
using Events.WebAPI.Models;
|
||||
using Events.WebAPI.Util.Middleware;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Events.WebAPI.Controllers.Generic;
|
||||
|
||||
[Authorize(Policy = nameof(Policies.ReadData))]
|
||||
[ApiController]
|
||||
[Route("[controller]")]
|
||||
[TypeFilter(typeof(BadRequestOnRuleValidationException), Order = 20)]
|
||||
[TypeFilter(typeof(ProblemDetailsForSqlException), Order = 10)]
|
||||
[TypeFilter(typeof(ProblemDetailsForException), Order = 1)] //last one
|
||||
public abstract class GetController<TDto, TPK> : ControllerBase
|
||||
where TPK : IEquatable<TPK>
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// Get number of item satisfying filters
|
||||
/// </summary>
|
||||
/// <param name="filters">Each filter is like key(operator)value, using Sieve syntax</param>
|
||||
/// <param name="mediator"></param>
|
||||
/// <param name="mapper"></param>
|
||||
/// <returns></returns>
|
||||
[HttpGet(nameof(Count))]
|
||||
public virtual async Task<int> Count(string filters, [FromServices] IMediator mediator, [FromServices] IMapper mapper)
|
||||
{
|
||||
var countRequest = new GetCountQuery<TDto>
|
||||
{
|
||||
Filters = filters,
|
||||
};
|
||||
int count = await mediator.Send(countRequest);
|
||||
return count;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns single item based on primary key value
|
||||
/// </summary>
|
||||
/// <param name="id"></param>
|
||||
/// <param name="mediator"></param>
|
||||
/// <returns></returns>
|
||||
[HttpGet("{id}")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public virtual async Task<ActionResult<TDto>> Get(TPK id, [FromServices] IMediator mediator)
|
||||
{
|
||||
var query = new GetSingleItemQuery<TDto, TPK>(id);
|
||||
var item = await mediator.Send(query);
|
||||
return item != null ? item : Problem(statusCode: StatusCodes.Status404NotFound, detail: $"No data for id = {id}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get all items based on (lazy) load parameters (paging, sorting, and filtering)
|
||||
/// </summary>
|
||||
/// <param name="loadParams"></param>
|
||||
/// <param name="mediator"></param>
|
||||
/// <param name="mapper"></param>
|
||||
/// <returns></returns>
|
||||
[HttpGet]
|
||||
public virtual async Task<Items<TDto>> GetAll([FromQuery] LoadParams loadParams, [FromServices] IMediator mediator, [FromServices] IMapper mapper)
|
||||
{
|
||||
loadParams ??= new();
|
||||
var result = new Items<TDto>();
|
||||
var countRequest = new GetCountQuery<TDto>
|
||||
{
|
||||
Filters = loadParams.Filters
|
||||
};
|
||||
result.Count = await mediator.Send(countRequest);
|
||||
|
||||
if (result.Count > 0)
|
||||
{
|
||||
var dataRequest = new GetItemsQuery<TDto>
|
||||
{
|
||||
Filters = loadParams.Filters,
|
||||
Sort = loadParams.Sort,
|
||||
Page = loadParams.Page,
|
||||
PageSize = loadParams.PageSize,
|
||||
Ascending = loadParams.Ascending
|
||||
};
|
||||
|
||||
result.Data = await mediator.Send(dataRequest);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
31
Events-WebApi/Events.WebAPI/Controllers/LookupController.cs
Normal file
31
Events-WebApi/Events.WebAPI/Controllers/LookupController.cs
Normal file
@@ -0,0 +1,31 @@
|
||||
using Events.WebAPI.Contract.DTOs;
|
||||
using Events.WebAPI.Contract.LookupQueries;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Events.WebAPI.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("[controller]/[action]")]
|
||||
public class LookupController : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
public async Task<ActionResult<List<IdName<string>>>> Countries(string? text, [FromServices] IMediator mediator)
|
||||
{
|
||||
var countries = await mediator.Send(new LookupCountryQuery { Text = text });
|
||||
return countries;
|
||||
}
|
||||
|
||||
[Authorize(Policy = nameof(Policies.ReadData))]
|
||||
[HttpGet]
|
||||
public async Task<ActionResult<List<IdName<int>>>> People(string? text, string? countryCode, [FromServices] IMediator mediator)
|
||||
{
|
||||
var people = await mediator.Send(new LookupPeopleQuery
|
||||
{
|
||||
Text = text,
|
||||
CountryCode = countryCode
|
||||
});
|
||||
return people;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
using Events.WebAPI.Contract.DTOs;
|
||||
using Events.WebAPI.Controllers.Generic;
|
||||
|
||||
namespace Events.WebAPI.Controllers;
|
||||
|
||||
public class PeopleController : CrudController<PersonDTO, int>
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
using Events.WebAPI.Contract.DTOs;
|
||||
using Events.WebAPI.Controllers.Generic;
|
||||
|
||||
namespace Events.WebAPI.Controllers;
|
||||
|
||||
public class RegistrationsController : CrudController<RegistrationDTO, int>
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
using Events.WebAPI.Contract.DTOs;
|
||||
using Events.WebAPI.Controllers.Generic;
|
||||
|
||||
namespace Events.WebAPI.Controllers;
|
||||
|
||||
public class SportsController : CrudController<SportDTO, int>
|
||||
{
|
||||
}
|
||||
32
Events-WebApi/Events.WebAPI/Events.WebAPI.csproj
Normal file
32
Events-WebApi/Events.WebAPI/Events.WebAPI.csproj
Normal file
@@ -0,0 +1,32 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<GenerateDocumentationFile>true</GenerateDocumentationFile>
|
||||
<NoWarn>1701;1702;1591</NoWarn>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<UserSecretsId>PI</UserSecretsId>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="12.1.1" />
|
||||
<PackageReference Include="MassTransit.RabbitMQ" Version="8.5.9" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.7" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.JsonPatch" Version="10.0.7" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="10.0.7" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="10.1.7" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Events.WebAPI.Contract\Events.WebAPI.Contract.csproj" />
|
||||
<ProjectReference Include="..\Events.WebAPI.Handlers.EF\Events.WebAPI.Handlers.EF.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
34
Events-WebApi/Events.WebAPI/Models/LoadParams.cs
Normal file
34
Events-WebApi/Events.WebAPI/Models/LoadParams.cs
Normal file
@@ -0,0 +1,34 @@
|
||||
using Microsoft.AspNetCore.Mvc.ModelBinding;
|
||||
|
||||
namespace Events.WebAPI.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Map lazy loading parameters (e.g. from PrimeNG table)
|
||||
/// </summary>
|
||||
public class LoadParams
|
||||
{
|
||||
/// <summary>
|
||||
/// Page to load
|
||||
/// </summary>
|
||||
public int Page { get; set; } = 1;
|
||||
/// <summary>
|
||||
/// Number of elements to return
|
||||
/// </summary>
|
||||
public int? PageSize { get; set; }
|
||||
/// <summary>
|
||||
/// Name of a column. Must be same as in corresponding DTO object, case insensitive
|
||||
/// In case of multiple columns, separated them with comma and without spaces
|
||||
/// </summary>
|
||||
public string? Sort { get; set; }
|
||||
/// <summary>
|
||||
/// 1 ascending, -1 descending
|
||||
/// </summary>
|
||||
public int? SortOrder { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Sieve style filter string
|
||||
/// </summary>
|
||||
public string? Filters { get; set; }
|
||||
|
||||
[BindNever] public bool Ascending => SortOrder == null || SortOrder != -1;
|
||||
}
|
||||
31
Events-WebApi/Events.WebAPI/Policies.cs
Normal file
31
Events-WebApi/Events.WebAPI/Policies.cs
Normal file
@@ -0,0 +1,31 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
|
||||
namespace Events.WebAPI;
|
||||
|
||||
public class Policies
|
||||
{
|
||||
public static IEnumerable<KeyValuePair<string, Action<AuthorizationPolicyBuilder>>> All
|
||||
{
|
||||
get
|
||||
{
|
||||
yield return new KeyValuePair<string, Action<AuthorizationPolicyBuilder>>(nameof(ReadData), ReadData);
|
||||
yield return new KeyValuePair<string, Action<AuthorizationPolicyBuilder>>(nameof(EditData), EditData);
|
||||
}
|
||||
}
|
||||
|
||||
public static Action<AuthorizationPolicyBuilder> ReadData
|
||||
{
|
||||
get
|
||||
{
|
||||
return policy => policy.RequireClaim("scope", "events:read");
|
||||
}
|
||||
}
|
||||
|
||||
public static Action<AuthorizationPolicyBuilder> EditData
|
||||
{
|
||||
get
|
||||
{
|
||||
return policy => policy.RequireClaim("scope", "events:write");
|
||||
}
|
||||
}
|
||||
}
|
||||
5
Events-WebApi/Events.WebAPI/Program.Testing.cs
Normal file
5
Events-WebApi/Events.WebAPI/Program.Testing.cs
Normal file
@@ -0,0 +1,5 @@
|
||||
namespace Events.WebAPI;
|
||||
|
||||
public partial class Program
|
||||
{
|
||||
}
|
||||
84
Events-WebApi/Events.WebAPI/Program.cs
Normal file
84
Events-WebApi/Events.WebAPI/Program.cs
Normal file
@@ -0,0 +1,84 @@
|
||||
using System.Reflection;
|
||||
using AutoMapper;
|
||||
using Events.WebAPI;
|
||||
using Events.WebAPI.Contract.Validation.Sport;
|
||||
using Events.WebAPI.Contract.Validation;
|
||||
using Events.WebAPI.Handlers.EF.Mappings;
|
||||
using Events.WebAPI.Handlers.EF.QueryHandlers;
|
||||
using Events.WebAPI.Handlers.EF.Data.Postgres;
|
||||
using Events.WebAPI.Util.Extensions;
|
||||
using Events.WebAPI.Util.Startup;
|
||||
using Events.WebAPI.Util.Swagger;
|
||||
using Events.WebAPI.Util.Validation;
|
||||
using FluentValidation;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.OpenApi;
|
||||
using Sieve.Models;
|
||||
using Sieve.Services;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
builder.Services
|
||||
.AddControllers(options => options.AddJsonPatchSupport())
|
||||
.AddJsonOptions(configure => configure.JsonSerializerOptions.PropertyNamingPolicy = null);
|
||||
|
||||
builder.Services.AddDbContext<EventsContext>(options =>
|
||||
options.UseNpgsql(builder.Configuration.GetConnectionString("EventDB")));
|
||||
|
||||
builder.Services.Configure<SieveOptions>(builder.Configuration.GetSection("Sieve"));
|
||||
builder.Services.AddScoped<ISieveProcessor, SieveProcessor>();
|
||||
builder.Services.AddScoped<IValidationMessageProvider, ValidationMessageProvider>();
|
||||
|
||||
builder.Services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehaviour<,>));
|
||||
builder.Services.AddValidatorsFromAssemblyContaining(typeof(AddSportValidator));
|
||||
builder.Services.AddMediatR(cfg => {
|
||||
cfg.RegisterServicesFromAssembly(typeof(SportsQueryHandler).Assembly);
|
||||
});
|
||||
|
||||
builder.Services.SetupMassTransit(builder.Configuration);
|
||||
builder.Services.SetupAuthenticationAndAuthorization(builder.Configuration);
|
||||
|
||||
#region AutoMapper settings
|
||||
Action<IServiceProvider, IMapperConfigurationExpression> mapperConfigAction = (serviceProvider, cfg) =>
|
||||
{
|
||||
cfg.ConstructServicesUsing(serviceProvider.GetService);
|
||||
};
|
||||
builder.Services.AddAutoMapper(mapperConfigAction, typeof(EFMappingProfile)); //assemblies containing mapping profiles
|
||||
#endregion
|
||||
|
||||
builder.Services.AddSwaggerGen(c =>
|
||||
{
|
||||
c.SwaggerDoc(Constants.ApiVersion, new OpenApiInfo { Title = "Events API", Version = Constants.ApiVersion });
|
||||
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
|
||||
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
|
||||
if (File.Exists(xmlPath))
|
||||
c.IncludeXmlComments(xmlPath);
|
||||
c.AddBearerTokenScheme();
|
||||
});
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI(c =>
|
||||
{
|
||||
c.RoutePrefix = "docs";
|
||||
c.DocumentTitle = "Events WebApi";
|
||||
c.SwaggerEndpoint($"../swagger/{Constants.ApiVersion}/swagger.json", "Events WebAPI");
|
||||
});
|
||||
|
||||
app.UseRouting();
|
||||
|
||||
app.UseCors(builder =>
|
||||
{
|
||||
builder
|
||||
.AllowAnyOrigin()
|
||||
.AllowAnyMethod()
|
||||
.AllowAnyHeader()
|
||||
.WithExposedHeaders("Token-Expired", "Content-Disposition");
|
||||
});
|
||||
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
|
||||
app.MapControllers();
|
||||
app.Run();
|
||||
14
Events-WebApi/Events.WebAPI/Properties/launchSettings.json
Normal file
14
Events-WebApi/Events.WebAPI/Properties/launchSettings.json
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"$schema": "http://json.schemastore.org/launchsettings.json",
|
||||
"profiles": {
|
||||
"https": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": true,
|
||||
"applicationUrl": "https://localhost:7295",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Formatters;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Events.WebAPI.Util.Extensions;
|
||||
|
||||
public static class AddJsonPatchSupportExtension
|
||||
{
|
||||
public static void AddJsonPatchSupport(this MvcOptions options)
|
||||
{
|
||||
options.InputFormatters.Insert(0, GetJsonPatchInputFormatter());
|
||||
}
|
||||
|
||||
// Add Newtonsoft only to the JSON Patch formatter so the rest of the API keeps System.Text.Json.
|
||||
private static NewtonsoftJsonPatchInputFormatter GetJsonPatchInputFormatter()
|
||||
{
|
||||
var builder = new ServiceCollection()
|
||||
.AddLogging()
|
||||
.AddControllers()
|
||||
.AddNewtonsoftJson()
|
||||
.Services
|
||||
.BuildServiceProvider();
|
||||
|
||||
return builder
|
||||
.GetRequiredService<IOptions<MvcOptions>>()
|
||||
.Value
|
||||
.InputFormatters
|
||||
.OfType<NewtonsoftJsonPatchInputFormatter>()
|
||||
.First();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
namespace Events.WebAPI.Util.Extensions;
|
||||
|
||||
public static class DictionaryExtensions
|
||||
{
|
||||
public static TValue GetOrCreate<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key) where TValue : new() where TKey : notnull
|
||||
{
|
||||
if (!dict.ContainsKey(key))
|
||||
{
|
||||
var item = new TValue();
|
||||
dict[key] = item;
|
||||
return item;
|
||||
}
|
||||
else
|
||||
{
|
||||
return dict[key];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
using System.Text;
|
||||
|
||||
namespace Events.WebAPI.Util.Extensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Class with useful extensions for exceptions handling
|
||||
/// </summary>
|
||||
public static class ExceptionExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// return complete hierarchy of an exception. It checks whether the exception has inner exception,
|
||||
/// and if it has, then it appends inner exception message.
|
||||
/// Then it looks for inner exception of the inner exceptions, and so on.
|
||||
/// </summary>
|
||||
/// <param name="exc">Exception which message hiearchy should be obtained</param>
|
||||
/// <returns>String containing all exception hierarchy messages</returns>
|
||||
public static string CompleteExceptionMessage(this Exception? exc)
|
||||
{
|
||||
StringBuilder sb = new();
|
||||
while (exc != null)
|
||||
{
|
||||
sb.AppendLine(exc.Message);
|
||||
exc = exc.InnerException;
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
using FluentValidation;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using Events.WebAPI.Util.Extensions;
|
||||
using Events.WebAPI.Contract.Command;
|
||||
|
||||
namespace Events.WebAPI.Util.Middleware;
|
||||
|
||||
public class BadRequestOnRuleValidationException : ExceptionFilterAttribute
|
||||
{
|
||||
private readonly ILogger<BadRequestOnRuleValidationException> logger;
|
||||
|
||||
public BadRequestOnRuleValidationException(ILogger<BadRequestOnRuleValidationException> logger)
|
||||
{
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
public override void OnException(ExceptionContext context)
|
||||
{
|
||||
if (context.Exception is ValidationException)
|
||||
{
|
||||
|
||||
string exceptionMessage = context.Exception.CompleteExceptionMessage();
|
||||
logger.LogDebug("Validation error: {0}", exceptionMessage);
|
||||
|
||||
ValidationException exc = (ValidationException)context.Exception;
|
||||
Dictionary<string, List<string>> validationErrors = new Dictionary<string, List<string>>();
|
||||
Dictionary<string, List<string>> validationErrorCodes = new Dictionary<string, List<string>>();
|
||||
|
||||
foreach(var failure in exc.Errors)
|
||||
{
|
||||
//remove prefix Dto. (part of Update and AddCommand)
|
||||
string propertyName = failure.PropertyName.Replace(nameof(AddCommand<object, object>.Dto) + ".", "");
|
||||
if (propertyName == nameof(AddCommand<object, object>.Dto))
|
||||
{
|
||||
propertyName = string.Empty;
|
||||
}
|
||||
|
||||
validationErrors.GetOrCreate(propertyName).Add(failure.ErrorMessage);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(failure.ErrorCode))
|
||||
{
|
||||
validationErrorCodes.GetOrCreate(propertyName).Add(failure.ErrorCode);
|
||||
}
|
||||
}
|
||||
|
||||
var problemDetails = new ValidationProblemDetails(validationErrors.ToDictionary(d => d.Key, d => d.Value.ToArray()))
|
||||
{
|
||||
Detail = context.Exception.Message,
|
||||
Title = "Validation exception",
|
||||
Instance = context.HttpContext.TraceIdentifier
|
||||
};
|
||||
if (validationErrorCodes.Count > 0)
|
||||
{
|
||||
problemDetails.Extensions["errorCodes"] = validationErrorCodes.ToDictionary(d => d.Key, d => d.Value.ToArray());
|
||||
}
|
||||
context.Result = new ObjectResult(problemDetails)
|
||||
{
|
||||
ContentTypes = { "application/problem+json" },
|
||||
StatusCode = StatusCodes.Status400BadRequest
|
||||
};
|
||||
|
||||
context.HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
|
||||
context.ExceptionHandled = true;
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using Events.WebAPI.Util.Extensions;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
|
||||
namespace Events.WebAPI.Util.Middleware;
|
||||
|
||||
public class ProblemDetailsForException : ExceptionFilterAttribute
|
||||
{
|
||||
private readonly ILogger<ProblemDetailsForException> logger;
|
||||
|
||||
public ProblemDetailsForException(ILogger<ProblemDetailsForException> logger)
|
||||
{
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
public override void OnException(ExceptionContext context)
|
||||
{
|
||||
string exceptionMessage = context.Exception.CompleteExceptionMessage();
|
||||
logger.LogError("Error 500: {0}", exceptionMessage); //TO DO: Log data from context.ActionDescriptor?
|
||||
logger.LogError(context.Exception.StackTrace);
|
||||
context.ExceptionHandled = true;
|
||||
var problemDetails = new ProblemDetails
|
||||
{
|
||||
Type = "https://httpstatuses.io/500",
|
||||
Detail = exceptionMessage,
|
||||
Title = "Internal server error",
|
||||
Instance = context.HttpContext.TraceIdentifier
|
||||
};
|
||||
context.Result = new ObjectResult(problemDetails)
|
||||
{
|
||||
ContentTypes = { "application/problem+json" },
|
||||
StatusCode = StatusCodes.Status500InternalServerError
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
using Events.WebAPI.Util.Extensions;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Npgsql;
|
||||
|
||||
namespace Events.WebAPI.Util.Middleware;
|
||||
|
||||
public class ProblemDetailsForSqlException : ExceptionFilterAttribute
|
||||
{
|
||||
private readonly ILogger<ProblemDetailsForSqlException> logger;
|
||||
|
||||
public ProblemDetailsForSqlException(ILogger<ProblemDetailsForSqlException> logger)
|
||||
{
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
public override void OnException(ExceptionContext context)
|
||||
{
|
||||
Exception? exception = context.Exception;
|
||||
PostgresException? postgresException = null;
|
||||
|
||||
while (exception is not null)
|
||||
{
|
||||
if (exception is PostgresException currentPostgresException)
|
||||
{
|
||||
postgresException = currentPostgresException;
|
||||
break;
|
||||
}
|
||||
|
||||
if (exception is DbUpdateException dbUpdateException && dbUpdateException.InnerException is not null)
|
||||
{
|
||||
exception = dbUpdateException.InnerException;
|
||||
continue;
|
||||
}
|
||||
|
||||
exception = exception.InnerException;
|
||||
}
|
||||
|
||||
if (postgresException is null)
|
||||
{
|
||||
base.OnException(context);
|
||||
return;
|
||||
}
|
||||
|
||||
ProblemDetails problemDetails = postgresException.SqlState switch
|
||||
{
|
||||
PostgresErrorCodes.UniqueViolation => new ProblemDetails
|
||||
{
|
||||
Title = "Duplicate data",
|
||||
Detail = "A record with the same data already exists."
|
||||
},
|
||||
PostgresErrorCodes.ForeignKeyViolation => new ProblemDetails
|
||||
{
|
||||
Title = "Related data",
|
||||
Detail = "The operation is not allowed because related data exists."
|
||||
},
|
||||
_ => new ProblemDetails
|
||||
{
|
||||
Title = "Database error",
|
||||
Detail = $"An error occurred while saving data to the database. {postgresException.MessageText}"
|
||||
}
|
||||
};
|
||||
|
||||
logger.LogDebug("Database exception: {message}", context.Exception.CompleteExceptionMessage());
|
||||
context.ExceptionHandled = true;
|
||||
context.Result = new ObjectResult(problemDetails)
|
||||
{
|
||||
ContentTypes = { "application/problem+json" },
|
||||
StatusCode = StatusCodes.Status500InternalServerError
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace Events.WebAPI.Util.Settings;
|
||||
|
||||
public class RabbitMqSettings
|
||||
{
|
||||
[Required]
|
||||
public string Host { get; set; } = string.Empty;
|
||||
|
||||
[Required]
|
||||
public string Username { get; set; } = string.Empty;
|
||||
|
||||
[Required]
|
||||
public string Password { get; set; } = string.Empty;
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
|
||||
namespace Events.WebAPI.Util.Startup;
|
||||
|
||||
public static class AuthSetupExtensions
|
||||
{
|
||||
public static void SetupAuthenticationAndAuthorization(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
Microsoft.IdentityModel.JsonWebTokens.JsonWebTokenHandler.DefaultInboundClaimTypeMap.Clear();
|
||||
|
||||
services.AddScoped<IClaimsTransformation, ScopeClaimsTransformation>();
|
||||
|
||||
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||
.AddJwtBearer(opt =>
|
||||
{
|
||||
opt.Authority = configuration["Auth:Authority"];
|
||||
opt.Audience = configuration["Auth:Audience"];
|
||||
opt.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateAudience = true,
|
||||
ValidateIssuerSigningKey = true,
|
||||
NameClaimType = ClaimTypes.NameIdentifier
|
||||
};
|
||||
opt.Events = new JwtBearerEvents
|
||||
{
|
||||
OnAuthenticationFailed = context =>
|
||||
{
|
||||
if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
|
||||
{
|
||||
context.Response.Headers.Append("Token-Expired", "true");
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
services.AddAuthorization(options =>
|
||||
{
|
||||
foreach (var policy in Policies.All)
|
||||
{
|
||||
options.AddPolicy(policy.Key, policy.Value);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using Events.WebAPI.Util.Settings;
|
||||
using MassTransit;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Events.WebAPI.Util.Startup;
|
||||
|
||||
public static class MassTransitSetupExtensions
|
||||
{
|
||||
public static void SetupMassTransit(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
services.AddOptions<RabbitMqSettings>()
|
||||
.Bind(configuration.GetSection("RabbitMq"))
|
||||
.ValidateDataAnnotations()
|
||||
.Validate(
|
||||
settings => Uri.TryCreate(settings.Host, UriKind.Absolute, out var uri) &&
|
||||
uri.Scheme == "rabbitmq" &&
|
||||
!string.IsNullOrWhiteSpace(uri.Host),
|
||||
"RabbitMq:Host must be a valid absolute rabbitmq:// URI.")
|
||||
.ValidateOnStart();
|
||||
|
||||
services.AddMassTransit(x =>
|
||||
{
|
||||
x.UsingRabbitMq((context, cfg) =>
|
||||
{
|
||||
var settings = context.GetRequiredService<IOptions<RabbitMqSettings>>().Value;
|
||||
|
||||
cfg.Host(new Uri(settings.Host), h =>
|
||||
{
|
||||
h.Username(settings.Username);
|
||||
h.Password(settings.Password);
|
||||
});
|
||||
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
|
||||
namespace Events.WebAPI.Util.Startup;
|
||||
|
||||
public sealed class ScopeClaimsTransformation : IClaimsTransformation
|
||||
{
|
||||
public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
|
||||
{
|
||||
if (principal.Identity is not ClaimsIdentity identity || !identity.IsAuthenticated)
|
||||
{
|
||||
return Task.FromResult(principal);
|
||||
}
|
||||
|
||||
Claim[] combinedScopeClaims = identity
|
||||
.FindAll("scope")
|
||||
.Where(claim => claim.Value.Contains(' '))
|
||||
.ToArray();
|
||||
|
||||
if (combinedScopeClaims.Length == 0)
|
||||
{
|
||||
return Task.FromResult(principal);
|
||||
}
|
||||
|
||||
var additionalIdentity = new ClaimsIdentity();
|
||||
|
||||
foreach (Claim combinedClaim in combinedScopeClaims)
|
||||
{
|
||||
foreach (string scope in combinedClaim.Value.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
|
||||
{
|
||||
if (identity.HasClaim("scope", scope) || additionalIdentity.HasClaim("scope", scope))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
additionalIdentity.AddClaim(new Claim("scope", scope, combinedClaim.ValueType, combinedClaim.Issuer));
|
||||
}
|
||||
}
|
||||
|
||||
if (additionalIdentity.Claims.Any())
|
||||
{
|
||||
principal.AddIdentity(additionalIdentity);
|
||||
}
|
||||
|
||||
return Task.FromResult(principal);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.OpenApi;
|
||||
using Swashbuckle.AspNetCore.SwaggerGen;
|
||||
|
||||
|
||||
namespace Events.WebAPI.Util.Swagger;
|
||||
|
||||
public static class AddBearerTokenSchemeExtension
|
||||
{
|
||||
public static void AddBearerTokenScheme(this SwaggerGenOptions opt)
|
||||
{
|
||||
var jwtSecurityScheme = new OpenApiSecurityScheme
|
||||
{
|
||||
Description = "Paste token here",
|
||||
Name = "Authorization",
|
||||
In = ParameterLocation.Header,
|
||||
Type = SecuritySchemeType.Http,
|
||||
Scheme = JwtBearerDefaults.AuthenticationScheme,
|
||||
BearerFormat = "JWT",
|
||||
};
|
||||
|
||||
//Dodaj Authorize button u Swagger UI
|
||||
opt.AddSecurityDefinition(jwtSecurityScheme.Scheme, jwtSecurityScheme);
|
||||
|
||||
//opt.AddSecurityRequirement(document => new() { [new OpenApiSecuritySchemeReference(jwtSecurityScheme.Scheme, document)] = [] });
|
||||
|
||||
// nemoj ga primijeniti na sve operacije (redak iznad), nego samo na one koje imaju Authorize atribut
|
||||
opt.OperationFilter<AuthorizeOperationFilter>();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.OpenApi;
|
||||
using Swashbuckle.AspNetCore.SwaggerGen;
|
||||
|
||||
namespace Events.WebAPI.Util.Swagger;
|
||||
|
||||
public class AuthorizeOperationFilter : IOperationFilter
|
||||
{
|
||||
public void Apply(OpenApiOperation operation, OperationFilterContext context)
|
||||
{
|
||||
var hasAuthorize = context.MethodInfo.DeclaringType?
|
||||
.GetCustomAttributes(true)
|
||||
.OfType<AuthorizeAttribute>().Any() == true
|
||||
||
|
||||
context.MethodInfo.GetCustomAttributes(true)
|
||||
.OfType<AuthorizeAttribute>().Any();
|
||||
|
||||
if (!hasAuthorize)
|
||||
return;
|
||||
|
||||
operation.Security ??= new List<OpenApiSecurityRequirement>();
|
||||
|
||||
operation.Security.Add(new OpenApiSecurityRequirement
|
||||
{
|
||||
[
|
||||
new OpenApiSecuritySchemeReference(
|
||||
JwtBearerDefaults.AuthenticationScheme,
|
||||
context.Document
|
||||
)
|
||||
] = new List<string>()
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
using Events.WebAPI.Contract.Validation;
|
||||
|
||||
namespace Events.WebAPI.Util.Validation;
|
||||
|
||||
public class ValidationMessageProvider : IValidationMessageProvider
|
||||
{
|
||||
public ValidationMessage UniqueSportName(string sportName)
|
||||
=> new(ValidationErrorCodes.SportNameNotUnique, $"A sport named '{sportName}' already exists.");
|
||||
|
||||
public ValidationMessage UniquePersonDocumentAndCountry()
|
||||
=> new(ValidationErrorCodes.PersonDocumentCountryNotUnique, "A person with the same document number already exists for the selected country.");
|
||||
|
||||
public ValidationMessage PersonEmailOrContactPhoneRequired()
|
||||
=> new(ValidationErrorCodes.PersonEmailOrContactPhoneRequired, "Either e-mail address or contact phone is required.");
|
||||
|
||||
public ValidationMessage UniqueRegistration()
|
||||
=> new(ValidationErrorCodes.RegistrationNotUnique, "The person is already registered for the selected sport at this event.");
|
||||
|
||||
public ValidationMessage EventNotFound()
|
||||
=> new(ValidationErrorCodes.EventNotFound, "The selected event does not exist.");
|
||||
|
||||
public ValidationMessage PersonNotFound()
|
||||
=> new(ValidationErrorCodes.PersonNotFound, "The selected person does not exist.");
|
||||
|
||||
public ValidationMessage SportNotFound()
|
||||
=> new(ValidationErrorCodes.SportNotFound, "The selected sport does not exist.");
|
||||
|
||||
public ValidationMessage ForeignKeyNotFound(string propertyName)
|
||||
=> new(ValidationErrorCodes.ForeignKeyNotFound, $"The selected value for {propertyName} does not exist.");
|
||||
}
|
||||
8
Events-WebApi/Events.WebAPI/appsettings.Development.json
Normal file
8
Events-WebApi/Events.WebAPI/appsettings.Development.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
}
|
||||
}
|
||||
30
Events-WebApi/Events.WebAPI/appsettings.json
Normal file
30
Events-WebApi/Events.WebAPI/appsettings.json
Normal file
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning",
|
||||
"Microsoft.EntityFrameworkCore.Database.Command": "Warning"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*",
|
||||
"Sieve": {
|
||||
"CaseSensitive": false,
|
||||
"DefaultPageSize": 50,
|
||||
"MaxPageSize": 200,
|
||||
"ThrowExceptions": true,
|
||||
"IgnoreNullsOnNotEqual": true,
|
||||
"DisableNullableTypeExpressionForSorting": false
|
||||
},
|
||||
"RabbitMq": {
|
||||
"Host": "rabbitmq://localhost",
|
||||
"Username": "guest",
|
||||
"Password": "guest"
|
||||
},
|
||||
"ConnectionStrings": {
|
||||
"EventDB": "Host=localhost;Port=5432;Database=events;Username=sport;Password=go and look in the secrets file;Persist Security Info=True;"
|
||||
},
|
||||
"Auth": {
|
||||
"Authority": "https://fer-web2.eu.auth0.com/",
|
||||
"Audience": "https://erasmus-sta-2026/events-api"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user