61 lines
2.5 KiB
C#
61 lines
2.5 KiB
C#
using System.Text;
|
|
using System.Text.RegularExpressions;
|
|
using Messenger.Api.Services;
|
|
using static Messenger.Api.Services.ApiSupport;
|
|
|
|
namespace Messenger.Api.Endpoints;
|
|
|
|
public static class AuthEndpoints
|
|
{
|
|
private static readonly UTF8Encoding StrictUtf8 = new(false, true);
|
|
|
|
public static IEndpointRouteBuilder MapAuthEndpoints(this IEndpointRouteBuilder app)
|
|
{
|
|
app.MapPost("/api/v1/auth/sessions", async (HttpContext context, SessionService sessions) =>
|
|
{
|
|
if (!context.Request.Headers.TryGetValue("Authorization", out var header))
|
|
return Unauthorized(context, basic: true);
|
|
|
|
var authorization = header.ToString();
|
|
if (!authorization.StartsWith("Basic ", StringComparison.OrdinalIgnoreCase))
|
|
return Unauthorized(context, basic: true);
|
|
|
|
string credentials;
|
|
try
|
|
{
|
|
credentials = StrictUtf8.GetString(Convert.FromBase64String(authorization[6..]));
|
|
}
|
|
catch (Exception exception) when (exception is FormatException or DecoderFallbackException)
|
|
{
|
|
return Unauthorized(context, basic: true);
|
|
}
|
|
|
|
var delimiter = credentials.IndexOf(':');
|
|
if (delimiter < 0) return Unauthorized(context, basic: true);
|
|
var username = credentials[..delimiter];
|
|
var password = credentials[(delimiter + 1)..];
|
|
if (!Regex.IsMatch(username, "\\A[a-z0-9_]{3,32}\\z"))
|
|
return Unauthorized(context, basic: true);
|
|
|
|
if (context.Request.ContentLength > 0 || context.Request.Headers.ContainsKey("Transfer-Encoding"))
|
|
return ApiError(context, 400, "invalid_request", "Вход принимает Basic без тела запроса");
|
|
|
|
var session = await sessions.LoginAsync(username, password);
|
|
return session is null
|
|
? Unauthorized(context, basic: true)
|
|
: Results.Json(session, statusCode: StatusCodes.Status201Created);
|
|
});
|
|
|
|
app.MapDelete("/api/v1/auth/sessions/current", async (HttpContext context, SessionService sessions) =>
|
|
{
|
|
var (user, tokenHash) = await sessions.AuthenticateAsync(context);
|
|
if (user is null || tokenHash is null) return Unauthorized(context);
|
|
return await sessions.RevokeAsync(tokenHash)
|
|
? Results.NoContent()
|
|
: Unauthorized(context);
|
|
});
|
|
|
|
return app;
|
|
}
|
|
}
|