aboutsummaryrefslogtreecommitdiff
path: root/BackEnd/Timeline/Services/User/UserDeleteService.cs
blob: e0391841245bf56b44c8e1eb4a92b5a06a440981 (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
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
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<bool> 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 == null)
                return false;

            if (user.Id == 1)
                throw new InvalidOperationOnRootUserException(Resource.ExceptionDeleteRootUser);

            await _timelinePostService.DeleteAllPostsOfUser(user.Id);

            _databaseContext.Users.Remove(user);

            await _databaseContext.SaveChangesAsync();
            _logger.LogWarning(Resource.LogDeleteUser, user.Username, user.Id);

            return true;
        }

    }
}