diff options
author | crupest <crupest@outlook.com> | 2020-08-11 01:48:57 +0800 |
---|---|---|
committer | crupest <crupest@outlook.com> | 2020-08-11 01:48:57 +0800 |
commit | caa09ff7ce89088d2de0865c5141ab5f867b7b5c (patch) | |
tree | e68a43b71118bbaa229d0a28159af1452a232cb7 | |
parent | d31cc920403b1e1f90a48d2569084c2f6a4d7dbe (diff) | |
download | timeline-caa09ff7ce89088d2de0865c5141ab5f867b7b5c.tar.gz timeline-caa09ff7ce89088d2de0865c5141ab5f867b7b5c.tar.bz2 timeline-caa09ff7ce89088d2de0865c5141ab5f867b7b5c.zip |
Handle post deletion on user deletion correctly.
-rw-r--r-- | Timeline.Tests/IntegratedTests/TokenTest.cs | 4 | ||||
-rw-r--r-- | Timeline/Controllers/UserController.cs | 6 | ||||
-rw-r--r-- | Timeline/Services/TimelineService.cs | 35 | ||||
-rw-r--r-- | Timeline/Services/UserDeleteService.cs | 69 | ||||
-rw-r--r-- | Timeline/Services/UserService.cs | 44 | ||||
-rw-r--r-- | Timeline/Startup.cs | 1 |
6 files changed, 111 insertions, 48 deletions
diff --git a/Timeline.Tests/IntegratedTests/TokenTest.cs b/Timeline.Tests/IntegratedTests/TokenTest.cs index d1c31606..480d66cd 100644 --- a/Timeline.Tests/IntegratedTests/TokenTest.cs +++ b/Timeline.Tests/IntegratedTests/TokenTest.cs @@ -119,9 +119,9 @@ namespace Timeline.Tests.IntegratedTests using var client = await CreateDefaultClient();
var token = (await CreateUserTokenAsync(client, "user1", "user1pw")).Token;
- using (var scope = TestApp.Host.Services.CreateScope()) // UserService is scoped.
+ using (var scope = TestApp.Host.Services.CreateScope()) // UserDeleteService is scoped.
{
- var userService = scope.ServiceProvider.GetRequiredService<IUserService>();
+ var userService = scope.ServiceProvider.GetRequiredService<IUserDeleteService>();
await userService.DeleteUser("user1");
}
diff --git a/Timeline/Controllers/UserController.cs b/Timeline/Controllers/UserController.cs index c8c1e610..3986bb5b 100644 --- a/Timeline/Controllers/UserController.cs +++ b/Timeline/Controllers/UserController.cs @@ -22,12 +22,14 @@ namespace Timeline.Controllers {
private readonly ILogger<UserController> _logger;
private readonly IUserService _userService;
+ private readonly IUserDeleteService _userDeleteService;
private readonly IMapper _mapper;
- public UserController(ILogger<UserController> logger, IUserService userService, IMapper mapper)
+ public UserController(ILogger<UserController> logger, IUserService userService, IUserDeleteService userDeleteService, IMapper mapper)
{
_logger = logger;
_userService = userService;
+ _userDeleteService = userDeleteService;
_mapper = mapper;
}
@@ -102,7 +104,7 @@ namespace Timeline.Controllers [HttpDelete("users/{username}"), AdminAuthorize]
public async Task<ActionResult<CommonDeleteResponse>> Delete([FromRoute][Username] string username)
{
- var delete = await _userService.DeleteUser(username);
+ var delete = await _userDeleteService.DeleteUser(username);
if (delete)
return Ok(CommonDeleteResponse.Delete());
else
diff --git a/Timeline/Services/TimelineService.cs b/Timeline/Services/TimelineService.cs index ad410d15..283938fb 100644 --- a/Timeline/Services/TimelineService.cs +++ b/Timeline/Services/TimelineService.cs @@ -220,6 +220,12 @@ namespace Timeline.Services Task DeletePost(string timelineName, long postId);
/// <summary>
+ /// Delete all posts of the given user. Used when delete a user.
+ /// </summary>
+ /// <param name="userId">The id of the user.</param>
+ Task DeleteAllPostsOfUser(long userId);
+
+ /// <summary>
/// Change member of timeline.
/// </summary>
/// <param name="timelineName">The name of the timeline.</param>
@@ -776,6 +782,35 @@ namespace Timeline.Services }
}
+ public async Task DeleteAllPostsOfUser(long userId)
+ {
+ var posts = await _database.TimelinePosts.Where(p => p.AuthorId == userId).ToListAsync();
+
+ var now = _clock.GetCurrentTime();
+
+ var dataTags = new List<string>();
+
+ foreach (var post in posts)
+ {
+ if (post.Content != null)
+ {
+ if (post.ContentType == TimelinePostContentTypes.Image)
+ {
+ dataTags.Add(post.Content);
+ }
+ post.Content = null;
+ }
+ post.LastUpdated = now;
+ }
+
+ await _database.SaveChangesAsync();
+
+ foreach (var dataTag in dataTags)
+ {
+ await _dataManager.FreeEntry(dataTag);
+ }
+ }
+
public async Task ChangeProperty(string timelineName, TimelineChangePropertyRequest newProperties)
{
if (timelineName == null)
diff --git a/Timeline/Services/UserDeleteService.cs b/Timeline/Services/UserDeleteService.cs new file mode 100644 index 00000000..845de573 --- /dev/null +++ b/Timeline/Services/UserDeleteService.cs @@ -0,0 +1,69 @@ +using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.Logging;
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Threading.Tasks;
+using Timeline.Entities;
+using Timeline.Helpers;
+using Timeline.Models.Validation;
+using static Timeline.Resources.Services.UserService;
+
+namespace Timeline.Services
+{
+ public interface IUserDeleteService
+ {
+ /// <summary>
+ /// Delete a user of given username.
+ /// </summary>
+ /// <param name="username">Username of the user to delete. Can't be null.</param>
+ /// <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>
+ Task<bool> DeleteUser(string username);
+ }
+
+ public class UserDeleteService : IUserDeleteService
+ {
+ private readonly ILogger<UserDeleteService> _logger;
+
+ private readonly DatabaseContext _databaseContext;
+
+ private readonly ITimelineService _timelineService;
+
+ private readonly UsernameValidator _usernameValidator = new UsernameValidator();
+
+ public UserDeleteService(ILogger<UserDeleteService> logger, DatabaseContext databaseContext, ITimelineService timelineService)
+ {
+ _logger = logger;
+ _databaseContext = databaseContext;
+ _timelineService = timelineService;
+ }
+
+ public async Task<bool> DeleteUser(string username)
+ {
+ if (username == null)
+ throw new ArgumentNullException(nameof(username));
+
+ if (!_usernameValidator.Validate(username, out var message))
+ {
+ throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, ExceptionUsernameBadFormat, message), nameof(username));
+ }
+
+ var user = await _databaseContext.Users.Where(u => u.Username == username).SingleOrDefaultAsync();
+ if (user == null)
+ return false;
+
+ await _timelineService.DeleteAllPostsOfUser(user.Id);
+
+ _databaseContext.Users.Remove(user);
+
+ await _databaseContext.SaveChangesAsync();
+ _logger.LogInformation(Log.Format(LogDatabaseRemove, ("Id", user.Id), ("Username", user.Username)));
+
+ return true;
+ }
+
+ }
+}
diff --git a/Timeline/Services/UserService.cs b/Timeline/Services/UserService.cs index 4e56c86a..c186c170 100644 --- a/Timeline/Services/UserService.cs +++ b/Timeline/Services/UserService.cs @@ -127,22 +127,6 @@ namespace Timeline.Services Task<User> ModifyUser(string username, User? info);
/// <summary>
- /// Delete a user of given id.
- /// </summary>
- /// <param name="id">Id of the user to delete.</param>
- /// <returns>True if user is deleted, false if user not exist.</returns>
- Task<bool> DeleteUser(long id);
-
- /// <summary>
- /// Delete a user of given username.
- /// </summary>
- /// <param name="username">Username of the user to delete. Can't be null.</param>
- /// <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>
- Task<bool> DeleteUser(string username);
-
- /// <summary>
/// Try to change a user's password with old password.
/// </summary>
/// <param name="id">The id of user to change password of.</param>
@@ -428,34 +412,6 @@ namespace Timeline.Services return CreateUserFromEntity(entity);
}
- public async Task<bool> DeleteUser(long id)
- {
- var user = await _databaseContext.Users.Where(u => u.Id == id).SingleOrDefaultAsync();
- if (user == null)
- return false;
-
- _databaseContext.Users.Remove(user);
- await _databaseContext.SaveChangesAsync();
- _logger.LogInformation(Log.Format(LogDatabaseRemove, ("Id", id), ("Username", user.Username)));
- return true;
- }
-
- public async Task<bool> DeleteUser(string username)
- {
- if (username == null)
- throw new ArgumentNullException(nameof(username));
- CheckUsernameFormat(username, nameof(username));
-
- var user = await _databaseContext.Users.Where(u => u.Username == username).SingleOrDefaultAsync();
- if (user == null)
- return false;
-
- _databaseContext.Users.Remove(user);
- await _databaseContext.SaveChangesAsync();
- _logger.LogInformation(Log.Format(LogDatabaseRemove, ("Id", user.Id), ("Username", username)));
- return true;
- }
-
public async Task ChangePassword(long id, string oldPassword, string newPassword)
{
if (oldPassword == null)
diff --git a/Timeline/Startup.cs b/Timeline/Startup.cs index 84f0e8ba..7a813ac7 100644 --- a/Timeline/Startup.cs +++ b/Timeline/Startup.cs @@ -71,6 +71,7 @@ namespace Timeline services.AddTransient<IPasswordService, PasswordService>();
services.AddScoped<IUserService, UserService>();
+ services.AddScoped<IUserDeleteService, UserDeleteService>();
services.AddScoped<IUserTokenService, JwtUserTokenService>();
services.AddScoped<IUserTokenManager, UserTokenManager>();
|