Update to dotnet 9.0, add user roles, MatchStats and OpenApi/Scalar in dev
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using AutoMapper;
|
||||
using LaDOSE.Business.Interface;
|
||||
using LaDOSE.DTO;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace LaDOSE.Api.Controllers
|
||||
{
|
||||
[Authorize]
|
||||
[Produces("application/json")]
|
||||
[Route("api/[controller]")]
|
||||
public class StatisticsController : Controller
|
||||
{
|
||||
private readonly IStatisticsService _service;
|
||||
private readonly IMapper _mapper;
|
||||
|
||||
public StatisticsController(IMapper mapper, IStatisticsService service)
|
||||
{
|
||||
_mapper = mapper;
|
||||
_service = service;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Match statistics for the given Event ids. Body is a bare JSON array of ids,
|
||||
/// like TournamentController.GetResults.
|
||||
/// A null or empty array returns a zeroed, empty MatchStatsDTO rather than an error.
|
||||
/// Read Coverage before trusting the numbers: many brackets have no set rows at all.
|
||||
/// </summary>
|
||||
[HttpPost("Matches")]
|
||||
public async Task<MatchStatsDTO> GetMatchStats([FromBody] List<int> ids)
|
||||
{
|
||||
var stats = await _service.GetMatchStats(ids);
|
||||
return _mapper.Map<MatchStatsDTO>(stats);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Linq;
|
||||
@@ -9,6 +9,7 @@ using LaDOSE.Business.Interface;
|
||||
using LaDOSE.DTO;
|
||||
using LaDOSE.Entity;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.Options;
|
||||
@@ -33,12 +34,32 @@ namespace LaDOSE.Api.Controllers
|
||||
_configuration = configuration;
|
||||
}
|
||||
|
||||
/// <summary>Public view of a user: no password, no hash, no salt.</summary>
|
||||
private static ApplicationUserDTO ToDto(ApplicationUser user)
|
||||
{
|
||||
return new ApplicationUserDTO
|
||||
{
|
||||
Id = user.Id,
|
||||
Username = user.Username,
|
||||
FirstName = user.FirstName,
|
||||
LastName = user.LastName,
|
||||
Roles = user.Names()
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The id the JWT was issued for; null if the request is not authenticated.</summary>
|
||||
private int? CurrentUserId()
|
||||
{
|
||||
return int.TryParse(User?.Identity?.Name, out var id) ? id : (int?)null;
|
||||
}
|
||||
|
||||
[AllowAnonymous]
|
||||
[HttpPost("auth")]
|
||||
public IActionResult Authenticate([FromBody]ApplicationUser userDto)
|
||||
[ProducesResponseType(typeof(ApplicationUserDTO), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
public IActionResult Authenticate([FromBody]ApplicationUserDTO userDto)
|
||||
{
|
||||
var user = _userService.Authenticate(userDto.Username, userDto.Password);
|
||||
var user = _userService.Authenticate(userDto?.Username, userDto?.Password);
|
||||
|
||||
if (user == null)
|
||||
return BadRequest(new { message = "Username or password is incorrect" });
|
||||
@@ -47,10 +68,13 @@ namespace LaDOSE.Api.Controllers
|
||||
var key = Encoding.ASCII.GetBytes(this._configuration["JWTTokenSecret"]);
|
||||
var tokenDescriptor = new SecurityTokenDescriptor
|
||||
{
|
||||
// Only the user id goes in the token. Roles are read from the database on
|
||||
// every request instead, so granting or revoking Admin takes effect at
|
||||
// once rather than whenever the current token happens to expire.
|
||||
Subject = new ClaimsIdentity(new Claim[]
|
||||
{
|
||||
new Claim(ClaimTypes.Name, user.Id.ToString()),
|
||||
|
||||
|
||||
|
||||
}),
|
||||
Expires = DateTime.UtcNow.AddMinutes(16),
|
||||
@@ -60,29 +84,62 @@ namespace LaDOSE.Api.Controllers
|
||||
var tokenString = tokenHandler.WriteToken(token);
|
||||
|
||||
// return basic user info (without password) and token to store client side
|
||||
return Ok(new ApplicationUserDTO
|
||||
{
|
||||
Id = user.Id,
|
||||
Username = user.Username,
|
||||
FirstName = user.FirstName,
|
||||
LastName = user.LastName,
|
||||
Token = tokenString,
|
||||
Expire = token.ValidTo
|
||||
});
|
||||
var dto = ToDto(user);
|
||||
dto.Token = tokenString;
|
||||
dto.Expire = token.ValidTo;
|
||||
return Ok(dto);
|
||||
}
|
||||
|
||||
[AllowAnonymous]
|
||||
[HttpPost("register")]
|
||||
public IActionResult Register([FromBody]ApplicationUser userDto)
|
||||
/// <summary>Every account, for the admin user-management screen.</summary>
|
||||
[Authorize(Roles = Roles.Admin)]
|
||||
[HttpGet]
|
||||
[ProducesResponseType(typeof(List<ApplicationUserDTO>), StatusCodes.Status200OK)]
|
||||
public IActionResult GetUsers()
|
||||
{
|
||||
// map dto to entity
|
||||
var users = _userService.GetAll()
|
||||
.OrderBy(user => user.Username)
|
||||
.Select(ToDto)
|
||||
.ToList();
|
||||
|
||||
return Ok(users);
|
||||
}
|
||||
|
||||
/// <summary>The role names that may be assigned, from the applicationrole table.</summary>
|
||||
[Authorize(Roles = Roles.Admin)]
|
||||
[HttpGet("Roles")]
|
||||
[ProducesResponseType(typeof(List<string>), StatusCodes.Status200OK)]
|
||||
public IActionResult GetRoles()
|
||||
{
|
||||
return Ok(_userService.GetAllRoles().Select(role => role.Name).ToList());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an account. This replaces the old anonymous <c>register</c> endpoint —
|
||||
/// only an admin may create users now, so the very first admin has to be promoted
|
||||
/// directly in the database (see Sql/2026-08-05_roles.sql).
|
||||
/// </summary>
|
||||
[Authorize(Roles = Roles.Admin)]
|
||||
[HttpPost("AddUser")]
|
||||
[ProducesResponseType(typeof(ApplicationUserDTO), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
public IActionResult AddUser([FromBody]ApplicationUserDTO userDto)
|
||||
{
|
||||
if (userDto == null)
|
||||
return BadRequest(new { message = "No user supplied" });
|
||||
|
||||
try
|
||||
{
|
||||
// save
|
||||
_userService.Create(userDto, userDto.Password);
|
||||
return Ok();
|
||||
var created = _userService.Create(
|
||||
new ApplicationUser
|
||||
{
|
||||
Username = userDto.Username?.Trim(),
|
||||
FirstName = userDto.FirstName,
|
||||
LastName = userDto.LastName
|
||||
},
|
||||
userDto.Password,
|
||||
userDto.Roles);
|
||||
|
||||
return Ok(ToDto(created));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -91,7 +148,35 @@ namespace LaDOSE.Api.Controllers
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes an account. Refuses to delete the caller: since only an admin can reach
|
||||
/// this, and an admin cannot remove themselves, at least one admin always survives
|
||||
/// — which matters because there is no anonymous way back in any more.
|
||||
/// </summary>
|
||||
[Authorize(Roles = Roles.Admin)]
|
||||
[HttpDelete("{id}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public IActionResult DeleteUser(int id)
|
||||
{
|
||||
var user = _userService.GetById(id);
|
||||
if (user == null)
|
||||
return NotFound(new { message = "User not found" });
|
||||
|
||||
if (CurrentUserId() == id)
|
||||
return BadRequest(new { message = "You cannot delete your own account" });
|
||||
|
||||
try
|
||||
{
|
||||
_userService.Delete(id);
|
||||
return NoContent();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return BadRequest(new { message = ex.Message });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
#if DEBUG
|
||||
using System.Linq;
|
||||
using Microsoft.AspNetCore.Mvc.ApplicationModels;
|
||||
using Microsoft.AspNetCore.Mvc.Routing;
|
||||
|
||||
namespace LaDOSE.Api.Helpers
|
||||
{
|
||||
/// <summary>
|
||||
/// The controllers in this project are attribute-routed but do not carry [ApiController].
|
||||
/// Without it MVC never sets ApiExplorer visibility, so ApiExplorer yields no descriptions
|
||||
/// and the generated OpenAPI document comes out with an empty "paths" object.
|
||||
/// This convention opts the attribute-routed actions into ApiExplorer for the
|
||||
/// OpenAPI/Scalar tooling only, without pulling in the [ApiController] behaviours
|
||||
/// (automatic 400 responses, [FromBody] inference) that would change runtime binding.
|
||||
/// </summary>
|
||||
public class ApiExplorerVisibilityConvention : IControllerModelConvention
|
||||
{
|
||||
public void Apply(ControllerModel controller)
|
||||
{
|
||||
// Default the controller to hidden, then opt in action by action.
|
||||
controller.ApiExplorer.IsVisible ??= false;
|
||||
|
||||
foreach (var action in controller.Actions)
|
||||
{
|
||||
if (action.ApiExplorer.IsVisible != null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// An action with a [Route] but no verb attribute (e.g. BotEventController's
|
||||
// CreateBotEvent) matches every HTTP method, so ApiExplorer reports an empty
|
||||
// method and OpenAPI generation throws "Unsupported HTTP method".
|
||||
// Only document actions that pin down a verb.
|
||||
action.ApiExplorer.IsVisible = action.Attributes
|
||||
.OfType<IActionHttpMethodProvider>()
|
||||
.Any(provider => provider.HttpMethods?.Any() == true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,7 +1,7 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<LangVersion>12</LangVersion>
|
||||
</PropertyGroup>
|
||||
@@ -15,6 +15,9 @@
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.12" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="8.0.12" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.1" />
|
||||
<PackageReference Include="Microsoft.OpenApi" Version="1.6.17" Condition="'$(Configuration)' == 'Debug'" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.18" Condition="'$(Configuration)' == 'Debug'" />
|
||||
<PackageReference Include="Scalar.AspNetCore" Version="2.16.17" Condition="'$(Configuration)' == 'Debug'" />
|
||||
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="8.0.7" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.11" />
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System;
|
||||
using System.Reflection;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using LaDOSE.Business.Interface;
|
||||
@@ -25,6 +26,9 @@ using Result = LaDOSE.Entity.Challonge.Result;
|
||||
using LaDOSE.Entity.BotEvent;
|
||||
using Microsoft.EntityFrameworkCore.Storage;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
#if DEBUG
|
||||
using Scalar.AspNetCore;
|
||||
#endif
|
||||
|
||||
namespace LaDOSE.Api
|
||||
{
|
||||
@@ -55,11 +59,21 @@ namespace LaDOSE.Api
|
||||
}
|
||||
|
||||
services.AddCors();
|
||||
services.AddMvc().AddNewtonsoftJson(x =>
|
||||
services.AddMvc(options =>
|
||||
{
|
||||
#if DEBUG
|
||||
// Make the attribute-routed controllers visible to ApiExplorer so the
|
||||
// OpenAPI document is actually populated. See ApiExplorerVisibilityConvention.
|
||||
options.Conventions.Add(new ApiExplorerVisibilityConvention());
|
||||
#endif
|
||||
}).AddNewtonsoftJson(x =>
|
||||
{
|
||||
x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
|
||||
x.SerializerSettings.MaxDepth= 4;
|
||||
});
|
||||
#if DEBUG
|
||||
services.AddOpenApi();
|
||||
#endif
|
||||
// services.AddDbContextPool<LaDOSEDbContext>( // replace "YourDbContext" with the class name of your DbContext
|
||||
//
|
||||
// options => options.UseMySql($"Server={MySqlServer};Database={MySqlDatabase};User={MySqlUser};Password={MySqlPassword};", // replace with your Connection String
|
||||
@@ -92,6 +106,18 @@ namespace LaDOSE.Api
|
||||
{
|
||||
// return unauthorized if user no longer exists
|
||||
context.Fail("Unauthorized");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
// Roles are attached here, from the database, rather than being
|
||||
// signed into the token: a promotion or demotion then applies to
|
||||
// the caller's very next request instead of waiting 16 minutes.
|
||||
if (context.Principal.Identity is ClaimsIdentity identity)
|
||||
{
|
||||
foreach (var role in user.Names())
|
||||
{
|
||||
identity.AddClaim(new Claim(identity.RoleClaimType, role));
|
||||
}
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
@@ -130,6 +156,13 @@ namespace LaDOSE.Api
|
||||
cfg.CreateMapTwoWay<Game, LaDOSE.DTO.GameDTO>();
|
||||
cfg.CreateMapTwoWay<Todo, LaDOSE.DTO.TodoDTO>();
|
||||
|
||||
// Match statistics: plain POCO aggregates computed by StatisticsService,
|
||||
// mapped by name (same pattern as TournamentsResult above).
|
||||
cfg.CreateMap<MatchStats, LaDOSE.DTO.MatchStatsDTO>();
|
||||
cfg.CreateMap<MatchCoverage, LaDOSE.DTO.MatchCoverageDTO>();
|
||||
cfg.CreateMap<PlayerMatchStats, LaDOSE.DTO.PlayerMatchStatsDTO>();
|
||||
cfg.CreateMap<HeadToHead, LaDOSE.DTO.HeadToHeadDTO>();
|
||||
|
||||
});
|
||||
IMapper mapper = mapperConfig.CreateMapper();
|
||||
services.AddSingleton(mapper);
|
||||
@@ -149,6 +182,7 @@ namespace LaDOSE.Api
|
||||
services.AddScoped<IBotEventService, BotEventService>();
|
||||
|
||||
services.AddScoped<IPlayerService, PlayerService>();
|
||||
services.AddScoped<IStatisticsService, StatisticsService>();
|
||||
services.AddTransient<IChallongeProvider>(p => new ChallongeProvider( p.GetRequiredService<IGameService>(),
|
||||
p.GetRequiredService<IEventService>(),
|
||||
p.GetRequiredService<IPlayerService>(),
|
||||
@@ -185,7 +219,17 @@ namespace LaDOSE.Api
|
||||
app.UseRouting();
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
app.UseEndpoints(x => x.MapControllers());
|
||||
app.UseEndpoints(x =>
|
||||
{
|
||||
x.MapControllers();
|
||||
#if DEBUG
|
||||
if (env.IsDevelopment())
|
||||
{
|
||||
x.MapOpenApi();
|
||||
x.MapScalarApiReference();
|
||||
}
|
||||
#endif
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user