45 lines
1.5 KiB
C#
45 lines
1.5 KiB
C#
using Microsoft.AspNetCore.Mvc;
|
|
using Server.WatchBody.Web.Services;
|
|
|
|
namespace Server.WatchBody.Web.Controllers.Admin;
|
|
|
|
/// <summary>POST /api/admin/login, POST /api/admin/logout (spec 01).</summary>
|
|
public class AdminAuthController(AdminAuthService auth) : Controller
|
|
{
|
|
public ActionResult Login()
|
|
{
|
|
var body = ReadJson();
|
|
var login = body?.TryGetProperty("login", out var l) == true ? l.GetString() : null;
|
|
var password = body?.TryGetProperty("password", out var p) == true ? p.GetString() : null;
|
|
var token = login == null || password == null ? null : auth.Login(login, password);
|
|
if (token == null)
|
|
{
|
|
Response.StatusCode = 401;
|
|
return new JsonResult(new { error = "unauthorized" });
|
|
}
|
|
return new JsonResult(new { token });
|
|
}
|
|
|
|
public ActionResult Logout()
|
|
{
|
|
var header = Request.Headers.Authorization.FirstOrDefault();
|
|
if (header?.StartsWith("Bearer ") == true)
|
|
auth.Logout(header["Bearer ".Length..]);
|
|
return new JsonResult(new { ok = true });
|
|
}
|
|
|
|
private System.Text.Json.JsonElement? ReadJson()
|
|
{
|
|
using var reader = new StreamReader(Request.Body);
|
|
var json = reader.ReadToEndAsync().GetAwaiter().GetResult();
|
|
try
|
|
{
|
|
return System.Text.Json.JsonDocument.Parse(json).RootElement.Clone();
|
|
}
|
|
catch (System.Text.Json.JsonException)
|
|
{
|
|
return null;
|
|
}
|
|
}
|
|
}
|