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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
|
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.Helpers;
using Timeline.Models;
using Timeline.Models.Validation;
using Timeline.Services.Exceptions;
using static Timeline.Resources.Services.UserService;
namespace Timeline.Services
{
/// <summary>
/// Null means not change.
/// </summary>
public record ModifyUserParams
{
public string? Username { get; set; }
public string? Password { get; set; }
public string? Nickname { get; set; }
}
public interface IUserService
{
/// <summary>
/// Try to verify the given username and password.
/// </summary>
/// <param name="username">The username of the user to verify.</param>
/// <param name="password">The password of the user to verify.</param>
/// <returns>The user info and auth info.</returns>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="username"/> or <paramref name="password"/> is null.</exception>
/// <exception cref="ArgumentException">Thrown when <paramref name="username"/> is of bad format or <paramref name="password"/> is empty.</exception>
/// <exception cref="UserNotExistException">Thrown when the user with given username does not exist.</exception>
/// <exception cref="BadPasswordException">Thrown when password is wrong.</exception>
Task<User> VerifyCredential(string username, string password);
/// <summary>
/// Try to get a user by id.
/// </summary>
/// <param name="id">The id of the user.</param>
/// <returns>The user info.</returns>
/// <exception cref="UserNotExistException">Thrown when the user with given id does not exist.</exception>
Task<User> GetUser(long id);
/// <summary>
/// Get the user id of given username.
/// </summary>
/// <param name="username">Username of the user.</param>
/// <returns>The id of the user.</returns>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="username"/> is null.</exception>
/// <exception cref="ArgumentException">Thrown when <paramref name="username"/> is of bad format.</exception>
/// <exception cref="UserNotExistException">Thrown when the user with given username does not exist.</exception>
Task<long> GetUserIdByUsername(string username);
/// <summary>
/// List all users.
/// </summary>
/// <returns>The user info of users.</returns>
Task<List<User>> GetUsers();
/// <summary>
/// Create a user with given info.
/// </summary>
/// <param name="username">The username of new user.</param>
/// <param name="password">The password of new user.</param>
/// <returns>The the new user.</returns>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="username"/> or <paramref name="password"/> is null.</exception>
/// <exception cref="ArgumentException">Thrown when <paramref name="username"/> or <paramref name="password"/> is of bad format.</exception>
/// <exception cref="EntityAlreadyExistException">Thrown when a user with given username already exists.</exception>
Task<User> CreateUser(string username, string password);
/// <summary>
/// Modify a user.
/// </summary>
/// <param name="id">The id of the user.</param>
/// <param name="param">The new information.</param>
/// <returns>The new user info.</returns>
/// <exception cref="ArgumentException">Thrown when some fields in <paramref name="param"/> is bad.</exception>
/// <exception cref="UserNotExistException">Thrown when user with given id does not exist.</exception>
/// <remarks>
/// Version will increase if password is changed.
/// </remarks>
Task<User> ModifyUser(long id, ModifyUserParams? param);
/// <summary>
/// Try to change a user's password with old password.
/// </summary>
/// <param name="id">The id of user to change password of.</param>
/// <param name="oldPassword">Old password.</param>
/// <param name="newPassword">New password.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="oldPassword"/> or <paramref name="newPassword"/> is null.</exception>
/// <exception cref="ArgumentException">Thrown if <paramref name="oldPassword"/> or <paramref name="newPassword"/> is empty.</exception>
/// <exception cref="UserNotExistException">Thrown if the user with given username does not exist.</exception>
/// <exception cref="BadPasswordException">Thrown if the old password is wrong.</exception>
Task ChangePassword(long id, string oldPassword, string newPassword);
}
public class UserService : IUserService
{
private readonly ILogger<UserService> _logger;
private readonly IClock _clock;
private readonly DatabaseContext _databaseContext;
private readonly IPasswordService _passwordService;
private readonly IUserPermissionService _userPermissionService;
private readonly UsernameValidator _usernameValidator = new UsernameValidator();
private readonly NicknameValidator _nicknameValidator = new NicknameValidator();
public UserService(ILogger<UserService> logger, DatabaseContext databaseContext, IPasswordService passwordService, IClock clock, IUserPermissionService userPermissionService)
{
_logger = logger;
_clock = clock;
_databaseContext = databaseContext;
_passwordService = passwordService;
_userPermissionService = userPermissionService;
}
private void CheckUsernameFormat(string username, string? paramName)
{
if (!_usernameValidator.Validate(username, out var message))
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, ExceptionUsernameBadFormat, message), paramName);
}
}
private static void CheckPasswordFormat(string password, string? paramName)
{
if (password.Length == 0)
{
throw new ArgumentException(ExceptionPasswordEmpty, paramName);
}
}
private void CheckNicknameFormat(string nickname, string? paramName)
{
if (!_nicknameValidator.Validate(nickname, out var message))
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, ExceptionNicknameBadFormat, message), paramName);
}
}
private static void ThrowUsernameConflict()
{
throw new EntityAlreadyExistException(EntityNames.User, ExceptionUsernameConflict);
}
private async Task<User> CreateUserFromEntity(UserEntity entity)
{
var permission = await _userPermissionService.GetPermissionsOfUserAsync(entity.Id);
return new User
{
UniqueId = entity.UniqueId,
Username = entity.Username,
Administrator = permission.Contains(UserPermission.UserManagement),
Permissions = permission,
Nickname = string.IsNullOrEmpty(entity.Nickname) ? entity.Username : entity.Nickname,
Id = entity.Id,
Version = entity.Version,
CreateTime = entity.CreateTime,
UsernameChangeTime = entity.UsernameChangeTime,
LastModified = entity.LastModified
};
}
public async Task<User> VerifyCredential(string username, string password)
{
if (username == null)
throw new ArgumentNullException(nameof(username));
if (password == null)
throw new ArgumentNullException(nameof(password));
CheckUsernameFormat(username, nameof(username));
CheckPasswordFormat(password, nameof(password));
var entity = await _databaseContext.Users.Where(u => u.Username == username).SingleOrDefaultAsync();
if (entity == null)
throw new UserNotExistException(username);
if (!_passwordService.VerifyPassword(entity.Password, password))
throw new BadPasswordException(password);
return await CreateUserFromEntity(entity);
}
public async Task<User> GetUser(long id)
{
var user = await _databaseContext.Users.Where(u => u.Id == id).SingleOrDefaultAsync();
if (user == null)
throw new UserNotExistException(id);
return await CreateUserFromEntity(user);
}
public async Task<long> GetUserIdByUsername(string username)
{
if (username == null)
throw new ArgumentNullException(nameof(username));
CheckUsernameFormat(username, nameof(username));
var entity = await _databaseContext.Users.Where(user => user.Username == username).Select(u => new { u.Id }).SingleOrDefaultAsync();
if (entity == null)
throw new UserNotExistException(username);
return entity.Id;
}
public async Task<List<User>> GetUsers()
{
List<User> result = new();
foreach (var entity in await _databaseContext.Users.ToArrayAsync())
{
result.Add(await CreateUserFromEntity(entity));
}
return result;
}
public async Task<User> CreateUser(string username, string password)
{
if (username == null)
throw new ArgumentNullException(nameof(username));
if (password == null)
throw new ArgumentNullException(nameof(password));
CheckUsernameFormat(username, nameof(username));
CheckPasswordFormat(password, nameof(password));
var conflict = await _databaseContext.Users.AnyAsync(u => u.Username == username);
if (conflict)
ThrowUsernameConflict();
var newEntity = new UserEntity
{
Username = username,
Password = _passwordService.HashPassword(password),
Version = 1
};
_databaseContext.Users.Add(newEntity);
await _databaseContext.SaveChangesAsync();
_logger.LogInformation(Log.Format(LogDatabaseCreate, ("Id", newEntity.Id), ("Username", username)));
return await CreateUserFromEntity(newEntity);
}
public async Task<User> ModifyUser(long id, ModifyUserParams? param)
{
if (param != null)
{
if (param.Username != null)
CheckUsernameFormat(param.Username, nameof(param));
if (param.Password != null)
CheckPasswordFormat(param.Password, nameof(param));
if (param.Nickname != null)
CheckNicknameFormat(param.Nickname, nameof(param));
}
var entity = await _databaseContext.Users.Where(u => u.Id == id).SingleOrDefaultAsync();
if (entity == null)
throw new UserNotExistException(id);
if (param != null)
{
var now = _clock.GetCurrentTime();
bool updateLastModified = false;
var username = param.Username;
if (username != null && username != entity.Username)
{
var conflict = await _databaseContext.Users.AnyAsync(u => u.Username == username);
if (conflict)
ThrowUsernameConflict();
entity.Username = username;
entity.UsernameChangeTime = now;
updateLastModified = true;
}
var password = param.Password;
if (password != null)
{
entity.Password = _passwordService.HashPassword(password);
entity.Version += 1;
}
var nickname = param.Nickname;
if (nickname != null && nickname != entity.Nickname)
{
entity.Nickname = nickname;
updateLastModified = true;
}
if (updateLastModified)
{
entity.LastModified = now;
}
await _databaseContext.SaveChangesAsync();
_logger.LogInformation(LogDatabaseUpdate, ("Id", id));
}
return await CreateUserFromEntity(entity);
}
public async Task ChangePassword(long id, string oldPassword, string newPassword)
{
if (oldPassword == null)
throw new ArgumentNullException(nameof(oldPassword));
if (newPassword == null)
throw new ArgumentNullException(nameof(newPassword));
CheckPasswordFormat(oldPassword, nameof(oldPassword));
CheckPasswordFormat(newPassword, nameof(newPassword));
var entity = await _databaseContext.Users.Where(u => u.Id == id).SingleOrDefaultAsync();
if (entity == null)
throw new UserNotExistException(id);
if (!_passwordService.VerifyPassword(entity.Password, oldPassword))
throw new BadPasswordException(oldPassword);
entity.Password = _passwordService.HashPassword(newPassword);
entity.Version += 1;
await _databaseContext.SaveChangesAsync();
_logger.LogInformation(Log.Format(LogDatabaseUpdate, ("Id", id), ("Operation", "Change password")));
}
}
}
|