Projekt

Obecné

Profil

Stáhnout (6.67 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
        private readonly DatabaseContext _databaseContext;
20
        private readonly ILogger _logger;
21
        private readonly IMapper _mapper;
22

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

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

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

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

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

    
54
            return ChangePassword(user, newPassword);
55
        }
56

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

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

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

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

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

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

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

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

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

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

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

    
164
            _databaseContext.SaveChanges();
165
            return user;
166
        }
167

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

    
181

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

    
199
            return userList;
200
        }
201

    
202

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

    
(2-2/2)