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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
|
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading.Tasks;
using Timeline.Entities;
using Timeline.Models;
using static Timeline.Entities.UserUtility;
namespace Timeline.Services
{
public class CreateTokenResult
{
public string Token { get; set; }
public UserInfo User { get; set; }
}
[Serializable]
public class UserNotExistException : Exception
{
public UserNotExistException(): base("The user does not exist.") { }
public UserNotExistException(string message) : base(message) { }
public UserNotExistException(string message, Exception inner) : base(message, inner) { }
protected UserNotExistException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context) : base(info, context) { }
}
[Serializable]
public class BadPasswordException : Exception
{
public BadPasswordException(): base("Password is wrong.") { }
public BadPasswordException(string message) : base(message) { }
public BadPasswordException(string message, Exception inner) : base(message, inner) { }
protected BadPasswordException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context) : base(info, context) { }
}
[Serializable]
public class BadTokenVersionException : Exception
{
public BadTokenVersionException(): base("Token version is expired.") { }
public BadTokenVersionException(string message) : base(message) { }
public BadTokenVersionException(string message, Exception inner) : base(message, inner) { }
protected BadTokenVersionException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context) : base(info, context) { }
}
public enum PutUserResult
{
/// <summary>
/// A new user is created.
/// </summary>
Created,
/// <summary>
/// A existing user is modified.
/// </summary>
Modified
}
public enum PatchUserResult
{
/// <summary>
/// Succeed to modify user.
/// </summary>
Success,
/// <summary>
/// A user of given username does not exist.
/// </summary>
NotExists
}
public enum DeleteUserResult
{
/// <summary>
/// A existing user is deleted.
/// </summary>
Deleted,
/// <summary>
/// A user of given username does not exist.
/// </summary>
NotExists
}
public enum ChangePasswordResult
{
/// <summary>
/// Success to change password.
/// </summary>
Success,
/// <summary>
/// The user does not exists.
/// </summary>
NotExists,
/// <summary>
/// Old password is wrong.
/// </summary>
BadOldPassword
}
public enum PutAvatarResult
{
/// <summary>
/// Success to upload avatar.
/// </summary>
Success,
/// <summary>
/// The user does not exists.
/// </summary>
UserNotExists
}
public interface IUserService
{
/// <summary>
/// Try to anthenticate with the given username and password.
/// If success, create a token and return the user info.
/// </summary>
/// <param name="username">The username of the user to anthenticate.</param>
/// <param name="password">The password of the user to anthenticate.</param>
/// <returns>An <see cref="CreateTokenResult"/> containing the created token and user info.</returns>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="username"/> or <paramref name="password"/> is null.</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<CreateTokenResult> CreateToken(string username, string password);
/// <summary>
/// Verify the given token.
/// If success, return the user info.
/// </summary>
/// <param name="token">The token to verify.</param>
/// <returns>The user info specified by the token.</returns>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="token"/> is null.</exception>
/// <exception cref="JwtTokenVerifyException">Thrown when the token is of bad format. Thrown by <see cref="JwtService.VerifyJwtToken(string)"/>.</exception>
/// <exception cref="UserNotExistException">Thrown when the user specified by the token does not exist. Usually it has been deleted after the token was issued.</exception>
/// <exception cref="BadTokenVersionException">Thrown when the version in the token is expired. User needs to recreate the token.</exception>
Task<UserInfo> VerifyToken(string token);
/// <summary>
/// Get the user info of given username.
/// </summary>
/// <param name="username">Username of the user.</param>
/// <returns>The info of the user. Null if the user of given username does not exists.</returns>
Task<UserInfo> GetUser(string username);
/// <summary>
/// List all users.
/// </summary>
/// <returns>The user info of users.</returns>
Task<UserInfo[]> ListUsers();
/// <summary>
/// Create or modify a user with given username.
/// Return <see cref="PutUserResult.Created"/> if a new user is created.
/// Return <see cref="PutUserResult.Modified"/> if a existing user is modified.
/// </summary>
/// <param name="username">Username of user.</param>
/// <param name="password">Password of user.</param>
/// <param name="roles">Array of roles of user.</param>
/// <returns>Return <see cref="PutUserResult.Created"/> if a new user is created.
/// Return <see cref="PutUserResult.Modified"/> if a existing user is modified.</returns>
Task<PutUserResult> PutUser(string username, string password, bool isAdmin);
/// <summary>
/// Partially modify a use of given username.
/// </summary>
/// <param name="username">Username of the user to modify.</param>
/// <param name="password">New password. If not modify, then null.</param>
/// <param name="roles">New roles. If not modify, then null.</param>
/// <returns>Return <see cref="PatchUserResult.Success"/> if modification succeeds.
/// Return <see cref="PatchUserResult.NotExists"/> if the user of given username doesn't exist.</returns>
Task<PatchUserResult> PatchUser(string username, string password, bool? isAdmin);
/// <summary>
/// Delete a user of given username.
/// Return <see cref="DeleteUserResult.Deleted"/> if the user is deleted.
/// Return <see cref="DeleteUserResult.NotExists"/> if the user of given username
/// does not exist.
/// </summary>
/// <param name="username">Username of thet user to delete.</param>
/// <returns><see cref="DeleteUserResult.Deleted"/> if the user is deleted.
/// <see cref="DeleteUserResult.NotExists"/> if the user doesn't exist.</returns>
Task<DeleteUserResult> DeleteUser(string username);
/// <summary>
/// Try to change a user's password with old password.
/// </summary>
/// <param name="username">The name of user to change password of.</param>
/// <param name="oldPassword">The user's old password.</param>
/// <param name="newPassword">The user's new password.</param>
/// <returns><see cref="ChangePasswordResult.Success"/> if success.
/// <see cref="ChangePasswordResult.NotExists"/> if user does not exist.
/// <see cref="ChangePasswordResult.BadOldPassword"/> if old password is wrong.</returns>
Task<ChangePasswordResult> ChangePassword(string username, string oldPassword, string newPassword);
/// <summary>
/// Get the true avatar url of a user.
/// </summary>
/// <param name="username">The name of user.</param>
/// <returns>The url if user exists. Null if user does not exist.</returns>
Task<string> GetAvatarUrl(string username);
/// <summary>
/// Put a avatar of a user.
/// </summary>
/// <param name="username">The name of user.</param>
/// <param name="data">The data of avatar image.</param>
/// <param name="mimeType">The mime type of the image.</param>
/// <returns>Return <see cref="PutAvatarResult.Success"/> if success.
/// Return <see cref="PutAvatarResult.UserNotExists"/> if user does not exist.</returns>
Task<PutAvatarResult> PutAvatar(string username, byte[] data, string mimeType);
}
internal class UserCache
{
public string Username { get; set; }
public bool IsAdmin { get; set; }
public long Version { get; set; }
public UserInfo ToUserInfo()
{
return new UserInfo(Username, IsAdmin);
}
}
public class UserService : IUserService
{
private readonly ILogger<UserService> _logger;
private readonly IMemoryCache _memoryCache;
private readonly DatabaseContext _databaseContext;
private readonly IJwtService _jwtService;
private readonly IPasswordService _passwordService;
private readonly IQCloudCosService _cosService;
public UserService(ILogger<UserService> logger, IMemoryCache memoryCache, DatabaseContext databaseContext, IJwtService jwtService, IPasswordService passwordService, IQCloudCosService cosService)
{
_logger = logger;
_memoryCache = memoryCache;
_databaseContext = databaseContext;
_jwtService = jwtService;
_passwordService = passwordService;
_cosService = cosService;
}
private string GenerateCacheKeyByUserId(long id) => $"user:{id}";
private void RemoveCache(long id)
{
_memoryCache.Remove(GenerateCacheKeyByUserId(id));
}
public async Task<CreateTokenResult> CreateToken(string username, string password)
{
if (username == null)
throw new ArgumentNullException(nameof(username));
if (password == null)
throw new ArgumentNullException(nameof(password));
// We need password info, so always check the database.
var user = await _databaseContext.Users.Where(u => u.Name == username).SingleOrDefaultAsync();
if (user == null)
{
var e = new UserNotExistException();
_logger.LogInformation(e, $"Create token failed. Reason: invalid username. Username = {username} Password = {password} .");
throw e;
}
if (!_passwordService.VerifyPassword(user.EncryptedPassword, password))
{
var e = new BadPasswordException();
_logger.LogInformation(e, $"Create token failed. Reason: invalid password. Username = {username} Password = {password} .");
throw e;
}
var token = _jwtService.GenerateJwtToken(new TokenInfo
{
Id = user.Id,
Version = user.Version
});
return new CreateTokenResult
{
Token = token,
User = CreateUserInfo(user)
};
}
public async Task<UserInfo> VerifyToken(string token)
{
TokenInfo tokenInfo;
try
{
tokenInfo = _jwtService.VerifyJwtToken(token);
}
catch (JwtTokenVerifyException e)
{
_logger.LogInformation(e, $"Verify token falied. Reason: invalid token. Token: {token} .");
throw e;
}
var id = tokenInfo.Id;
var key = GenerateCacheKeyByUserId(id);
if (!_memoryCache.TryGetValue<UserCache>(key, out var cache))
{
// no cache, check the database
var user = await _databaseContext.Users.Where(u => u.Id == id).SingleOrDefaultAsync();
if (user == null)
{
var e = new UserNotExistException();
_logger.LogInformation(e, $"Verify token falied. Reason: invalid id. Token: {token} Id: {id}.");
throw e;
}
// create cache
cache = CreateUserCache(user);
_memoryCache.CreateEntry(key).SetValue(cache);
}
if (tokenInfo.Version != cache.Version)
{
var e = new BadTokenVersionException();
_logger.LogInformation(e, $"Verify token falied. Reason: invalid version. Token: {token} Id: {id} Username: {cache.Username} Version: {tokenInfo.Version} Version in cache: {cache.Version}.");
throw e;
}
return cache.ToUserInfo();
}
public async Task<UserInfo> GetUser(string username)
{
return await _databaseContext.Users
.Where(user => user.Name == username)
.Select(user => CreateUserInfo(user))
.SingleOrDefaultAsync();
}
public async Task<UserInfo[]> ListUsers()
{
return await _databaseContext.Users
.Select(user => CreateUserInfo(user))
.ToArrayAsync();
}
public async Task<PutUserResult> PutUser(string username, string password, bool isAdmin)
{
var user = await _databaseContext.Users.Where(u => u.Name == username).SingleOrDefaultAsync();
if (user == null)
{
await _databaseContext.AddAsync(new User
{
Name = username,
EncryptedPassword = _passwordService.HashPassword(password),
RoleString = IsAdminToRoleString(isAdmin),
Version = 0
});
await _databaseContext.SaveChangesAsync();
return PutUserResult.Created;
}
user.EncryptedPassword = _passwordService.HashPassword(password);
user.RoleString = IsAdminToRoleString(isAdmin);
user.Version += 1;
await _databaseContext.SaveChangesAsync();
//clear cache
RemoveCache(user.Id);
return PutUserResult.Modified;
}
public async Task<PatchUserResult> PatchUser(string username, string password, bool? isAdmin)
{
var user = await _databaseContext.Users.Where(u => u.Name == username).SingleOrDefaultAsync();
if (user == null)
return PatchUserResult.NotExists;
bool modified = false;
if (password != null)
{
modified = true;
user.EncryptedPassword = _passwordService.HashPassword(password);
}
if (isAdmin != null)
{
modified = true;
user.RoleString = IsAdminToRoleString(isAdmin.Value);
}
if (modified)
{
await _databaseContext.SaveChangesAsync();
//clear cache
RemoveCache(user.Id);
}
return PatchUserResult.Success;
}
public async Task<DeleteUserResult> DeleteUser(string username)
{
var user = await _databaseContext.Users.Where(u => u.Name == username).SingleOrDefaultAsync();
if (user == null)
{
return DeleteUserResult.NotExists;
}
_databaseContext.Users.Remove(user);
await _databaseContext.SaveChangesAsync();
//clear cache
RemoveCache(user.Id);
return DeleteUserResult.Deleted;
}
public async Task<ChangePasswordResult> ChangePassword(string username, string oldPassword, string newPassword)
{
var user = await _databaseContext.Users.Where(u => u.Name == username).SingleOrDefaultAsync();
if (user == null)
return ChangePasswordResult.NotExists;
var verifyResult = _passwordService.VerifyPassword(user.EncryptedPassword, oldPassword);
if (!verifyResult)
return ChangePasswordResult.BadOldPassword;
user.EncryptedPassword = _passwordService.HashPassword(newPassword);
await _databaseContext.SaveChangesAsync();
//clear cache
RemoveCache(user.Id);
return ChangePasswordResult.Success;
}
public async Task<string> GetAvatarUrl(string username)
{
if (username == null)
throw new ArgumentNullException(nameof(username));
if ((await GetUser(username)) == null)
return null;
var exists = await _cosService.IsObjectExists("avatar", username);
if (exists)
return _cosService.GenerateObjectGetUrl("avatar", username);
else
return _cosService.GenerateObjectGetUrl("avatar", "__default");
}
public async Task<PutAvatarResult> PutAvatar(string username, byte[] data, string mimeType)
{
if (username == null)
throw new ArgumentNullException(nameof(username));
if (data == null)
throw new ArgumentNullException(nameof(data));
if (mimeType == null)
throw new ArgumentNullException(nameof(mimeType));
if ((await GetUser(username)) == null)
return PutAvatarResult.UserNotExists;
await _cosService.PutObject("avatar", username, data, mimeType);
return PutAvatarResult.Success;
}
}
}
|