From 966ab9bdda8bcac890670fa3fa699e77d432fae6 Mon Sep 17 00:00:00 2001 From: Polianin Nikita Date: Tue, 28 May 2024 07:19:40 +0300 Subject: [PATCH] feat: add generate and check token --- .../Configuration/SetupController.cs | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Endpoint/Controllers/Configuration/SetupController.cs diff --git a/Endpoint/Controllers/Configuration/SetupController.cs b/Endpoint/Controllers/Configuration/SetupController.cs new file mode 100644 index 0000000..225da6e --- /dev/null +++ b/Endpoint/Controllers/Configuration/SetupController.cs @@ -0,0 +1,48 @@ +using System; +using System.Security.Cryptography; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Mirea.Api.Endpoint.Common.Attributes; +using Mirea.Api.Endpoint.Common.Exceptions; +using Mirea.Api.Endpoint.Common.Interfaces; +using Mirea.Api.Endpoint.Configuration.General; + +namespace Mirea.Api.Endpoint.Controllers.Configuration; + +[ApiVersion("1.0")] +[ApiController] +[MaintenanceModeIgnore] +public class SetupController(ISetupToken setupToken, IMaintenanceModeNotConfigureService notConfigureService) : BaseController +{ + [HttpGet("GenerateToken")] + public ActionResult GenerateToken() + { + if (!notConfigureService.IsMaintenanceMode) + throw new ControllerArgumentException( + "The token cannot be generated because the server has been configured. " + + $"If you need to restart the configuration, then delete the \"{GeneralConfig.FilePath}\" file and restart the application."); + + var token = new byte[32]; + RandomNumberGenerator.Create().GetBytes(token); + setupToken.SetToken(token); + + return Ok(Convert.ToBase64String(token)); + } + + [HttpGet("CheckToken")] + public ActionResult CheckToken([FromQuery] string token) + { + if (!setupToken.MatchToken(Convert.FromBase64String(token))) return Unauthorized("The token is not valid"); + + Response.Cookies.Append("AuthToken", token, new CookieOptions + { + HttpOnly = false, + Secure = false, + Path = "/" + }); + + return Ok(true); + } + + +} \ No newline at end of file