using System.Net; using EnvelopeGenerator.ReceiverUI.Options; using Microsoft.Extensions.Options; namespace EnvelopeGenerator.ReceiverUI.Services; public enum EnvelopeLoginResult { Success, InvalidCode, NotFound, Error } public class AuthService(HttpClient http, IOptions apiOptions) { private readonly ApiOptions _api = apiOptions.Value; /// /// Checks whether the current user holds a valid receiver token for the given envelope key. /// Calls GET /api/auth/check/envelope/{envelopeKey}. /// public async Task CheckEnvelopeAccessAsync(string envelopeKey, CancellationToken cancel = default) { var response = await http.GetAsync($"{_api.BaseUrl}/api/auth/check/envelope/{Uri.EscapeDataString(envelopeKey)}", cancel); return response.StatusCode == HttpStatusCode.OK; } /// /// Submits the access code for the given envelope key. /// Calls POST /api/Auth/envelope-receiver/{key} with multipart/form-data. /// On success the API sets an authentication cookie automatically. /// public async Task LoginEnvelopeReceiverAsync(string envelopeKey, string accessCode, CancellationToken cancel = default) { var form = new MultipartFormDataContent(); form.Add(new StringContent(accessCode), "AccessCode"); var response = await http.PostAsync( $"{_api.BaseUrl}/api/Auth/envelope-receiver/{Uri.EscapeDataString(envelopeKey)}", form, cancel); return response.StatusCode switch { HttpStatusCode.OK => EnvelopeLoginResult.Success, HttpStatusCode.Unauthorized => EnvelopeLoginResult.InvalidCode, HttpStatusCode.NotFound => EnvelopeLoginResult.NotFound, _ => EnvelopeLoginResult.Error }; } /// /// Removes the per-envelope receiver cookie for the given envelope key. /// Calls POST /api/auth/logout/envelope/{envelopeKey}. /// public async Task LogoutEnvelopeReceiverAsync(string envelopeKey, CancellationToken cancel = default) { var response = await http.PostAsync( $"{_api.BaseUrl}/api/auth/logout/envelope/{Uri.EscapeDataString(envelopeKey)}", null, cancel); return response.IsSuccessStatusCode; } }