!fix(users): restrict AccountId assignment to Admin [SH-221]

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Arthur Bassi 2026-08-11 09:28:08 -03:00
parent ea2dedf579
commit d0724a0ac5
6 changed files with 352 additions and 41 deletions

View file

@ -7,6 +7,7 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Moq; using Moq;
using SeaHaven.Services.DTOs; using SeaHaven.Services.DTOs;
using SeaHaven.Services.Helpers;
using SeaHaven.Services.Interfaces; using SeaHaven.Services.Interfaces;
using System.Security.Claims; using System.Security.Claims;
using System.Text.Json; using System.Text.Json;
@ -19,22 +20,25 @@ public class UserControllerTests
private static string Json(object? value) => private static string Json(object? value) =>
JsonSerializer.Serialize(value, value?.GetType() ?? typeof(object)); JsonSerializer.Serialize(value, value?.GetType() ?? typeof(object));
private static UserController NewController(Mock<IUserService> service, string? userId = null) private static UserController NewController(
Mock<IUserService> service,
string? userId = null,
string? role = null)
{ {
var controller = new UserController(service.Object, Mock.Of<ILogger<UserController>>()); var controller = new UserController(service.Object, Mock.Of<ILogger<UserController>>());
var claims = new List<Claim>();
if (userId != null) if (userId != null)
claims.Add(new Claim(ClaimTypes.NameIdentifier, userId));
if (role != null)
claims.Add(new Claim(ClaimTypes.Role, role));
controller.ControllerContext = new ControllerContext
{ {
controller.ControllerContext = new ControllerContext HttpContext = new DefaultHttpContext
{ {
HttpContext = new DefaultHttpContext User = new ClaimsPrincipal(new ClaimsIdentity(claims, "Test"))
{ }
User = new ClaimsPrincipal(new ClaimsIdentity(new[] };
{
new Claim(ClaimTypes.NameIdentifier, userId)
}, "Test"))
}
};
}
return controller; return controller;
} }
@ -60,10 +64,13 @@ public class UserControllerTests
public async Task AddUser_Success_ReturnsUpdatedSuccessfully() public async Task AddUser_Success_ReturnsUpdatedSuccessfully()
{ {
var service = new Mock<IUserService>(); var service = new Mock<IUserService>();
service.Setup(s => s.AddUserAsync(It.IsAny<AddUserRequestDTO>(), It.IsAny<CancellationToken>())) service.Setup(s => s.AddUserAsync(
It.IsAny<AddUserRequestDTO>(),
It.IsAny<ClaimsPrincipal>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(new AddUserOutcomeDTO { Success = true }); .ReturnsAsync(new AddUserOutcomeDTO { Success = true });
var controller = NewController(service); var controller = NewController(service, "admin-1", "Admin");
var result = await controller.AddUser(new User_DTO { Name = "N", Email = "n@x.com", Role = "Admin" }, CancellationToken.None); var result = await controller.AddUser(new User_DTO { Name = "N", Email = "n@x.com", Role = "Admin" }, CancellationToken.None);
@ -71,16 +78,23 @@ public class UserControllerTests
var response = ok.Value.Should().BeOfType<DataResponse>().Subject; var response = ok.Value.Should().BeOfType<DataResponse>().Subject;
response.Status.Should().Be("200"); response.Status.Should().Be("200");
response.Message.Should().Be("Updated Successfully"); response.Message.Should().Be("Updated Successfully");
service.Verify(s => s.AddUserAsync(
It.IsAny<AddUserRequestDTO>(),
It.Is<ClaimsPrincipal>(p => p.IsInRole("Admin")),
It.IsAny<CancellationToken>()), Times.Once);
} }
[Fact] [Fact]
public async Task AddUser_Failure_ReturnsBadRequestWithServiceError() public async Task AddUser_Failure_ReturnsBadRequestWithServiceError()
{ {
var service = new Mock<IUserService>(); var service = new Mock<IUserService>();
service.Setup(s => s.AddUserAsync(It.IsAny<AddUserRequestDTO>(), It.IsAny<CancellationToken>())) service.Setup(s => s.AddUserAsync(
It.IsAny<AddUserRequestDTO>(),
It.IsAny<ClaimsPrincipal>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(new AddUserOutcomeDTO { Success = false, Error = "boom" }); .ReturnsAsync(new AddUserOutcomeDTO { Success = false, Error = "boom" });
var controller = NewController(service); var controller = NewController(service, "admin-1", "Admin");
var result = await controller.AddUser(new User_DTO(), CancellationToken.None); var result = await controller.AddUser(new User_DTO(), CancellationToken.None);
@ -90,30 +104,55 @@ public class UserControllerTests
response.Message.Should().Be("boom"); response.Message.Should().Be("boom");
} }
[Fact]
public async Task AddUser_ServiceForbidden_ReturnsForbid()
{
var service = new Mock<IUserService>();
service.Setup(s => s.AddUserAsync(
It.IsAny<AddUserRequestDTO>(),
It.IsAny<ClaimsPrincipal>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(new AddUserOutcomeDTO { Success = false, Error = UserMutationErrors.Forbidden });
var controller = NewController(service, "tech-1", "User");
var result = await controller.AddUser(
new User_DTO { Name = "N", Email = "n@x.com", Role = "User", AccountId = 99 },
CancellationToken.None);
result.Should().BeOfType<ForbidResult>();
}
[Fact] [Fact]
public async Task EditUser_NotFound_ReturnsUserNotFoundMessage() public async Task EditUser_NotFound_ReturnsUserNotFoundMessage()
{ {
var service = new Mock<IUserService>(); var service = new Mock<IUserService>();
service.Setup(s => s.EditUserAsync(It.IsAny<EditUserRequestDTO>(), It.IsAny<CancellationToken>())) service.Setup(s => s.EditUserAsync(
.ReturnsAsync(false); It.IsAny<EditUserRequestDTO>(),
It.IsAny<ClaimsPrincipal>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(new AddUserOutcomeDTO { Success = false, Error = UserMutationErrors.UserNotFound });
var controller = NewController(service); var controller = NewController(service, "admin-1", "Admin");
var result = await controller.EditUser(new EditUser_DTO { Id = "9" }, CancellationToken.None); var result = await controller.EditUser(new EditUser_DTO { Id = "9" }, CancellationToken.None);
var bad = result.Should().BeOfType<BadRequestObjectResult>().Subject; var bad = result.Should().BeOfType<BadRequestObjectResult>().Subject;
var response = bad.Value.Should().BeOfType<Response>().Subject; var response = bad.Value.Should().BeOfType<Response>().Subject;
response.Message.Should().Be("User not found"); response.Message.Should().Be(UserMutationErrors.UserNotFound);
} }
[Fact] [Fact]
public async Task EditUser_Found_ReturnsUpdatedSuccessfully() public async Task EditUser_Found_ReturnsUpdatedSuccessfully()
{ {
var service = new Mock<IUserService>(); var service = new Mock<IUserService>();
service.Setup(s => s.EditUserAsync(It.IsAny<EditUserRequestDTO>(), It.IsAny<CancellationToken>())) service.Setup(s => s.EditUserAsync(
.ReturnsAsync(true); It.IsAny<EditUserRequestDTO>(),
It.IsAny<ClaimsPrincipal>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(new AddUserOutcomeDTO { Success = true });
var controller = NewController(service); var controller = NewController(service, "admin-1", "Admin");
var result = await controller.EditUser(new EditUser_DTO { Id = "9" }, CancellationToken.None); var result = await controller.EditUser(new EditUser_DTO { Id = "9" }, CancellationToken.None);
@ -121,6 +160,25 @@ public class UserControllerTests
ok.Value.Should().BeOfType<DataResponse>(); ok.Value.Should().BeOfType<DataResponse>();
} }
[Fact]
public async Task EditUser_ServiceForbidden_ReturnsForbid()
{
var service = new Mock<IUserService>();
service.Setup(s => s.EditUserAsync(
It.IsAny<EditUserRequestDTO>(),
It.IsAny<ClaimsPrincipal>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(new AddUserOutcomeDTO { Success = false, Error = UserMutationErrors.Forbidden });
var controller = NewController(service, "tech-1", "User");
var result = await controller.EditUser(
new EditUser_DTO { Id = "tech-1", AccountId = 42, Email = "me@x.com", Role = "User" },
CancellationToken.None);
result.Should().BeOfType<ForbidResult>();
}
[Fact] [Fact]
public async Task DeleteUser_NotFound_ReturnsIdNotMatchedMessage() public async Task DeleteUser_NotFound_ReturnsIdNotMatchedMessage()
{ {

View file

@ -5,22 +5,36 @@ using Moq;
using SeaHaven.DataServices.Dto; using SeaHaven.DataServices.Dto;
using SeaHaven.DataServices.Interfaces; using SeaHaven.DataServices.Interfaces;
using SeaHaven.Services.DTOs; using SeaHaven.Services.DTOs;
using SeaHaven.Services.Helpers;
using SeaHaven.Services.Implementation; using SeaHaven.Services.Implementation;
using SeaHaven.Services.Interfaces; using SeaHaven.Services.Interfaces;
using System.Security.Claims;
using Xunit; using Xunit;
namespace Api.SeaHavenIndustries.Tests; namespace Api.SeaHavenIndustries.Tests;
public class UserServiceTests public class UserServiceTests
{ {
private static ClaimsPrincipal Principal(params string[] roles)
{
var claims = roles.Select(r => new Claim(ClaimTypes.Role, r)).ToList();
claims.Add(new Claim(ClaimTypes.NameIdentifier, "caller-1"));
return new ClaimsPrincipal(new ClaimsIdentity(claims, "Test"));
}
private static UserService NewService( private static UserService NewService(
Mock<IUserDataService> userData, Mock<IUserDataService> userData,
Mock<IEmailSender> email, Mock<IEmailSender> email,
out Mock<IUserRoleStore<ApplicationUser>> store) out Mock<IUserRoleStore<ApplicationUser>> store,
Mock<IAccountDataService>? accounts = null)
{ {
var (manager, s, _) = IdentityTestHelpers.CreateUserManager(); var (manager, s, _) = IdentityTestHelpers.CreateUserManager();
store = s; store = s;
return new UserService(manager, userData.Object, email.Object); return new UserService(
manager,
userData.Object,
(accounts ?? new Mock<IAccountDataService>()).Object,
email.Object);
} }
[Fact] [Fact]
@ -39,7 +53,7 @@ public class UserServiceTests
var users = (await service.GetUsersAsync(CancellationToken.None)).ToList(); var users = (await service.GetUsersAsync(CancellationToken.None)).ToList();
users.Should().HaveCount(2); users.Should().HaveCount(2);
users[0].Date.Should().Be("Jan 05 2026"); users[0].Date.Should().Be(new DateTime(2026, 1, 5).ToString("MMM dd yyyy"));
users[0].RoleName.Should().Be("Admin"); users[0].RoleName.Should().Be("Admin");
users[0].Status.Should().Be("Active"); users[0].Status.Should().Be("Active");
users[1].Date.Should().Be(""); users[1].Date.Should().Be("");
@ -91,16 +105,20 @@ public class UserServiceTests
} }
[Fact] [Fact]
public async Task EditUser_NotFound_ReturnsFalse() public async Task EditUser_NotFound_ReturnsUserNotFound()
{ {
var userData = new Mock<IUserDataService>(); var userData = new Mock<IUserDataService>();
userData.Setup(u => u.GetForEditAsync("x", It.IsAny<CancellationToken>())).ReturnsAsync((ApplicationUser?)null); userData.Setup(u => u.GetForEditAsync("x", It.IsAny<CancellationToken>())).ReturnsAsync((ApplicationUser?)null);
var service = NewService(userData, new Mock<IEmailSender>(), out _); var service = NewService(userData, new Mock<IEmailSender>(), out _);
var succeeded = await service.EditUserAsync(new EditUserRequestDTO { Id = "x", Email = "e@x.com", Name = "n", Role = "Admin" }, CancellationToken.None); var outcome = await service.EditUserAsync(
new EditUserRequestDTO { Id = "x", Email = "e@x.com", Name = "n", Role = "Admin" },
Principal("Admin"),
CancellationToken.None);
succeeded.Should().BeFalse(); outcome.Success.Should().BeFalse();
outcome.Error.Should().Be(UserMutationErrors.UserNotFound);
} }
[Fact] [Fact]
@ -140,7 +158,10 @@ public class UserServiceTests
store.Setup(s => s.AddToRoleAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>(), It.IsAny<CancellationToken>())) store.Setup(s => s.AddToRoleAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
var outcome = await service.AddUserAsync(new AddUserRequestDTO { Name = "N", Email = "n@x.com", Role = "Admin" }, CancellationToken.None); var outcome = await service.AddUserAsync(
new AddUserRequestDTO { Name = "N", Email = "n@x.com", Role = "Admin" },
Principal("Admin"),
CancellationToken.None);
outcome.Success.Should().BeTrue(); outcome.Success.Should().BeTrue();
store.Verify(s => s.CreateAsync(It.IsAny<ApplicationUser>(), It.IsAny<CancellationToken>()), Times.Once); store.Verify(s => s.CreateAsync(It.IsAny<ApplicationUser>(), It.IsAny<CancellationToken>()), Times.Once);
@ -166,12 +187,174 @@ public class UserServiceTests
store.Setup(s => s.CreateAsync(It.IsAny<ApplicationUser>(), It.IsAny<CancellationToken>())) store.Setup(s => s.CreateAsync(It.IsAny<ApplicationUser>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(IdentityResult.Failed(new IdentityError { Description = "duplicate" })); .ReturnsAsync(IdentityResult.Failed(new IdentityError { Description = "duplicate" }));
var outcome = await service.AddUserAsync(new AddUserRequestDTO { Name = "N", Email = "n@x.com", Role = "Admin" }, CancellationToken.None); var outcome = await service.AddUserAsync(
new AddUserRequestDTO { Name = "N", Email = "n@x.com", Role = "Admin" },
Principal("Admin"),
CancellationToken.None);
outcome.Success.Should().BeFalse(); outcome.Success.Should().BeFalse();
outcome.Error.Should().Be("duplicate"); outcome.Error.Should().Be("duplicate");
} }
[Fact]
public async Task AddUser_NonAdmin_CannotSetAccountId_OnSelfOrOthers()
{
var userData = new Mock<IUserDataService>();
var accounts = new Mock<IAccountDataService>();
accounts.Setup(a => a.ExistsAsync(99)).ReturnsAsync(true);
var service = NewService(userData, new Mock<IEmailSender>(), out _, accounts);
var selfOutcome = await service.AddUserAsync(
new AddUserRequestDTO { Name = "Me", Email = "me@x.com", Role = "User", AccountId = 99 },
Principal("User"),
CancellationToken.None);
var otherOutcome = await service.EditUserAsync(
new EditUserRequestDTO { Id = "other-1", Name = "Other", Email = "o@x.com", Role = "Dispatcher", AccountId = 99 },
Principal("Dispatcher"),
CancellationToken.None);
selfOutcome.Success.Should().BeFalse();
selfOutcome.Error.Should().Be(UserMutationErrors.Forbidden);
otherOutcome.Success.Should().BeFalse();
otherOutcome.Error.Should().Be(UserMutationErrors.Forbidden);
userData.Verify(u => u.UpdateUserAsync(It.IsAny<ApplicationUser>(), It.IsAny<CancellationToken>()), Times.Never);
accounts.Verify(a => a.ExistsAsync(It.IsAny<int>()), Times.Never);
}
[Fact]
public async Task EditUser_NonAdmin_CannotChangeOwnAccountScope()
{
var existing = IdentityTestHelpers.User("caller-1");
existing.AccountId = 1;
var userData = new Mock<IUserDataService>();
userData.Setup(u => u.GetForEditAsync("caller-1", It.IsAny<CancellationToken>())).ReturnsAsync(existing);
var accounts = new Mock<IAccountDataService>();
accounts.Setup(a => a.ExistsAsync(2)).ReturnsAsync(true);
var service = NewService(userData, new Mock<IEmailSender>(), out _, accounts);
var outcome = await service.EditUserAsync(
new EditUserRequestDTO
{
Id = "caller-1",
Name = "Alice",
Email = "alice@example.com",
Role = "User",
AccountId = 2
},
Principal("User"),
CancellationToken.None);
outcome.Success.Should().BeFalse();
outcome.Error.Should().Be(UserMutationErrors.Forbidden);
existing.AccountId.Should().Be(1);
userData.Verify(u => u.UpdateUserAsync(It.IsAny<ApplicationUser>(), It.IsAny<CancellationToken>()), Times.Never);
}
[Fact]
public async Task AddUser_Admin_InvalidAccountId_RejectsWithoutCreate()
{
var userData = new Mock<IUserDataService>();
var accounts = new Mock<IAccountDataService>();
accounts.Setup(a => a.ExistsAsync(404)).ReturnsAsync(false);
var service = NewService(userData, new Mock<IEmailSender>(), out var store, accounts);
var outcome = await service.AddUserAsync(
new AddUserRequestDTO { Name = "N", Email = "n@x.com", Role = "User", AccountId = 404 },
Principal("Admin"),
CancellationToken.None);
outcome.Success.Should().BeFalse();
outcome.Error.Should().Be(UserMutationErrors.AccountNotFound);
store.Verify(s => s.CreateAsync(It.IsAny<ApplicationUser>(), It.IsAny<CancellationToken>()), Times.Never);
userData.Verify(u => u.GetByIdAsync(It.IsAny<string>()), Times.Never);
}
[Fact]
public async Task EditUser_Admin_InvalidAccountId_RejectsWithoutSave()
{
var existing = IdentityTestHelpers.User("u9");
existing.AccountId = 1;
var userData = new Mock<IUserDataService>();
userData.Setup(u => u.GetForEditAsync("u9", It.IsAny<CancellationToken>())).ReturnsAsync(existing);
var accounts = new Mock<IAccountDataService>();
accounts.Setup(a => a.ExistsAsync(404)).ReturnsAsync(false);
var service = NewService(userData, new Mock<IEmailSender>(), out _, accounts);
var outcome = await service.EditUserAsync(
new EditUserRequestDTO { Id = "u9", Name = "N", Email = "n@x.com", Role = "User", AccountId = 404 },
Principal("Admin"),
CancellationToken.None);
outcome.Success.Should().BeFalse();
outcome.Error.Should().Be(UserMutationErrors.AccountNotFound);
existing.AccountId.Should().Be(1);
userData.Verify(u => u.UpdateUserAsync(It.IsAny<ApplicationUser>(), It.IsAny<CancellationToken>()), Times.Never);
}
[Fact]
public async Task AddUser_Admin_ValidAccountId_PersistsOnCreate()
{
var userData = new Mock<IUserDataService>();
userData.Setup(u => u.GetByIdAsync(It.IsAny<string>())).ReturnsAsync((ApplicationUser?)null);
var accounts = new Mock<IAccountDataService>();
accounts.Setup(a => a.ExistsAsync(10)).ReturnsAsync(true);
var service = NewService(userData, new Mock<IEmailSender>(), out var store, accounts);
store.As<IUserPasswordStore<ApplicationUser>>()
.Setup(s => s.SetPasswordHashAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.Returns(Task.CompletedTask);
ApplicationUser? created = null;
store.Setup(s => s.CreateAsync(It.IsAny<ApplicationUser>(), It.IsAny<CancellationToken>()))
.Callback<ApplicationUser, CancellationToken>((u, _) => created = u)
.ReturnsAsync(IdentityResult.Success);
store.Setup(s => s.AddToRoleAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.Returns(Task.CompletedTask);
var outcome = await service.AddUserAsync(
new AddUserRequestDTO { Name = "N", Email = "n@x.com", Role = "User", AccountId = 10 },
Principal("Admin"),
CancellationToken.None);
outcome.Success.Should().BeTrue();
created.Should().NotBeNull();
created!.AccountId.Should().Be(10);
accounts.Verify(a => a.ExistsAsync(10), Times.Once);
}
[Fact]
public async Task EditUser_Admin_ValidAccountId_PersistsOnEdit()
{
var existing = IdentityTestHelpers.User("u9");
existing.AccountId = 1;
var userData = new Mock<IUserDataService>();
userData.Setup(u => u.GetForEditAsync("u9", It.IsAny<CancellationToken>())).ReturnsAsync(existing);
var accounts = new Mock<IAccountDataService>();
accounts.Setup(a => a.ExistsAsync(10)).ReturnsAsync(true);
var service = NewService(userData, new Mock<IEmailSender>(), out var store, accounts);
store.Setup(s => s.GetRolesAsync(existing, It.IsAny<CancellationToken>()))
.ReturnsAsync(new List<string> { "User" });
store.Setup(s => s.RemoveFromRoleAsync(existing, "User", It.IsAny<CancellationToken>()))
.Returns(Task.CompletedTask);
store.Setup(s => s.AddToRoleAsync(existing, "User", It.IsAny<CancellationToken>()))
.Returns(Task.CompletedTask);
var outcome = await service.EditUserAsync(
new EditUserRequestDTO { Id = "u9", Name = "N", Email = "n@x.com", Role = "User", AccountId = 10 },
Principal("Admin"),
CancellationToken.None);
outcome.Success.Should().BeTrue();
existing.AccountId.Should().Be(10);
userData.Verify(u => u.UpdateUserAsync(existing, It.IsAny<CancellationToken>()), Times.Once);
}
private static bool ContainsStrongGeneratedPassword(string body) private static bool ContainsStrongGeneratedPassword(string body)
{ {
const string marker = "Your password is: "; const string marker = "Your password is: ";

View file

@ -5,6 +5,7 @@ using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using SeaHaven.Services.DTOs; using SeaHaven.Services.DTOs;
using SeaHaven.Services.Helpers;
using SeaHaven.Services.Interfaces; using SeaHaven.Services.Interfaces;
using System.Security.Claims; using System.Security.Claims;
@ -32,6 +33,7 @@ namespace Api.SeaHavenIndustries.Controllers
} }
[HttpPost] [HttpPost]
[Route("AddUser")] [Route("AddUser")]
[Authorize(Roles = "Admin")]
public async Task<IActionResult> AddUser(User_DTO user, CancellationToken cancellationToken) public async Task<IActionResult> AddUser(User_DTO user, CancellationToken cancellationToken)
{ {
try try
@ -44,9 +46,11 @@ namespace Api.SeaHavenIndustries.Controllers
Role = user.Role, Role = user.Role,
AccountId = user.AccountId AccountId = user.AccountId
}; };
var outcome = await _userService.AddUserAsync(dto, cancellationToken); var outcome = await _userService.AddUserAsync(dto, User, cancellationToken);
if (!outcome.Success) if (!outcome.Success)
{ {
if (string.Equals(outcome.Error, UserMutationErrors.Forbidden, StringComparison.Ordinal))
return Forbid();
return BadRequest(new Response { Status = "Error", Message = outcome.Error }); return BadRequest(new Response { Status = "Error", Message = outcome.Error });
} }
return Ok(new DataResponse { Message = "Updated Successfully", Status = "200" }); return Ok(new DataResponse { Message = "Updated Successfully", Status = "200" });
@ -60,6 +64,7 @@ namespace Api.SeaHavenIndustries.Controllers
} }
[HttpPut] [HttpPut]
[Route("EditUser")] [Route("EditUser")]
[Authorize(Roles = "Admin")]
public async Task<IActionResult> EditUser(EditUser_DTO user, CancellationToken cancellationToken) public async Task<IActionResult> EditUser(EditUser_DTO user, CancellationToken cancellationToken)
{ {
try try
@ -72,9 +77,13 @@ namespace Api.SeaHavenIndustries.Controllers
Role = user.Role, Role = user.Role,
AccountId = user.AccountId AccountId = user.AccountId
}; };
var succeeded = await _userService.EditUserAsync(dto, cancellationToken); var outcome = await _userService.EditUserAsync(dto, User, cancellationToken);
if (!succeeded) if (!outcome.Success)
return BadRequest(new Response { Status = "Error", Message = "User not found" }); {
if (string.Equals(outcome.Error, UserMutationErrors.Forbidden, StringComparison.Ordinal))
return Forbid();
return BadRequest(new Response { Status = "Error", Message = outcome.Error });
}
return Ok(new DataResponse { Message = "Updated Successfully", Status = "200" }); return Ok(new DataResponse { Message = "Updated Successfully", Status = "200" });
} }
catch (Exception ex) catch (Exception ex)

View file

@ -0,0 +1,10 @@
namespace SeaHaven.Services.Helpers
{
/// <summary>Stable user-mutation outcome messages (no internal detail).</summary>
public static class UserMutationErrors
{
public const string Forbidden = "Forbidden";
public const string AccountNotFound = "Account not found";
public const string UserNotFound = "User not found";
}
}

View file

@ -2,7 +2,9 @@ using Data.SeaHavenIndustries;
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity;
using SeaHaven.DataServices.Interfaces; using SeaHaven.DataServices.Interfaces;
using SeaHaven.Services.DTOs; using SeaHaven.Services.DTOs;
using SeaHaven.Services.Helpers;
using SeaHaven.Services.Interfaces; using SeaHaven.Services.Interfaces;
using System.Security.Claims;
using System.Security.Cryptography; using System.Security.Cryptography;
namespace SeaHaven.Services.Implementation namespace SeaHaven.Services.Implementation
@ -11,15 +13,18 @@ namespace SeaHaven.Services.Implementation
{ {
private readonly UserManager<ApplicationUser> _userManager; private readonly UserManager<ApplicationUser> _userManager;
private readonly IUserDataService _userDataService; private readonly IUserDataService _userDataService;
private readonly IAccountDataService _accountDataService;
private readonly IEmailSender _emailSender; private readonly IEmailSender _emailSender;
public UserService( public UserService(
UserManager<ApplicationUser> userManager, UserManager<ApplicationUser> userManager,
IUserDataService userDataService, IUserDataService userDataService,
IAccountDataService accountDataService,
IEmailSender emailSender) IEmailSender emailSender)
{ {
_userManager = userManager; _userManager = userManager;
_userDataService = userDataService; _userDataService = userDataService;
_accountDataService = accountDataService;
_emailSender = emailSender; _emailSender = emailSender;
} }
@ -37,8 +42,19 @@ namespace SeaHaven.Services.Implementation
}); });
} }
public async Task<AddUserOutcomeDTO> AddUserAsync(AddUserRequestDTO dto, CancellationToken cancellationToken) public async Task<AddUserOutcomeDTO> AddUserAsync(
AddUserRequestDTO dto,
ClaimsPrincipal caller,
CancellationToken cancellationToken)
{ {
var authFailure = EnsureAdminCaller(caller);
if (authFailure != null)
return authFailure;
var accountFailure = await EnsureAccountValidAsync(dto.AccountId);
if (accountFailure != null)
return accountFailure;
var model = new ApplicationUser var model = new ApplicationUser
{ {
UserName = dto.Email, UserName = dto.Email,
@ -80,7 +96,7 @@ namespace SeaHaven.Services.Implementation
{ {
var exist1 = await _userDataService.GetForEditAsync(model.Id, cancellationToken); var exist1 = await _userDataService.GetForEditAsync(model.Id, cancellationToken);
if (exist1 == null) if (exist1 == null)
return new AddUserOutcomeDTO { Success = false, Error = "User not found" }; return new AddUserOutcomeDTO { Success = false, Error = UserMutationErrors.UserNotFound };
var existingRole = await _userManager.GetRolesAsync(exist1); var existingRole = await _userManager.GetRolesAsync(exist1);
@ -103,11 +119,22 @@ namespace SeaHaven.Services.Implementation
} }
} }
public async Task<bool> EditUserAsync(EditUserRequestDTO dto, CancellationToken cancellationToken) public async Task<AddUserOutcomeDTO> EditUserAsync(
EditUserRequestDTO dto,
ClaimsPrincipal caller,
CancellationToken cancellationToken)
{ {
var authFailure = EnsureAdminCaller(caller);
if (authFailure != null)
return authFailure;
var accountFailure = await EnsureAccountValidAsync(dto.AccountId);
if (accountFailure != null)
return accountFailure;
var exist = await _userDataService.GetForEditAsync(dto.Id ?? "", cancellationToken); var exist = await _userDataService.GetForEditAsync(dto.Id ?? "", cancellationToken);
if (exist == null) if (exist == null)
return false; return new AddUserOutcomeDTO { Success = false, Error = UserMutationErrors.UserNotFound };
exist.FirstName = dto.Name; exist.FirstName = dto.Name;
if (string.IsNullOrWhiteSpace(dto.Email)) if (string.IsNullOrWhiteSpace(dto.Email))
@ -131,7 +158,7 @@ namespace SeaHaven.Services.Implementation
await _userManager.AddToRoleAsync(exist, dto.Role ?? ""); await _userManager.AddToRoleAsync(exist, dto.Role ?? "");
await _userDataService.UpdateUserAsync(exist, cancellationToken); await _userDataService.UpdateUserAsync(exist, cancellationToken);
return true; return new AddUserOutcomeDTO { Success = true };
} }
public async Task<bool> DeleteUserAsync(string id, CancellationToken cancellationToken) public async Task<bool> DeleteUserAsync(string id, CancellationToken cancellationToken)
@ -173,6 +200,29 @@ namespace SeaHaven.Services.Implementation
}; };
} }
private static AddUserOutcomeDTO? EnsureAdminCaller(ClaimsPrincipal caller)
{
if (caller is null || !caller.IsInRole("Admin"))
{
return new AddUserOutcomeDTO { Success = false, Error = UserMutationErrors.Forbidden };
}
return null;
}
private async Task<AddUserOutcomeDTO?> EnsureAccountValidAsync(int? accountId)
{
if (!accountId.HasValue)
return null;
if (accountId.Value <= 0 || !await _accountDataService.ExistsAsync(accountId.Value))
{
return new AddUserOutcomeDTO { Success = false, Error = UserMutationErrors.AccountNotFound };
}
return null;
}
private static string GenerateRandomPassword(int length = 8) private static string GenerateRandomPassword(int length = 8)
{ {
const string validChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_-+=<>?"; const string validChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_-+=<>?";

View file

@ -1,3 +1,4 @@
using System.Security.Claims;
using SeaHaven.Services.DTOs; using SeaHaven.Services.DTOs;
namespace SeaHaven.Services.Interfaces namespace SeaHaven.Services.Interfaces
@ -5,8 +6,8 @@ namespace SeaHaven.Services.Interfaces
public interface IUserService public interface IUserService
{ {
Task<IEnumerable<UserListRowDTO>> GetUsersAsync(CancellationToken cancellationToken); Task<IEnumerable<UserListRowDTO>> GetUsersAsync(CancellationToken cancellationToken);
Task<AddUserOutcomeDTO> AddUserAsync(AddUserRequestDTO dto, CancellationToken cancellationToken); Task<AddUserOutcomeDTO> AddUserAsync(AddUserRequestDTO dto, ClaimsPrincipal caller, CancellationToken cancellationToken);
Task<bool> EditUserAsync(EditUserRequestDTO dto, CancellationToken cancellationToken); Task<AddUserOutcomeDTO> EditUserAsync(EditUserRequestDTO dto, ClaimsPrincipal caller, CancellationToken cancellationToken);
Task<bool> DeleteUserAsync(string id, CancellationToken cancellationToken); Task<bool> DeleteUserAsync(string id, CancellationToken cancellationToken);
Task DeleteCurrentUserAsync(string userId, CancellationToken cancellationToken); Task DeleteCurrentUserAsync(string userId, CancellationToken cancellationToken);
Task<IReadOnlyList<UserProfileRowDTO>> GetUserProfileAsync(string userId, CancellationToken cancellationToken); Task<IReadOnlyList<UserProfileRowDTO>> GetUserProfileAsync(string userId, CancellationToken cancellationToken);