backend + web: Set passwords through email confirmation
This commit is contained in:
1 parent
bd8eb65e56
commit
ee5f1d3d10
23 files changed
+281
-110
No files matched your search
@@ -1,6 +1,5 @@
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using Helpdesk.Web.Api;
|
||||
using Helpdesk.Web.Auth;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
@@ -213,7 +212,6 @@ public sealed class AdminUsersTests
|
||||
["LastName"] = "Novák",
|
||||
["Email"] = "[email protected]",
|
||||
["Role"] = UserRoles.Student,
|
||||
["Password"] = "Initial-password",
|
||||
["IsActive"] = "true",
|
||||
["EmailConfirmed"] = "false",
|
||||
});
|
||||
@@ -269,13 +267,6 @@ public sealed class AdminUsersTests
|
||||
Assert.Contains("value=\"STUDENT\" selected=\"selected\"", html);
|
||||
}
|
||||
|
||||
private static string AntiforgeryToken(string html)
|
||||
{
|
||||
var token = Regex.Match(html, "name=\"__RequestVerificationToken\"[^>]*value=\"([^\"]+)\"").Groups[1].Value;
|
||||
Assert.NotEmpty(token);
|
||||
return token;
|
||||
}
|
||||
|
||||
private static WebApplicationFactory<Program> CreateApplication(AdminUsersBackend backend) =>
|
||||
new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
|
||||
builder.ConfigureTestServices(services => services.AddHttpClient(nameof(HelpdeskApiClient))
|
||||
|
||||
@@ -100,9 +100,9 @@ public class ModelStateExtensionsTests
|
||||
var error = new ApiException(HttpStatusCode.BadRequest, "Neplatná vstupní data.",
|
||||
new Dictionary<string, string[]> { ["newPassword"] = ["Heslo musí mít alespoň 8 znaků."] });
|
||||
|
||||
modelState.AddApiErrors(error, typeof(ResetPasswordViewModel));
|
||||
modelState.AddApiErrors(error, typeof(EmailPasswordViewModel));
|
||||
|
||||
Assert.Equal("Heslo musí mít alespoň 8 znaků.", modelState[nameof(ResetPasswordViewModel.NewPassword)]!.Errors.Single().ErrorMessage);
|
||||
Assert.Equal("Heslo musí mít alespoň 8 znaků.", modelState[nameof(EmailPasswordViewModel.NewPassword)]!.Errors.Single().ErrorMessage);
|
||||
Assert.False(modelState.ContainsKey(string.Empty));
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Helpdesk.Web.Api;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.AspNetCore.TestHost;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using static Helpdesk.Web.Tests.WebTestSession;
|
||||
|
||||
namespace Helpdesk.Web.Tests;
|
||||
|
||||
public sealed class RegistrationTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task RegistrationRequestsAnEmailAndConfirmationSetsThePassword()
|
||||
{
|
||||
var backend = new RegistrationBackend();
|
||||
await using var application = new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
|
||||
builder.ConfigureTestServices(services => services.AddHttpClient(nameof(AuthApiClient))
|
||||
.ConfigurePrimaryHttpMessageHandler(() => backend)));
|
||||
using var client = application.CreateClient(new WebApplicationFactoryClientOptions
|
||||
{
|
||||
AllowAutoRedirect = false,
|
||||
BaseAddress = new Uri("https://localhost"),
|
||||
});
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
|
||||
using var registration = await client.GetAsync("/register", ct);
|
||||
var registerHtml = await registration.Content.ReadAsStringAsync(ct);
|
||||
Assert.DoesNotContain("type=\"password\"", registerHtml);
|
||||
using var registerForm = new FormUrlEncodedContent(new Dictionary<string, string>
|
||||
{
|
||||
["__RequestVerificationToken"] = AntiforgeryToken(registerHtml),
|
||||
["Email"] = "[email protected]",
|
||||
["FirstName"] = "Jan",
|
||||
["LastName"] = "Novák",
|
||||
});
|
||||
using var registered = await client.PostAsync("/register", registerForm, ct);
|
||||
Assert.Equal(HttpStatusCode.OK, registered.StatusCode);
|
||||
var start = Assert.Single(backend.Requests);
|
||||
Assert.Equal("/api/v1/auth/register", start.Path);
|
||||
Assert.False(start.Body.TryGetProperty("password", out _));
|
||||
|
||||
using var link = await client.GetAsync("/confirm-email?token=email-token", ct);
|
||||
var confirmHtml = await link.Content.ReadAsStringAsync(ct);
|
||||
Assert.Contains("name=\"NewPassword\"", confirmHtml);
|
||||
Assert.Contains("name=\"ConfirmPassword\"", confirmHtml);
|
||||
Assert.Single(backend.Requests);
|
||||
var form = new Dictionary<string, string>
|
||||
{
|
||||
["__RequestVerificationToken"] = AntiforgeryToken(confirmHtml),
|
||||
["Token"] = "email-token",
|
||||
["NewPassword"] = "Mailbox-owner-password",
|
||||
["ConfirmPassword"] = "Different-password",
|
||||
};
|
||||
using var invalidForm = new FormUrlEncodedContent(form);
|
||||
using var invalid = await client.PostAsync("/confirm-email", invalidForm, ct);
|
||||
Assert.Equal(HttpStatusCode.OK, invalid.StatusCode);
|
||||
Assert.Contains("Hesla se neshodují.", WebUtility.HtmlDecode(await invalid.Content.ReadAsStringAsync(ct)));
|
||||
Assert.Single(backend.Requests);
|
||||
|
||||
form["ConfirmPassword"] = form["NewPassword"];
|
||||
using var confirmForm = new FormUrlEncodedContent(form);
|
||||
using var confirmed = await client.PostAsync("/confirm-email", confirmForm, ct);
|
||||
Assert.Equal(HttpStatusCode.Redirect, confirmed.StatusCode);
|
||||
Assert.Equal("/login", confirmed.Headers.Location?.OriginalString);
|
||||
var confirmation = backend.Requests[1];
|
||||
Assert.Equal("/api/v1/auth/confirm-email", confirmation.Path);
|
||||
Assert.Equal("email-token", confirmation.Body.GetProperty("token").GetString());
|
||||
Assert.Equal(form["NewPassword"], confirmation.Body.GetProperty("newPassword").GetString());
|
||||
}
|
||||
|
||||
private sealed class RegistrationBackend : HttpMessageHandler
|
||||
{
|
||||
public List<(string Path, JsonElement Body)> Requests { get; } = [];
|
||||
|
||||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
|
||||
{
|
||||
Assert.Equal(HttpMethod.Post, request.Method);
|
||||
var path = request.RequestUri!.AbsolutePath;
|
||||
using var json = JsonDocument.Parse(await request.Content!.ReadAsStringAsync(ct));
|
||||
Requests.Add((path, json.RootElement.Clone()));
|
||||
if (path == "/api/v1/auth/confirm-email")
|
||||
return new HttpResponseMessage(HttpStatusCode.NoContent);
|
||||
|
||||
Assert.Equal("/api/v1/auth/register", path);
|
||||
return new HttpResponseMessage(HttpStatusCode.Created)
|
||||
{
|
||||
Content = new StringContent("""
|
||||
{"id":7,"email":"[email protected]","firstName":"Jan","lastName":"Novák","role":"STUDENT","emailNotificationsEnabled":true}
|
||||
""", Encoding.UTF8, "application/json"),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Text.RegularExpressions;
|
||||
using Helpdesk.Web.Api;
|
||||
using Helpdesk.Web.Auth;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
@@ -9,6 +10,13 @@ namespace Helpdesk.Web.Tests;
|
||||
|
||||
internal static class WebTestSession
|
||||
{
|
||||
public static string AntiforgeryToken(string html)
|
||||
{
|
||||
var token = Regex.Match(html, "name=\"__RequestVerificationToken\"[^>]*value=\"([^\"]+)\"").Groups[1].Value;
|
||||
Assert.NotEmpty(token);
|
||||
return token;
|
||||
}
|
||||
|
||||
public static void SignIn(IServiceProvider services, HttpClient client, string role)
|
||||
{
|
||||
var scheme = CookieAuthenticationDefaults.AuthenticationScheme;
|
||||
|
||||
Reference in new issue
Block a user