Projekt

Obecné

Profil

Stáhnout (6.69 KB) Statistiky
| Větev: | Tag: | Revize:
1 897851f8 Vojtěch Bartička
using Core.Contexts;
2
using Core.Entities;
3 cd91f841 Vojtěch Bartička
using Models.Enums;
4 897851f8 Vojtěch Bartička
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 a70f3c5f Vojtěch Bartička
using Models.Users;
12
using AutoMapper;
13 faa3619b Vojtěch Bartička
using Microsoft.EntityFrameworkCore;
14 897851f8 Vojtěch Bartička
15
namespace Core.Services
16
{
17
    public class UserServiceEF : IUserService
18
    {
19 a35cb648 Vojtěch Bartička
        // DI
20
21 897851f8 Vojtěch Bartička
        private readonly DatabaseContext _databaseContext;
22
        private readonly ILogger _logger;
23 a70f3c5f Vojtěch Bartička
        private readonly IMapper _mapper;
24 897851f8 Vojtěch Bartička
25 a70f3c5f Vojtěch Bartička
        public UserServiceEF(DatabaseContext context, ILogger logger, IMapper mapper)
26 897851f8 Vojtěch Bartička
        {
27
            _databaseContext = context;
28
            _logger = logger;
29 a70f3c5f Vojtěch Bartička
            _mapper = mapper;
30 897851f8 Vojtěch Bartička
        }
31
32
        public User ChangePassword(User user, string newPassword)
33
        {
34 4ebfa716 Vojtěch Bartička
            if (newPassword == "")
35
            {
36
                throw new InvalidOperationException("Empty password.");
37
            }
38
39 897851f8 Vojtěch Bartička
            // 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 a9acbe07 Vojtěch Bartička
        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 897851f8 Vojtěch Bartička
        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 c349bab3 Lukáš Vlček
                    _logger.Information($"Password for user {username} doesn't match.");
68 897851f8 Vojtěch Bartička
                    return null;
69
                }
70
                return u;
71
            }
72 fc0e5b36 Vojtěch Bartička
            catch (Exception)
73 897851f8 Vojtěch Bartička
            {
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 4ebfa716 Vojtěch Bartička
            if (password == "")
82
            {
83
                return null;
84
            }
85
86 897851f8 Vojtěch Bartička
            // 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 fc0e5b36 Vojtěch Bartička
            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 897851f8 Vojtěch Bartička
            _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 fc0e5b36 Vojtěch Bartička
            catch (InvalidOperationException)
115 897851f8 Vojtěch Bartička
            {
116
                _logger.Warning($"No user with the username {username} found.");
117
                return null;
118
            }
119
        }
120
121 c349bab3 Lukáš Vlček
        public User? GetUserById(Guid id)
122 897851f8 Vojtěch Bartička
        {
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 fc0e5b36 Vojtěch Bartička
            catch (InvalidOperationException)
130 897851f8 Vojtěch Bartička
            {
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 4ebfa716 Vojtěch Bartička
            if (username is not null && username != "")
146 897851f8 Vojtěch Bartička
            {
147
                user.Username = username;
148
            }
149
150 4ebfa716 Vojtěch Bartička
            if (name is not null && name != "")
151 897851f8 Vojtěch Bartička
            {
152
                user.Name = name;
153
            }
154
155 4ebfa716 Vojtěch Bartička
            if (surname is not null && surname != "")
156 897851f8 Vojtěch Bartička
            {
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 a70f3c5f Vojtěch Bartička
170 a9acbe07 Vojtěch Bartička
        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 faa3619b Vojtěch Bartička
        public UserList GetUsers()
185 a70f3c5f Vojtěch Bartička
        {
186 faa3619b Vojtěch Bartička
            var userList = new UserList();
187 b78ec116 Vojtěch Bartička
            var users = _databaseContext.Users
188
                .OrderBy(u => u.Surname)
189
                .ToList();
190 faa3619b Vojtěch Bartička
            foreach (var user in users)
191
            {
192
                var userInfo = _mapper.Map<UserInfo>(user);
193 8c9ce202 Vojtěch Bartička
                userInfo.AssignedDocumentsCount = _databaseContext.Annotations
194
                    .Include(a => a.User)
195
                    .Where(a => !(a is FinalAnnotation))
196
                    .Where(a => a.User == user)
197
                    .Count();
198 faa3619b Vojtěch Bartička
                userList.Users.Add(userInfo);
199
            }
200
201
            return userList;
202
        }
203
204 f37d2b59 Vojtěch Bartička
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 78122c3a Vojtěch Bartička
                _databaseContext.SaveChanges();
212 f37d2b59 Vojtěch Bartička
            }
213
            catch (Exception)
214
            {
215
                throw new InvalidOperationException("User not found");
216
            }
217
        }
218 897851f8 Vojtěch Bartička
    }
219
}