blob: c21042dfcd3261ca435cccf684f6182ca78ceaef (
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
|
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.Models.Validation;
using Timeline.Services.Timeline;
namespace Timeline.Services.User
{
public class UserDeleteService : IUserDeleteService
{
private readonly ILogger<UserDeleteService> _logger;
private readonly DatabaseContext _databaseContext;
private readonly ITimelinePostService _timelinePostService;
private readonly UsernameValidator _usernameValidator = new UsernameValidator();
public UserDeleteService(ILogger<UserDeleteService> logger, DatabaseContext databaseContext, ITimelinePostService timelinePostService)
{
_logger = logger;
_databaseContext = databaseContext;
_timelinePostService = timelinePostService;
}
public async Task DeleteUserAsync(string username)
{
if (username == null)
throw new ArgumentNullException(nameof(username));
if (!_usernameValidator.Validate(username, out var message))
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resource.ExceptionUsernameBadFormat, message), nameof(username));
}
var user = await _databaseContext.Users.Where(u => u.Username == username).SingleOrDefaultAsync();
if (user is null)
throw new EntityNotExistException(EntityTypes.User, new Dictionary<string, object>
{
["username"] = username
});
if (user.Id == 1)
throw new InvalidOperationOnRootUserException(Resource.ExceptionDeleteRootUser);
await _timelinePostService.DeleteAllPostsOfUserAsync(user.Id);
_databaseContext.Users.Remove(user);
await _databaseContext.SaveChangesAsync();
_logger.LogWarning(Resource.LogDeleteUser, user.Username, user.Id);
}
}
}
|