blob: b630668257e7e3c530a03ea2d68a70322fefee12 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
|
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
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;
}
}
}
|