Files

52 lines
2.3 KiB
C#
Raw Permalink Normal View History

using System.Net;
using System.Net.Http.Json;
namespace Helpdesk.Web.Api;
/// <summary>
/// Anonymní endpointy <c>auth/*</c>. Záměrně bez <see cref="BearerTokenHandler"/>:
/// obnova tokenu běží uvnitř ověřování cookie a čtení tokenu z cookie by se zacyklilo.
/// </summary>
public sealed class AuthApiClient(HttpClient http)
{
public async Task<AuthResponse> LoginAsync(LoginRequest request, CancellationToken ct)
{
using var response = await http.PostAsJsonAsync("auth/login", request, ct);
return await ApiResponse.ReadAsync<AuthResponse>(response, ct);
}
/// <summary>Registrace. Roli (student / vyučující) určí API podle domény e-mailu.</summary>
public async Task<UserDto> RegisterAsync(RegisterRequest request, CancellationToken ct)
{
using var response = await http.PostAsJsonAsync("auth/register", request, ct);
return await ApiResponse.ReadAsync<UserDto>(response, ct);
}
public async Task ConfirmEmailAsync(string token, CancellationToken ct)
{
using var response = await http.PostAsJsonAsync("auth/confirm-email", new EmailTokenRequest(token), ct);
await ApiResponse.EnsureSuccessAsync(response, ct);
}
/// <summary>API odpoví stejně, ať účet existuje, nebo ne – stránka tak neprozradí registrované e-maily.</summary>
public async Task ForgotPasswordAsync(string email, CancellationToken ct)
{
using var response = await http.PostAsJsonAsync("auth/forgot-password", new ForgotPasswordRequest(email), ct);
await ApiResponse.EnsureSuccessAsync(response, ct);
}
public async Task ResetPasswordAsync(ResetPasswordRequest request, CancellationToken ct)
{
using var response = await http.PostAsJsonAsync("auth/reset-password", request, ct);
await ApiResponse.EnsureSuccessAsync(response, ct);
}
/// <summary>Obnoví pár tokenů. Neplatný nebo už použitý refresh token → <c>null</c>.</summary>
public async Task<TokenSet?> RefreshAsync(string refreshToken, CancellationToken ct)
{
using var response = await http.PostAsJsonAsync("auth/refresh", new RefreshTokenRequest(refreshToken), ct);
if (response.StatusCode == HttpStatusCode.Unauthorized)
return null;
return (await ApiResponse.ReadAsync<AuthResponse>(response, ct)).Tokens;
}
}