using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Shogi.Api.Identity; using System.Security.Claims; namespace Shogi.Api.Controllers; [Authorize] [Route("[controller]")] [ApiController] public class AccountController( SignInManager signInManager, UserManager UserManager, IConfiguration configuration) : ControllerBase { [Authorize("Admin")] [HttpPost("TestAccount")] public async Task CreateTestAccounts() { var newUser = new ShogiUser { UserName = "aat-account", Email = "test-account@lucaserver.space", EmailConfirmed = true }; var newUser2 = new ShogiUser { UserName = "aat-account-2", Email = "test-account2@lucaserver.space", EmailConfirmed = true }; var pass = configuration["TestUserPassword"] ?? throw new InvalidOperationException("TestUserPassword not configured."); var result = await UserManager.CreateAsync(newUser, pass); if (result != null && !result.Succeeded) { return this.Problem(string.Join(",", result.Errors.Select(e => e.Description))); } result = await UserManager.CreateAsync(newUser2, pass); if(result != null && !result.Succeeded) { return this.Problem(string.Join(",", result.Errors.Select(e => e.Description))); } return this.Created(); } [HttpPost("/logout")] public async Task Logout([FromBody] object empty) { // https://learn.microsoft.com/aspnet/core/blazor/security/webassembly/standalone-with-identity#antiforgery-support if (empty is not null) { await signInManager.SignOutAsync(); return this.Ok(); } return this.Unauthorized(); } [HttpGet("/roles")] public IActionResult GetRoles() { if (this.User.Identity is not null && this.User.Identity.IsAuthenticated) { var identity = (ClaimsIdentity)this.User.Identity; var roles = identity.FindAll(identity.RoleClaimType) .Select(c => new { c.Issuer, c.OriginalIssuer, c.Type, c.Value, c.ValueType }); return this.Ok(roles); } return this.Unauthorized(); } }