Files
Shogi/Shogi.Sockets/Controllers/UserController.cs
2022-10-30 12:47:39 -05:00

108 lines
3.0 KiB
C#

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Shogi.Contracts.Api;
using Shogi.Api.Extensions;
using Shogi.Api.Managers;
using Shogi.Api.Models;
using Shogi.Api.Repositories;
using System.Security.Claims;
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<UserController> 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<IActionResult> 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<IActionResult> 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<IActionResult> 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();
}
}