using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Shogi.Api.Extensions; using Shogi.Api.Managers; using Shogi.Api.Repositories; using Shogi.Contracts.Api; namespace Shogi.Api.Controllers; [ApiController] [Route("[controller]")] [Authorize] public class UserController : ControllerBase { private readonly ISocketTokenCache tokenCache; private readonly ISocketConnectionManager connectionManager; private readonly IUserRepository userRepository; private readonly IShogiUserClaimsTransformer claimsTransformation; private readonly AuthenticationProperties authenticationProps; public UserController( ILogger logger, ISocketTokenCache tokenCache, ISocketConnectionManager connectionManager, IUserRepository userRepository, IShogiUserClaimsTransformer claimsTransformation) { this.tokenCache = tokenCache; this.connectionManager = connectionManager; this.userRepository = userRepository; this.claimsTransformation = claimsTransformation; authenticationProps = new AuthenticationProperties { AllowRefresh = true, IsPersistent = true }; } [HttpPut("GuestLogout")] public async Task GuestLogout() { var signoutTask = HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); var userId = User?.GetGuestUserId(); if (!string.IsNullOrEmpty(userId)) { connectionManager.Unsubscribe(userId); } await signoutTask; return Ok(); } //[HttpGet("Token")] //public async Task GetToken() //{ // var user = await gameboardManager.ReadUser(User); // if (user == null) // { // await gameboardManager.CreateUser(User); // user = await gameboardManager.ReadUser(User); // } // if (user == null) // { // return Unauthorized(); // } // var token = tokenCache.GenerateToken(user.Id); // return new JsonResult(new CreateTokenResponse(token)); //} [AllowAnonymous] [HttpGet("LoginAsGuest")] public async Task GuestLogin() { var principal = await this.claimsTransformation.CreateClaimsFromGuestPrincipal(User); if (principal != null) { await HttpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, principal, authenticationProps ); } return Ok(); } [HttpGet("GuestToken")] public IActionResult GetGuestToken() { var id = User.GetGuestUserId(); var displayName = User.DisplayName(); if (!string.IsNullOrWhiteSpace(id) && !string.IsNullOrWhiteSpace(displayName)) { var token = tokenCache.GenerateToken(User.GetGuestUserId()!); return this.Ok(new CreateGuestTokenResponse(id, displayName, token)); } return this.Unauthorized(); } }