Projekt

Obecné

Profil

Stáhnout (6.69 KB) Statistiky
| Větev: | Tag: | Revize:
1
using Core.Contexts;
2
using Core.Entities;
3
using Models.Enums;
4
using System;
5
using System.Collections.Generic;
6
using System.Linq;
7
using System.Text;
8
using System.Threading.Tasks;
9
using Serilog;
10
using BCrypt.Net;
11
using Models.Users;
12
using AutoMapper;
13
using Microsoft.EntityFrameworkCore;
14

    
15
namespace Core.Services
16
{
17
    public class UserServiceEF : IUserService
18
    {
19
        // DI
20

    
21
        private readonly DatabaseContext _databaseContext;
22
        private readonly ILogger _logger;
23
        private readonly IMapper _mapper;
24

    
25
        public UserServiceEF(DatabaseContext context, ILogger logger, IMapper mapper)
26
        {
27
            _databaseContext = context;
28
            _logger = logger;
29
            _mapper = mapper;
30
        }
31

    
32
        public User ChangePassword(User user, string newPassword)
33
        {
34
            if (newPassword == "")
35
            {
36
                throw new InvalidOperationException("Empty password.");
37
            }
38

    
39
            // Check if the user is tracked by EF
40
            if (!_databaseContext.Users.Local.Any(u => u.Id == user.Id))
41
            {
42
                _logger.Information($"User {user.Username} with Guid {user.Id} is untracked by EF and password change cannot be done.");
43
                throw new InvalidOperationException("User is untracked by EF.");
44
            }
45

    
46
            user.Password = BCrypt.Net.BCrypt.HashPassword(newPassword);
47
            _databaseContext.SaveChanges();
48
            return user;
49
        }
50

    
51
        public User? ChangePassword(Guid userId, string newPassword)
52
        {
53
            User? user = null;
54
            user = _databaseContext.Users.First(u => u.Id == userId);
55

    
56
            return ChangePassword(user, newPassword);
57
        }
58

    
59
        public User? CheckUsernamePassword(string username, string password)
60
        {
61
            try
62
            {
63
                // Throws exception if user does not exist
64
                User u = _databaseContext.Users.First(u => u.Username == username);
65
                if (!BCrypt.Net.BCrypt.Verify(password, u.Password))
66
                {
67
                    _logger.Information($"Password for user {username} doesn't match.");
68
                    return null;
69
                }
70
                return u;
71
            }
72
            catch (Exception)
73
            {
74
                _logger.Information($"No user with username {username} found.");
75
                return null;
76
            }
77
        }
78

    
79
        public User? CreateUser(string username, string name, string surname, string password, ERole role)
80
        {
81
            if (password == "")
82
            {
83
                return null;
84
            }
85

    
86
            // Check if username already used
87
            if (_databaseContext.Users.Any(u => u.Username == username))
88
            {
89
                _logger.Information($"Username {username} is already used. Cannot create new user");
90
                return null;
91
            }
92

    
93
            User user = new User()
94
            {
95
                Username = username,
96
                Name = name,
97
                Surname = surname,
98
                Password = BCrypt.Net.BCrypt.HashPassword(password),
99
                Role = role
100
            };
101
            _databaseContext.Users.Add(user);
102
            _databaseContext.SaveChanges();
103
            return user;
104
        }
105

    
106
        public User? GetUserByUsername(string username)
107
        {
108
            try
109
            {
110
                // Throws exception on no user found
111
                User user = _databaseContext.Users.First(u => u.Username == username);
112
                return user;
113
            }
114
            catch (InvalidOperationException)
115
            {
116
                _logger.Warning($"No user with the username {username} found.");
117
                return null;
118
            }
119
        }
120

    
121
        public User? GetUserById(Guid id)
122
        {
123
            try
124
            {
125
                // Throws exception on no user found
126
                User user = _databaseContext.Users.First(u => u.Id == id);
127
                return user;
128
            }
129
            catch (InvalidOperationException)
130
            {
131
                _logger.Warning($"No user with the GUID {id} found.");
132
                return null;
133
            }
134
        }
135

    
136
        public User UpdateUser(User user, string? username = null, string? name = null, string? surname = null, ERole? role = null)
137
        {
138
            // Check if the user is tracked by EF
139
            if (!_databaseContext.Users.Local.Any(u => u.Id == user.Id))
140
            {
141
                _logger.Information($"User {user.Username} with Guid {user.Id} is untracked by EF and update cannot be done.");
142
                throw new InvalidOperationException("User is untracked by EF.");
143
            }
144

    
145
            if (username is not null && username != "")
146
            {
147
                user.Username = username;
148
            }
149

    
150
            if (name is not null && name != "")
151
            {
152
                user.Name = name;
153
            }
154

    
155
            if (surname is not null && surname != "")
156
            {
157
                user.Surname = surname;
158
            }
159

    
160
            if (role is not null)
161
            {
162
                // We know it is not null
163
                user.Role = (ERole)role;
164
            }
165

    
166
            _databaseContext.SaveChanges();
167
            return user;
168
        }
169

    
170
        public User? UpdateUser(Guid userId, string? username = null, string? name = null, string? surname = null, ERole? role = null)
171
        {
172
            try
173
            {
174
                User user = _databaseContext.Users.First(u => u.Id == userId);
175
                return UpdateUser(user, username, name, surname, role);
176
            }
177
            catch (Exception ex)
178
            {
179
                return null;
180
            }
181
        }
182

    
183

    
184
        public UserList GetUsers()
185
        {
186
            var userList = new UserList();
187
            var users = _databaseContext.Users
188
                .OrderBy(u => u.Surname)
189
                .ToList();
190
            foreach (var user in users)
191
            {
192
                var userInfo = _mapper.Map<UserInfo>(user);
193
                userInfo.AssignedDocumentsCount = _databaseContext.Annotations
194
                    .Include(a => a.User)
195
                    .Where(a => !(a is FinalAnnotation))
196
                    .Where(a => a.User == user)
197
                    .Count();
198
                userList.Users.Add(userInfo);
199
            }
200

    
201
            return userList;
202
        }
203

    
204

    
205
        public void DeleteUser(Guid userId)
206
        {
207
            try
208
            {
209
                var user = _databaseContext.Users.Where(u => u.Id == userId).First();
210
                _databaseContext.Users.Remove(user);
211
                _databaseContext.SaveChanges();
212
            }
213
            catch (Exception)
214
            {
215
                throw new InvalidOperationException("User not found");
216
            }
217
        }
218
    }
219
}
220

    
(2-2/2)