aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorcrupest <crupest@outlook.com>2020-11-15 20:54:33 +0800
committerGitHub <noreply@github.com>2020-11-15 20:54:33 +0800
commitdbc05b79c94894b25cbbb23025ed91dd1cf8a7a3 (patch)
tree7c2c792c141def97603cb43d98e83d29ac718e9a
parent63ec1050dd24e4123f73e9ed757376dc8128803d (diff)
parent1bbc60966cea77ec6ed7895bea1a01ad9c090c3a (diff)
downloadtimeline-dbc05b79c94894b25cbbb23025ed91dd1cf8a7a3.tar.gz
timeline-dbc05b79c94894b25cbbb23025ed91dd1cf8a7a3.tar.bz2
timeline-dbc05b79c94894b25cbbb23025ed91dd1cf8a7a3.zip
Merge pull request #188 from crupest/root-user
Forbid some operation on root user.
-rw-r--r--BackEnd/Timeline.ErrorCodes/ErrorCodes.cs2
-rw-r--r--BackEnd/Timeline.Tests/IntegratedTests/UserPermissionTest.cs18
-rw-r--r--BackEnd/Timeline.Tests/IntegratedTests/UserTest.cs7
-rw-r--r--BackEnd/Timeline.Tests/Services/UserDeleteServiceTest.cs27
-rw-r--r--BackEnd/Timeline.Tests/Services/UserPermissionServiceTest.cs14
-rw-r--r--BackEnd/Timeline/Controllers/UserController.cs26
-rw-r--r--BackEnd/Timeline/Models/Http/ErrorResponse.cs20
-rw-r--r--BackEnd/Timeline/Resources/Messages.Designer.cs18
-rw-r--r--BackEnd/Timeline/Resources/Messages.resx6
-rw-r--r--BackEnd/Timeline/Services/Exceptions/InvalidOperationOnRootUserException.cs16
-rw-r--r--BackEnd/Timeline/Services/UserDeleteService.cs5
-rw-r--r--BackEnd/Timeline/Services/UserPermissionService.cs10
12 files changed, 136 insertions, 33 deletions
diff --git a/BackEnd/Timeline.ErrorCodes/ErrorCodes.cs b/BackEnd/Timeline.ErrorCodes/ErrorCodes.cs
index 91e0c1fd..90c4ed99 100644
--- a/BackEnd/Timeline.ErrorCodes/ErrorCodes.cs
+++ b/BackEnd/Timeline.ErrorCodes/ErrorCodes.cs
@@ -43,6 +43,8 @@
{
public const int UsernameConflict = 1_102_01_01;
public const int ChangePassword_BadOldPassword = 1_102_02_01;
+ public const int ChangePermission_RootUser = 1_102_03_01;
+ public const int Delete_RootUser = 1_102_04_01;
}
public static class UserAvatar
diff --git a/BackEnd/Timeline.Tests/IntegratedTests/UserPermissionTest.cs b/BackEnd/Timeline.Tests/IntegratedTests/UserPermissionTest.cs
index 77cae590..3fb581f0 100644
--- a/BackEnd/Timeline.Tests/IntegratedTests/UserPermissionTest.cs
+++ b/BackEnd/Timeline.Tests/IntegratedTests/UserPermissionTest.cs
@@ -36,23 +36,15 @@ namespace Timeline.Tests.IntegratedTests
[Theory]
[MemberData(nameof(EveryPermissionTestData))]
- public async Task ModifyRootUserPermissionShouldHaveNoEffect(UserPermission permission)
+ public async Task ModifyRootUserPermission_Should_Error(UserPermission permission)
{
using var client = await CreateClientAsAdministrator();
- await client.TestDeleteAsync($"users/admin/permissions/{permission}");
+ await client.TestPutAssertErrorAsync($"users/admin/permissions/{permission}",
+ errorCode: ErrorCodes.UserController.ChangePermission_RootUser);
- {
- var body = await client.GetUserAsync("admin");
- body.Permissions.Should().BeEquivalentTo(Enum.GetNames<UserPermission>());
- }
-
- await client.TestPutAsync($"users/admin/permissions/{permission}");
-
- {
- var body = await client.GetUserAsync("admin");
- body.Permissions.Should().BeEquivalentTo(Enum.GetNames<UserPermission>());
- }
+ await client.TestDeleteAssertErrorAsync($"users/admin/permissions/{permission}",
+ errorCode: ErrorCodes.UserController.ChangePermission_RootUser);
}
[Theory]
diff --git a/BackEnd/Timeline.Tests/IntegratedTests/UserTest.cs b/BackEnd/Timeline.Tests/IntegratedTests/UserTest.cs
index 0c2e0b0d..55a37198 100644
--- a/BackEnd/Timeline.Tests/IntegratedTests/UserTest.cs
+++ b/BackEnd/Timeline.Tests/IntegratedTests/UserTest.cs
@@ -176,6 +176,13 @@ namespace Timeline.Tests.IntegratedTests
}
[Fact]
+ public async Task DeleteRootUser_Should_Error()
+ {
+ using var client = await CreateClientAsAdministrator();
+ await client.TestDeleteAssertErrorAsync("users/admin", errorCode: ErrorCodes.UserController.Delete_RootUser);
+ }
+
+ [Fact]
public async Task Delete_InvalidModel()
{
using var client = await CreateClientAsAdministrator();
diff --git a/BackEnd/Timeline.Tests/Services/UserDeleteServiceTest.cs b/BackEnd/Timeline.Tests/Services/UserDeleteServiceTest.cs
new file mode 100644
index 00000000..be11564e
--- /dev/null
+++ b/BackEnd/Timeline.Tests/Services/UserDeleteServiceTest.cs
@@ -0,0 +1,27 @@
+using FluentAssertions;
+using Microsoft.Extensions.Logging.Abstractions;
+using Moq;
+using System.Threading.Tasks;
+using Timeline.Services;
+using Timeline.Services.Exceptions;
+using Xunit;
+
+namespace Timeline.Tests.Services
+{
+ public class UserDeleteServiceTest : DatabaseBasedTest
+ {
+ private readonly Mock<ITimelineService> _mockTimelineService = new Mock<ITimelineService>();
+ private UserDeleteService _service = default!;
+
+ protected override void OnDatabaseCreated()
+ {
+ _service = new UserDeleteService(NullLogger<UserDeleteService>.Instance, Database, _mockTimelineService.Object);
+ }
+
+ [Fact]
+ public async Task DeleteRootUser_Should_Throw()
+ {
+ await _service.Awaiting(s => s.DeleteUser("admin")).Should().ThrowAsync<InvalidOperationOnRootUserException>();
+ }
+ }
+}
diff --git a/BackEnd/Timeline.Tests/Services/UserPermissionServiceTest.cs b/BackEnd/Timeline.Tests/Services/UserPermissionServiceTest.cs
index 5a4e4954..ea20bd18 100644
--- a/BackEnd/Timeline.Tests/Services/UserPermissionServiceTest.cs
+++ b/BackEnd/Timeline.Tests/Services/UserPermissionServiceTest.cs
@@ -48,18 +48,10 @@ namespace Timeline.Tests.Services
}
[Fact]
- public async Task ModifyPermissionOnRootUserShouldHaveNoEffect()
+ public async Task ModifyPermissionOnRootUser_Should_Throw()
{
- await _service.AddPermissionToUserAsync(1, UserPermission.AllTimelineManagement);
- {
- var permission = await _service.GetPermissionsOfUserAsync(1);
- permission.Should().BeEquivalentTo(Enum.GetValues<UserPermission>());
- }
- await _service.RemovePermissionFromUserAsync(1, UserPermission.AllTimelineManagement);
- {
- var permission = await _service.GetPermissionsOfUserAsync(1);
- permission.Should().BeEquivalentTo(Enum.GetValues<UserPermission>());
- }
+ await _service.Awaiting(s => s.AddPermissionToUserAsync(1, UserPermission.AllTimelineManagement)).Should().ThrowAsync<InvalidOperationOnRootUserException>();
+ await _service.Awaiting(s => s.RemovePermissionFromUserAsync(1, UserPermission.AllTimelineManagement)).Should().ThrowAsync<InvalidOperationOnRootUserException>();
}
[Fact]
diff --git a/BackEnd/Timeline/Controllers/UserController.cs b/BackEnd/Timeline/Controllers/UserController.cs
index bbdb5d57..8edae139 100644
--- a/BackEnd/Timeline/Controllers/UserController.cs
+++ b/BackEnd/Timeline/Controllers/UserController.cs
@@ -138,15 +138,23 @@ namespace Timeline.Controllers
/// <returns>Info of deletion.</returns>
[HttpDelete("users/{username}"), PermissionAuthorize(UserPermission.UserManagement)]
[ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status403Forbidden)]
public async Task<ActionResult<CommonDeleteResponse>> Delete([FromRoute][Username] string username)
{
- var delete = await _userDeleteService.DeleteUser(username);
- if (delete)
- return Ok(CommonDeleteResponse.Delete());
- else
- return Ok(CommonDeleteResponse.NotExist());
+ try
+ {
+ var delete = await _userDeleteService.DeleteUser(username);
+ if (delete)
+ return Ok(CommonDeleteResponse.Delete());
+ else
+ return Ok(CommonDeleteResponse.NotExist());
+ }
+ catch (InvalidOperationOnRootUserException)
+ {
+ return BadRequest(ErrorResponse.UserController.Delete_RootUser());
+ }
}
/// <summary>
@@ -212,6 +220,10 @@ namespace Timeline.Controllers
{
return NotFound(ErrorResponse.UserCommon.NotExist());
}
+ catch (InvalidOperationOnRootUserException)
+ {
+ return BadRequest(ErrorResponse.UserController.ChangePermission_RootUser());
+ }
}
[HttpDelete("users/{username}/permissions/{permission}"), PermissionAuthorize(UserPermission.UserManagement)]
@@ -232,6 +244,10 @@ namespace Timeline.Controllers
{
return NotFound(ErrorResponse.UserCommon.NotExist());
}
+ catch (InvalidOperationOnRootUserException)
+ {
+ return BadRequest(ErrorResponse.UserController.ChangePermission_RootUser());
+ }
}
}
}
diff --git a/BackEnd/Timeline/Models/Http/ErrorResponse.cs b/BackEnd/Timeline/Models/Http/ErrorResponse.cs
index ac86481f..10755fd1 100644
--- a/BackEnd/Timeline/Models/Http/ErrorResponse.cs
+++ b/BackEnd/Timeline/Models/Http/ErrorResponse.cs
@@ -156,6 +156,26 @@ namespace Timeline.Models.Http
return new CommonResponse(ErrorCodes.UserController.ChangePassword_BadOldPassword, string.Format(message, formatArgs));
}
+ public static CommonResponse ChangePermission_RootUser(params object?[] formatArgs)
+ {
+ return new CommonResponse(ErrorCodes.UserController.ChangePermission_RootUser, string.Format(UserController_ChangePermission_RootUser, formatArgs));
+ }
+
+ public static CommonResponse CustomMessage_ChangePermission_RootUser(string message, params object?[] formatArgs)
+ {
+ return new CommonResponse(ErrorCodes.UserController.ChangePermission_RootUser, string.Format(message, formatArgs));
+ }
+
+ public static CommonResponse Delete_RootUser(params object?[] formatArgs)
+ {
+ return new CommonResponse(ErrorCodes.UserController.Delete_RootUser, string.Format(UserController_Delete_RootUser, formatArgs));
+ }
+
+ public static CommonResponse CustomMessage_Delete_RootUser(string message, params object?[] formatArgs)
+ {
+ return new CommonResponse(ErrorCodes.UserController.Delete_RootUser, string.Format(message, formatArgs));
+ }
+
}
public static class UserAvatar
diff --git a/BackEnd/Timeline/Resources/Messages.Designer.cs b/BackEnd/Timeline/Resources/Messages.Designer.cs
index bb654ce6..c6b7d5e7 100644
--- a/BackEnd/Timeline/Resources/Messages.Designer.cs
+++ b/BackEnd/Timeline/Resources/Messages.Designer.cs
@@ -358,6 +358,24 @@ namespace Timeline.Resources {
}
/// <summary>
+ /// Looks up a localized string similar to You can&apos;t change permission of root user..
+ /// </summary>
+ internal static string UserController_ChangePermission_RootUser {
+ get {
+ return ResourceManager.GetString("UserController_ChangePermission_RootUser", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to You can&apos;t delete root user..
+ /// </summary>
+ internal static string UserController_Delete_RootUser {
+ get {
+ return ResourceManager.GetString("UserController_Delete_RootUser", resourceCulture);
+ }
+ }
+
+ /// <summary>
/// Looks up a localized string similar to You can&apos;t set permission unless you are administrator..
/// </summary>
internal static string UserController_Patch_Forbid_Administrator {
diff --git a/BackEnd/Timeline/Resources/Messages.resx b/BackEnd/Timeline/Resources/Messages.resx
index 2bbf494e..2386d1eb 100644
--- a/BackEnd/Timeline/Resources/Messages.resx
+++ b/BackEnd/Timeline/Resources/Messages.resx
@@ -216,6 +216,12 @@
<data name="UserController_ChangePassword_BadOldPassword" xml:space="preserve">
<value>Old password is wrong.</value>
</data>
+ <data name="UserController_ChangePermission_RootUser" xml:space="preserve">
+ <value>You can't change permission of root user.</value>
+ </data>
+ <data name="UserController_Delete_RootUser" xml:space="preserve">
+ <value>You can't delete root user.</value>
+ </data>
<data name="UserController_Patch_Forbid_Administrator" xml:space="preserve">
<value>You can't set permission unless you are administrator.</value>
</data>
diff --git a/BackEnd/Timeline/Services/Exceptions/InvalidOperationOnRootUserException.cs b/BackEnd/Timeline/Services/Exceptions/InvalidOperationOnRootUserException.cs
new file mode 100644
index 00000000..2bcab316
--- /dev/null
+++ b/BackEnd/Timeline/Services/Exceptions/InvalidOperationOnRootUserException.cs
@@ -0,0 +1,16 @@
+using System;
+
+namespace Timeline.Services.Exceptions
+{
+
+ [Serializable]
+ public class InvalidOperationOnRootUserException : InvalidOperationException
+ {
+ public InvalidOperationOnRootUserException() { }
+ public InvalidOperationOnRootUserException(string message) : base(message) { }
+ public InvalidOperationOnRootUserException(string message, Exception inner) : base(message, inner) { }
+ protected InvalidOperationOnRootUserException(
+ System.Runtime.Serialization.SerializationInfo info,
+ System.Runtime.Serialization.StreamingContext context) : base(info, context) { }
+ }
+}
diff --git a/BackEnd/Timeline/Services/UserDeleteService.cs b/BackEnd/Timeline/Services/UserDeleteService.cs
index b6306682..5365313b 100644
--- a/BackEnd/Timeline/Services/UserDeleteService.cs
+++ b/BackEnd/Timeline/Services/UserDeleteService.cs
@@ -7,6 +7,7 @@ using System.Threading.Tasks;
using Timeline.Entities;
using Timeline.Helpers;
using Timeline.Models.Validation;
+using Timeline.Services.Exceptions;
using static Timeline.Resources.Services.UserService;
namespace Timeline.Services
@@ -20,6 +21,7 @@ namespace Timeline.Services
/// <returns>True if user is deleted, false if user not exist.</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="username"/> is null.</exception>
/// <exception cref="ArgumentException">Thrown when <paramref name="username"/> is of bad format.</exception>
+ /// <exception cref="InvalidOperationOnRootUserException">Thrown when deleting root user.</exception>
Task<bool> DeleteUser(string username);
}
@@ -54,6 +56,9 @@ namespace Timeline.Services
if (user == null)
return false;
+ if (user.Id == 1)
+ throw new InvalidOperationOnRootUserException("Can't delete root user.");
+
await _timelineService.DeleteAllPostsOfUser(user.Id);
_databaseContext.Users.Remove(user);
diff --git a/BackEnd/Timeline/Services/UserPermissionService.cs b/BackEnd/Timeline/Services/UserPermissionService.cs
index ff09b4ee..42c93283 100644
--- a/BackEnd/Timeline/Services/UserPermissionService.cs
+++ b/BackEnd/Timeline/Services/UserPermissionService.cs
@@ -127,6 +127,7 @@ namespace Timeline.Services
/// <param name="userId">The id of the user.</param>
/// <param name="permission">The new permission.</param>
/// <exception cref="UserNotExistException">Thrown when user does not exist.</exception>
+ /// <exception cref="InvalidOperationOnRootUserException">Thrown when change root user's permission.</exception>
Task AddPermissionToUserAsync(long userId, UserPermission permission);
/// <summary>
@@ -136,6 +137,7 @@ namespace Timeline.Services
/// <param name="permission">The permission.</param>
/// <param name="checkUserExistence">Whether check the user's existence.</param>
/// <exception cref="UserNotExistException">Thrown when <paramref name="checkUserExistence"/> is true and user does not exist.</exception>
+ /// <exception cref="InvalidOperationOnRootUserException">Thrown when change root user's permission.</exception>
Task RemovePermissionFromUserAsync(long userId, UserPermission permission, bool checkUserExistence = true);
}
@@ -176,8 +178,8 @@ namespace Timeline.Services
public async Task AddPermissionToUserAsync(long userId, UserPermission permission)
{
- if (userId == 1) // The init administrator account.
- return;
+ if (userId == 1)
+ throw new InvalidOperationOnRootUserException("Can't change root user's permission.");
await CheckUserExistence(userId, true);
@@ -193,8 +195,8 @@ namespace Timeline.Services
public async Task RemovePermissionFromUserAsync(long userId, UserPermission permission, bool checkUserExistence = true)
{
- if (userId == 1) // The init administrator account.
- return;
+ if (userId == 1)
+ throw new InvalidOperationOnRootUserException("Can't change root user's permission.");
await CheckUserExistence(userId, checkUserExistence);