backend: Add concurrency checks to admin user edits
This commit is contained in:
1 parent
91d0c06c83
commit
bd8eb65e56
18 files changed
+216
-23
No files matched your search
@@ -151,13 +151,17 @@ public sealed class AdminUsersTests
|
||||
|
||||
using var editPage = await client.GetAsync(UsersPath + "/7/edit", ct);
|
||||
Assert.Equal(HttpStatusCode.OK, editPage.StatusCode);
|
||||
Assert.Contains("[email protected]", await editPage.Content.ReadAsStringAsync(ct));
|
||||
var editHtml = await editPage.Content.ReadAsStringAsync(ct);
|
||||
Assert.Contains("[email protected]", editHtml);
|
||||
Assert.Matches("""<input\b(?=[^>]*name="RowVersion")(?=[^>]*value="3")[^>]*>""", editHtml);
|
||||
fields.Remove("Password");
|
||||
fields["RowVersion"] = "3";
|
||||
using var editForm = new FormUrlEncodedContent(fields);
|
||||
using var edited = await client.PostAsync(UsersPath + "/7/edit", editForm, ct);
|
||||
Assert.Equal(HttpStatusCode.Redirect, edited.StatusCode);
|
||||
Assert.Equal(HttpMethod.Put, backend.Requests[^1].Method);
|
||||
Assert.Contains("\"password\":null", backend.Requests[^1].Body);
|
||||
Assert.Contains("\"rowVersion\":3", backend.Requests[^1].Body);
|
||||
|
||||
var bulk = new List<KeyValuePair<string, string>>
|
||||
{
|
||||
@@ -233,6 +237,38 @@ public sealed class AdminUsersTests
|
||||
(backend.Requests[^1].Method, backend.Requests[^1].Uri.AbsolutePath));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StaleEditReloadsTheCurrentAccountAndShowsTheConflict()
|
||||
{
|
||||
var backend = new AdminUsersBackend(staleEdit: true);
|
||||
await using var application = CreateApplication(backend);
|
||||
using var client = CreateClient(application);
|
||||
SignIn(application.Services, client, UserRoles.Admin);
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
using var editPage = await client.GetAsync(UsersPath + "/7/edit", ct);
|
||||
using var form = new FormUrlEncodedContent(new Dictionary<string, string>
|
||||
{
|
||||
["__RequestVerificationToken"] = AntiforgeryToken(await editPage.Content.ReadAsStringAsync(ct)),
|
||||
["FirstName"] = "Jan",
|
||||
["LastName"] = "Novák",
|
||||
["Email"] = "[email protected]",
|
||||
["Role"] = UserRoles.Admin,
|
||||
["RowVersion"] = "2",
|
||||
});
|
||||
|
||||
using var response = await client.PostAsync(UsersPath + "/7/edit?q=Jan", form, ct);
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.StartsWith(UsersPath + "/7/edit?q=Jan", response.Headers.Location?.OriginalString);
|
||||
Assert.Contains("\"rowVersion\":2", backend.Requests[^1].Body);
|
||||
|
||||
using var fresh = await client.GetAsync(response.Headers.Location, ct);
|
||||
Assert.Equal(HttpStatusCode.OK, fresh.StatusCode);
|
||||
var html = WebUtility.HtmlDecode(await fresh.Content.ReadAsStringAsync(ct));
|
||||
Assert.Contains("Účet se mezitím změnil.", html);
|
||||
Assert.Matches("""<input\b(?=[^>]*name="RowVersion")(?=[^>]*value="3")[^>]*>""", html);
|
||||
Assert.Contains("value=\"STUDENT\" selected=\"selected\"", html);
|
||||
}
|
||||
|
||||
private static string AntiforgeryToken(string html)
|
||||
{
|
||||
var token = Regex.Match(html, "name=\"__RequestVerificationToken\"[^>]*value=\"([^\"]+)\"").Groups[1].Value;
|
||||
@@ -252,7 +288,7 @@ public sealed class AdminUsersTests
|
||||
BaseAddress = new Uri("https://localhost"),
|
||||
});
|
||||
|
||||
private sealed class AdminUsersBackend(bool failVerification = false) : HttpMessageHandler
|
||||
private sealed class AdminUsersBackend(bool failVerification = false, bool staleEdit = false) : HttpMessageHandler
|
||||
{
|
||||
public List<(HttpMethod Method, Uri Uri, string? Body)> Requests { get; } = [];
|
||||
|
||||
@@ -268,6 +304,13 @@ public sealed class AdminUsersTests
|
||||
{"id":7,"email":"[email protected]","firstName":"Jan","lastName":"Novák","role":"STUDENT","isActive":true,"emailConfirmed":false,"emailNotificationsEnabled":true,"verificationEmailSent":false}
|
||||
""", Encoding.UTF8, "application/json"),
|
||||
};
|
||||
if (request.Method == HttpMethod.Put && uri.AbsolutePath == "/api/v1/admin/users/7" && staleEdit)
|
||||
return new HttpResponseMessage(HttpStatusCode.Conflict)
|
||||
{
|
||||
Content = new StringContent("""
|
||||
{"type":"urn:ntbug:account-version-conflict","title":"Účet se mezitím změnil.","status":409}
|
||||
""", Encoding.UTF8, "application/problem+json"),
|
||||
};
|
||||
if (request.Method != HttpMethod.Get)
|
||||
return new HttpResponseMessage(HttpStatusCode.NoContent);
|
||||
|
||||
@@ -275,7 +318,7 @@ public sealed class AdminUsersTests
|
||||
return new HttpResponseMessage(HttpStatusCode.OK)
|
||||
{
|
||||
Content = new StringContent("""
|
||||
{"id":7,"email":"[email protected]","firstName":"Jan","lastName":"Novák","role":"STUDENT","isActive":true,"emailConfirmed":false,"emailNotificationsEnabled":true}
|
||||
{"id":7,"email":"[email protected]","firstName":"Jan","lastName":"Novák","role":"STUDENT","isActive":true,"emailConfirmed":false,"emailNotificationsEnabled":true,"rowVersion":3}
|
||||
""", Encoding.UTF8, "application/json"),
|
||||
};
|
||||
|
||||
|
||||
@@ -8,11 +8,12 @@ namespace Helpdesk.Web.Api;
|
||||
/// Neúspěšná odpověď API ve formátu ProblemDetails (RFC 9457). Nese stav, titulek
|
||||
/// a u validačních chyb seznam chyb podle polí (klíče jsou názvy vlastností v camelCase).
|
||||
/// </summary>
|
||||
public sealed class ApiException(HttpStatusCode statusCode, string? title, IReadOnlyDictionary<string, string[]> errors)
|
||||
public sealed class ApiException(HttpStatusCode statusCode, string? title, IReadOnlyDictionary<string, string[]> errors, string? problemType = null)
|
||||
: Exception(title ?? $"API vrátilo stav {(int)statusCode}.")
|
||||
{
|
||||
public HttpStatusCode StatusCode { get; } = statusCode;
|
||||
public string? Title { get; } = title;
|
||||
public string? ProblemType { get; } = problemType;
|
||||
public IReadOnlyDictionary<string, string[]> Errors { get; } = errors;
|
||||
|
||||
/// <summary>Text pro uživatele. API píše titulky chyb česky, kromě odpovědí bez těla (např. 429).</summary>
|
||||
@@ -33,6 +34,7 @@ public sealed class ApiException(HttpStatusCode statusCode, string? title, IRead
|
||||
public static async Task<ApiException> FromResponseAsync(HttpResponseMessage response, CancellationToken ct)
|
||||
{
|
||||
string? title = null;
|
||||
string? type = null;
|
||||
Dictionary<string, string[]> errors = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
if (response.Content.Headers.ContentType?.MediaType is { } mediaType && mediaType.Contains("json", StringComparison.OrdinalIgnoreCase))
|
||||
@@ -41,6 +43,7 @@ public sealed class ApiException(HttpStatusCode statusCode, string? title, IRead
|
||||
{
|
||||
var problem = await response.Content.ReadFromJsonAsync<ProblemBody>(ct);
|
||||
title = problem?.Title;
|
||||
type = problem?.Type;
|
||||
if (problem?.Errors is { } fieldErrors)
|
||||
{
|
||||
foreach (var (field, messages) in fieldErrors)
|
||||
@@ -53,10 +56,10 @@ public sealed class ApiException(HttpStatusCode statusCode, string? title, IRead
|
||||
}
|
||||
}
|
||||
|
||||
return new ApiException(response.StatusCode, title, errors);
|
||||
return new ApiException(response.StatusCode, title, errors, type);
|
||||
}
|
||||
|
||||
private sealed record ProblemBody(string? Title, Dictionary<string, string[]>? Errors);
|
||||
private sealed record ProblemBody(string? Title, Dictionary<string, string[]>? Errors, string? Type);
|
||||
}
|
||||
|
||||
internal static class ApiResponse
|
||||
|
||||
@@ -53,10 +53,11 @@ public sealed record AdminUserDto(
|
||||
}
|
||||
|
||||
public sealed record AdminUserDetailsDto(int Id, string Email, string FirstName, string LastName, string? Phone,
|
||||
string Role, bool IsActive, bool EmailConfirmed, bool EmailNotificationsEnabled, bool? VerificationEmailSent = null);
|
||||
string Role, bool IsActive, bool EmailConfirmed, bool EmailNotificationsEnabled, int RowVersion,
|
||||
bool? VerificationEmailSent = null);
|
||||
|
||||
public sealed record SaveAdminUserRequest(string Email, string FirstName, string LastName, string? Phone,
|
||||
string Role, bool IsActive, bool EmailConfirmed, bool EmailNotificationsEnabled, string? Password);
|
||||
string Role, bool IsActive, bool EmailConfirmed, bool EmailNotificationsEnabled, string? Password, int? RowVersion);
|
||||
|
||||
/// <summary>Stránkovaný seznam z API: <c>{ items, totalCount, page, pageSize }</c>.</summary>
|
||||
public sealed record PagedResult<T>(IReadOnlyList<T> Items, int TotalCount, int Page, int PageSize)
|
||||
|
||||
@@ -45,6 +45,7 @@ public sealed class AdminUsersController(HelpdeskApiClient api) : Controller
|
||||
{
|
||||
Id = user.Id,
|
||||
Query = query,
|
||||
RowVersion = user.RowVersion,
|
||||
Email = user.Email,
|
||||
FirstName = user.FirstName,
|
||||
LastName = user.LastName,
|
||||
@@ -162,6 +163,12 @@ public sealed class AdminUsersController(HelpdeskApiClient api) : Controller
|
||||
if (id is not null && id == CurrentUserId)
|
||||
return RedirectToAction("Index", "Profile");
|
||||
|
||||
if (id is int userId && model.RowVersion is null or < 0)
|
||||
{
|
||||
TempData.SetError("Formulář nemá platnou verzi účtu. Změny zadejte znovu.");
|
||||
return BackToEdit(userId, query);
|
||||
}
|
||||
|
||||
model.Id = id;
|
||||
model.Query = query;
|
||||
if (id is null && string.IsNullOrWhiteSpace(model.Password))
|
||||
@@ -180,6 +187,12 @@ public sealed class AdminUsersController(HelpdeskApiClient api) : Controller
|
||||
}
|
||||
return BackToList(query);
|
||||
}
|
||||
catch (ApiException ex) when (id is int editedUserId && ex is
|
||||
{ StatusCode: HttpStatusCode.Conflict, ProblemType: "urn:ntbug:account-version-conflict" })
|
||||
{
|
||||
TempData.SetError(ex.UserMessage);
|
||||
return BackToEdit(editedUserId, query);
|
||||
}
|
||||
catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.Conflict)
|
||||
{
|
||||
ModelState.AddApiErrors(ex, typeof(AdminUserForm));
|
||||
|
||||
@@ -17,6 +17,8 @@ public sealed class AdminUserForm
|
||||
[BindNever]
|
||||
public AdminUsersQuery Query { get; set; } = new();
|
||||
|
||||
public int? RowVersion { get; set; }
|
||||
|
||||
[Display(Name = "Jméno"), Required(ErrorMessage = "Zadejte jméno."), StringLength(100)]
|
||||
public string FirstName { get; set; } = "";
|
||||
|
||||
@@ -46,5 +48,5 @@ public sealed class AdminUserForm
|
||||
public bool EmailNotificationsEnabled { get; set; } = true;
|
||||
|
||||
public SaveAdminUserRequest ToRequest() => new(Email.Trim(), FirstName.Trim(), LastName.Trim(), Phone,
|
||||
Role, IsActive, EmailConfirmed, EmailNotificationsEnabled, Password);
|
||||
Role, IsActive, EmailConfirmed, EmailNotificationsEnabled, Password, RowVersion);
|
||||
}
|
||||
@@ -16,6 +16,10 @@
|
||||
<partial name="_FormErrors" />
|
||||
<form method="post" asp-action="@(isNew ? "New" : "Edit")" asp-route-id="@Model.Id"
|
||||
asp-route-q="@query.Q" asp-route-role="@query.Role" asp-route-page="@query.Page" novalidate>
|
||||
@if (!isNew)
|
||||
{
|
||||
<input asp-for="RowVersion" type="hidden" />
|
||||
}
|
||||
<div class="row g-3 mb-4">
|
||||
<div class="col-sm-6">
|
||||
<label asp-for="FirstName" class="form-label"></label>
|
||||
|
||||
Reference in new issue
Block a user