Started implementing client and api server auth and the refresh endpoint

This commit is contained in:
Masu Baumgartner
2024-10-19 16:37:37 +02:00
parent 6be3b8338d
commit 8883b521e9
7 changed files with 94 additions and 9 deletions

View File

@@ -1,4 +1,5 @@
using Microsoft.AspNetCore.Mvc;
using MoonCore.Exceptions;
using MoonCore.Extended.Abstractions;
using MoonCore.Extended.Helpers;
using MoonCore.Extended.OAuth2.ApiServer;
@@ -39,6 +40,40 @@ public class AuthController : Controller
return Mapper.Map<AuthStartResponse>(data);
}
[HttpPost("refresh")]
public async Task Refresh([FromBody] RefreshRequest request)
{
var authConfig = ConfigService.Get().Authentication;
var tokenPair = await TokenHelper.RefreshPair(
request.RefreshToken,
authConfig.MlAccessSecret,
authConfig.MlRefreshSecret,
(refreshTokenData, newTokenData) =>
{
if (!refreshTokenData.TryGetValue("userId", out var userIdStr) || !int.TryParse(userIdStr, out var userId))
return false;
var user = UserRepository.Get().FirstOrDefault(x => x.Id == userId);
if (user == null)
return false;
//TODO: External check
newTokenData.Add("userId", user.Id.ToString());
return true;
}
);
if (!tokenPair.HasValue)
throw new HttpApiException("Unable to refresh token", 401);
Response.Cookies.Append("ml-access", tokenPair.Value.AccessToken);
Response.Cookies.Append("ml-refresh", tokenPair.Value.RefreshToken);
Response.Cookies.Append("ml-timestamp", DateTimeOffset.UtcNow.AddSeconds(3600).ToUnixTimeSeconds().ToString());
}
[HttpGet("handle")]
public async Task Handle([FromQuery(Name = "code")] string code)
{