Реализовать лабораторную работу 3
This commit is contained in:
@@ -0,0 +1,60 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
using Messenger.Api.Contracts;
|
||||
using Messenger.Api.Services;
|
||||
using static Messenger.Api.Services.ApiSupport;
|
||||
|
||||
namespace Messenger.Api.Endpoints;
|
||||
|
||||
public static class ChatEndpoints
|
||||
{
|
||||
public static IEndpointRouteBuilder MapChatEndpoints(this IEndpointRouteBuilder app)
|
||||
{
|
||||
app.MapPost("/api/v1/chats", async (HttpContext context, SessionService sessions, ChatService chats) =>
|
||||
{
|
||||
var (actor, _) = await sessions.AuthenticateAsync(context);
|
||||
if (actor is null) return Unauthorized(context);
|
||||
|
||||
var (request, error) = await ReadJsonAsync<CreateChatRequest>(context);
|
||||
if (error is not null) return error;
|
||||
if (string.IsNullOrWhiteSpace(request!.Title) || request.Title.EnumerateRunes().Count() > 100)
|
||||
return ApiError(context, 400, "invalid_request", "Некорректное название чата");
|
||||
if (request.MemberIds is null || request.MemberIds.Count is < 1 or > 100 ||
|
||||
request.MemberIds.Distinct().Count() != request.MemberIds.Count ||
|
||||
!request.MemberIds.Contains(actor.Id))
|
||||
return ApiError(context, 400, "invalid_request", "Некорректный список участников");
|
||||
|
||||
var chat = await chats.CreateAsync(request.Title, request.MemberIds);
|
||||
return chat is null
|
||||
? ApiError(context, 400, "invalid_request", "Один из участников не существует")
|
||||
: Results.Json(chat, statusCode: StatusCodes.Status201Created);
|
||||
});
|
||||
|
||||
app.MapGet("/api/v1/chats", async (HttpContext context, SessionService sessions, ChatService chats) =>
|
||||
{
|
||||
var (actor, _) = await sessions.AuthenticateAsync(context);
|
||||
if (actor is null) return Unauthorized(context);
|
||||
var (limit, limitError) = ParseLimit(context);
|
||||
if (limitError is not null) return limitError;
|
||||
var (cursor, cursorTime, cursorError) = ParseCursor(context, $"user:{actor.Id}");
|
||||
if (cursorError is not null) return cursorError;
|
||||
|
||||
var page = await chats.ListAsync(actor.Id, cursorTime, cursor?.Id, limit + 1);
|
||||
string? nextCursor = null;
|
||||
if (page.Count > limit)
|
||||
{
|
||||
var last = page[limit - 1];
|
||||
nextCursor = CursorService.EncodeChatCursor(new ChatCursor($"user:{actor.Id}", last.CreatedAt, last.Id));
|
||||
page = page.Take(limit).ToList();
|
||||
}
|
||||
return Results.Ok(new { items = page, next_cursor = nextCursor });
|
||||
});
|
||||
|
||||
app.MapGet("/api/v1/chats/{chat_id}", async (
|
||||
string chat_id, HttpContext context, SessionService sessions, ChatService chats) =>
|
||||
{
|
||||
var (actor, _) = await sessions.AuthenticateAsync(context);
|
||||
if (actor is null) return Unauthorized(context);
|
||||
if (!Guid.TryParse(chat_id, out var chatId))
|
||||
return ApiError(context, 400, "invalid_request", "Некорректный chat_id");
|
||||
|
||||
var chat = await chats.FindForMemberAsync(chatId, actor.Id);
|
||||
return chat is null
|
||||
? ApiError(context, 404, "not_found", "Чат не найден")
|
||||
: Results.Ok(chat);
|
||||
});
|
||||
|
||||
return app;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
using Messenger.Api.Data;
|
||||
using Messenger.Api.Services;
|
||||
using Messenger.Api.Infrastructure;
|
||||
|
||||
namespace Messenger.Api.Endpoints;
|
||||
|
||||
public static class HealthEndpoints
|
||||
{
|
||||
public static IEndpointRouteBuilder MapHealthEndpoints(this IEndpointRouteBuilder app)
|
||||
{
|
||||
app.MapGet("/health/live", () => Results.Ok(new { status = "ok" }));
|
||||
app.MapGet("/health/ready", async (HttpContext context, AppDatabase database, ReadinessState readiness) =>
|
||||
!readiness.IsStopping && await database.IsReadyAsync()
|
||||
? Results.Ok(new { status = "ok" })
|
||||
: ApiSupport.ApiError(context, 503, "unavailable", "База данных недоступна"));
|
||||
return app;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
using Messenger.Api.Contracts;
|
||||
using Messenger.Api.Services;
|
||||
using System.Text.Json;
|
||||
using static Messenger.Api.Services.ApiSupport;
|
||||
|
||||
namespace Messenger.Api.Endpoints;
|
||||
|
||||
public static class MessageEndpoints
|
||||
{
|
||||
public static IEndpointRouteBuilder MapMessageEndpoints(this IEndpointRouteBuilder app)
|
||||
{
|
||||
app.MapPost("/api/v1/chats/{chat_id}/messages", async (
|
||||
string chat_id, HttpContext context, SessionService sessions, ChatService chats, MessageService messages) =>
|
||||
{
|
||||
var (actor, _) = await sessions.AuthenticateAsync(context);
|
||||
if (actor is null) return Unauthorized(context);
|
||||
if (!Guid.TryParse(chat_id, out var chatId))
|
||||
return ApiError(context, 400, "invalid_request", "Некорректный chat_id");
|
||||
if (await chats.FindForMemberAsync(chatId, actor.Id) is null)
|
||||
return ApiError(context, 404, "not_found", "Чат не найден");
|
||||
|
||||
var keys = context.Request.Headers["Idempotency-Key"];
|
||||
var key = keys.ToString();
|
||||
if (keys.Count != 1 || key.Length is < 1 or > 128 ||
|
||||
key.Any(c => !char.IsAsciiLetterOrDigit(c) && c is not '.' and not '_' and not ':' and not '-'))
|
||||
return ApiError(context, 400, "invalid_request", "Требуется корректный Idempotency-Key");
|
||||
|
||||
var (request, error) = await ReadJsonAsync<CreateMessageRequest>(context);
|
||||
if (error is not null) return error;
|
||||
if (string.IsNullOrWhiteSpace(request!.Text) || request.Text.EnumerateRunes().Count() > 4000)
|
||||
return ApiError(context, 400, "invalid_request", "Некорректный текст сообщения");
|
||||
if (request.AttachmentIds.ValueKind != JsonValueKind.Undefined &&
|
||||
(request.AttachmentIds.ValueKind != JsonValueKind.Array || request.AttachmentIds.GetArrayLength() != 0))
|
||||
return ApiError(context, 400, "invalid_request", "Вложения в этой версии не поддерживаются");
|
||||
|
||||
var message = await messages.CreateAsync(chatId, actor.Id, request.Text, key);
|
||||
if (message is null)
|
||||
return ApiError(context, 409, "conflict", "Этот ключ уже использован для другого сообщения");
|
||||
return Results.Json(message, statusCode: StatusCodes.Status201Created);
|
||||
});
|
||||
|
||||
app.MapGet("/api/v1/chats/{chat_id}/messages", async (
|
||||
string chat_id, HttpContext context, SessionService sessions, ChatService chats, MessageService messages) =>
|
||||
{
|
||||
var (actor, _) = await sessions.AuthenticateAsync(context);
|
||||
if (actor is null) return Unauthorized(context);
|
||||
if (!Guid.TryParse(chat_id, out var chatId))
|
||||
return ApiError(context, 400, "invalid_request", "Некорректный chat_id");
|
||||
if (await chats.FindForMemberAsync(chatId, actor.Id) is null)
|
||||
return ApiError(context, 404, "not_found", "Чат не найден");
|
||||
var (limit, limitError) = ParseLimit(context);
|
||||
if (limitError is not null) return limitError;
|
||||
var (cursor, cursorTime, cursorError) = ParseCursor(context, $"chat:{chatId}");
|
||||
if (cursorError is not null) return cursorError;
|
||||
|
||||
var page = await messages.ListAsync(chatId, cursorTime, cursor?.Id, limit + 1);
|
||||
string? nextCursor = null;
|
||||
if (page.Count > limit)
|
||||
{
|
||||
var last = page[limit - 1];
|
||||
nextCursor = CursorService.EncodeChatCursor(new ChatCursor($"chat:{chatId}", last.CreatedAt, last.Id));
|
||||
page = page.Take(limit).ToList();
|
||||
}
|
||||
return Results.Ok(new { items = page, next_cursor = nextCursor });
|
||||
});
|
||||
|
||||
return app;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
using Messenger.Api.Data;
|
||||
using Messenger.Api.Services;
|
||||
using static Messenger.Api.Services.ApiSupport;
|
||||
|
||||
namespace Messenger.Api.Endpoints;
|
||||
|
||||
public static class ReactionEndpoints
|
||||
{
|
||||
public static IEndpointRouteBuilder MapReactionEndpoints(this IEndpointRouteBuilder app)
|
||||
{
|
||||
app.MapGet("/api/ui/chats/{chat_id}/reactions", async (
|
||||
string chat_id, HttpContext context, SessionService sessions, ChatService chats, AppDatabase database) =>
|
||||
{
|
||||
var (actor, _) = await sessions.AuthenticateAsync(context);
|
||||
if (actor is null) return Unauthorized(context);
|
||||
if (!Guid.TryParse(chat_id, out var chatId)) return ApiError(context, 400, "invalid_request", "Некорректный chat_id");
|
||||
if (await chats.FindForMemberAsync(chatId, actor.Id) is null) return ApiError(context, 404, "not_found", "Чат не найден");
|
||||
var values = context.Request.Query["message_ids"].ToString().Split(',');
|
||||
if (values.Length is < 1 or > 100 || values.Any(value => !Guid.TryParse(value, out _)))
|
||||
return ApiError(context, 400, "invalid_request", "Укажите от 1 до 100 ID сообщений");
|
||||
var ids = values.Select(Guid.Parse).Distinct().ToArray();
|
||||
return Results.Ok(new { items = await database.ListReactionsAsync(chatId, ids, actor.Id) });
|
||||
});
|
||||
app.MapMethods("/api/ui/chats/{chat_id}/messages/{message_id}/reactions/{reaction}", ["PUT", "DELETE"], async (
|
||||
string chat_id, string message_id, string reaction, HttpContext context,
|
||||
SessionService sessions, ChatService chats, AppDatabase database) =>
|
||||
{
|
||||
var (actor, _) = await sessions.AuthenticateAsync(context);
|
||||
if (actor is null) return Unauthorized(context);
|
||||
if (!Guid.TryParse(chat_id, out var chatId) || !Guid.TryParse(message_id, out var messageId)
|
||||
|| reaction is not ("like" or "love" or "laugh" or "mushroom"))
|
||||
return ApiError(context, 400, "invalid_request", "Некорректная реакция или ID");
|
||||
if (await chats.FindForMemberAsync(chatId, actor.Id) is null) return ApiError(context, 404, "not_found", "Чат не найден");
|
||||
return await database.SetReactionAsync(chatId, messageId, actor.Id, reaction, context.Request.Method == "PUT")
|
||||
? Results.NoContent() : ApiError(context, 404, "not_found", "Сообщение не найдено");
|
||||
});
|
||||
return app;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
using Messenger.Api.Contracts;
|
||||
using Messenger.Api.Services;
|
||||
using Messenger.Api.Data;
|
||||
using Messenger.Api.Infrastructure;
|
||||
using static Messenger.Api.Services.ApiSupport;
|
||||
|
||||
namespace Messenger.Api.Endpoints;
|
||||
|
||||
public static class UiEndpoints
|
||||
{
|
||||
// The required /api/v1 history stays ascending. The web client has a separate,
|
||||
// optional route to open a large chat at its newest page and page backwards.
|
||||
public static IEndpointRouteBuilder MapUiEndpoints(this IEndpointRouteBuilder app)
|
||||
{
|
||||
app.MapGet("/api/ui/cluster", async (HttpContext context, SessionService sessions, ClusterPresence presence) =>
|
||||
{
|
||||
var (actor, _) = await sessions.AuthenticateAsync(context);
|
||||
if (actor is null) return Unauthorized(context);
|
||||
context.Response.Headers.CacheControl = "no-store";
|
||||
return Results.Ok(await presence.ReadAsync());
|
||||
});
|
||||
|
||||
app.MapGet("/api/ui/chats", async (HttpContext context, SessionService sessions, AppDatabase database) =>
|
||||
{
|
||||
var (actor, _) = await sessions.AuthenticateAsync(context);
|
||||
if (actor is null) return Unauthorized(context);
|
||||
var (limit, limitError) = ParseLimit(context);
|
||||
if (limitError is not null) return limitError;
|
||||
var (cursor, cursorTime, cursorError) = ParseCursor(context, $"ui-chats:{actor.Id}");
|
||||
if (cursorError is not null) return cursorError;
|
||||
var page = await database.ListChatPreviewsAsync(actor.Id, cursorTime, cursor?.Id, limit + 1);
|
||||
string? nextCursor = null;
|
||||
if (page.Count > limit)
|
||||
{
|
||||
var last = page[limit - 1];
|
||||
nextCursor = CursorService.EncodeChatCursor(new ChatCursor($"ui-chats:{actor.Id}", last.CreatedAt, last.Id));
|
||||
page = page.Take(limit).ToList();
|
||||
}
|
||||
return Results.Ok(new { items = page, next_cursor = nextCursor });
|
||||
});
|
||||
|
||||
app.MapGet("/api/ui/chats/{chat_id}/members", async (
|
||||
string chat_id, HttpContext context, SessionService sessions, ChatService chats, UserService users) =>
|
||||
{
|
||||
var (actor, _) = await sessions.AuthenticateAsync(context);
|
||||
if (actor is null) return Unauthorized(context);
|
||||
if (!Guid.TryParse(chat_id, out var chatId))
|
||||
return ApiError(context, 400, "invalid_request", "Некорректный chat_id");
|
||||
if (await chats.FindForMemberAsync(chatId, actor.Id) is null)
|
||||
return ApiError(context, 404, "not_found", "Чат не найден");
|
||||
return Results.Ok(new { items = await users.ListForChatAsync(chatId) });
|
||||
});
|
||||
|
||||
app.MapGet("/api/ui/chats/{chat_id}/messages", async (
|
||||
string chat_id, HttpContext context, SessionService sessions, ChatService chats, MessageService messages) =>
|
||||
{
|
||||
var (actor, _) = await sessions.AuthenticateAsync(context);
|
||||
if (actor is null) return Unauthorized(context);
|
||||
if (!Guid.TryParse(chat_id, out var chatId))
|
||||
return ApiError(context, 400, "invalid_request", "Некорректный chat_id");
|
||||
if (await chats.FindForMemberAsync(chatId, actor.Id) is null)
|
||||
return ApiError(context, 404, "not_found", "Чат не найден");
|
||||
var (limit, limitError) = ParseLimit(context);
|
||||
if (limitError is not null) return limitError;
|
||||
var (cursor, cursorTime, cursorError) = ParseCursor(context, $"recent-chat:{chatId}");
|
||||
if (cursorError is not null) return cursorError;
|
||||
|
||||
var page = await messages.ListAsync(chatId, cursorTime, cursor?.Id, limit + 1, newestFirst: true);
|
||||
string? nextCursor = null;
|
||||
if (page.Count > limit)
|
||||
{
|
||||
var last = page[limit - 1];
|
||||
nextCursor = CursorService.EncodeChatCursor(new ChatCursor($"recent-chat:{chatId}", last.CreatedAt, last.Id));
|
||||
page = page.Take(limit).ToList();
|
||||
}
|
||||
return Results.Ok(new { items = page, next_cursor = nextCursor });
|
||||
});
|
||||
return app;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
using System.Text.RegularExpressions;
|
||||
using Messenger.Api.Contracts;
|
||||
using Messenger.Api.Services;
|
||||
using static Messenger.Api.Services.ApiSupport;
|
||||
|
||||
namespace Messenger.Api.Endpoints;
|
||||
|
||||
public static class UserEndpoints
|
||||
{
|
||||
public static IEndpointRouteBuilder MapUserEndpoints(this IEndpointRouteBuilder app)
|
||||
{
|
||||
app.MapPost("/api/v1/users", async (HttpContext context, UserService users) =>
|
||||
{
|
||||
var (request, error) = await ReadJsonAsync<CreateUserRequest>(context);
|
||||
if (error is not null) return error;
|
||||
|
||||
if (request!.Username is null || !Regex.IsMatch(request.Username, "\\A[a-z0-9_]{3,32}\\z"))
|
||||
return ApiError(context, 400, "invalid_request", "Некорректный username");
|
||||
if (string.IsNullOrWhiteSpace(request.DisplayName) ||
|
||||
request.DisplayName.EnumerateRunes().Count() is < 1 or > 100)
|
||||
return ApiError(context, 400, "invalid_request", "Некорректный display_name");
|
||||
if (string.IsNullOrWhiteSpace(request.Password) ||
|
||||
request.Password.EnumerateRunes().Count() is < 12 or > 128)
|
||||
return ApiError(context, 400, "invalid_request", "Пароль должен содержать 12-128 символов");
|
||||
|
||||
var user = await users.RegisterAsync(request.Username, request.DisplayName, request.Password);
|
||||
return user is null
|
||||
? ApiError(context, 409, "conflict", "Username уже занят")
|
||||
: Results.Json(user, statusCode: StatusCodes.Status201Created);
|
||||
});
|
||||
|
||||
app.MapGet("/api/v1/users/me", async (HttpContext context, SessionService sessions) =>
|
||||
{
|
||||
var (user, _) = await sessions.AuthenticateAsync(context);
|
||||
return user is null ? Unauthorized(context) : Results.Ok(user);
|
||||
});
|
||||
|
||||
return app;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user