diff options
37 files changed, 901 insertions, 310 deletions
diff --git a/Timeline.Tests/Controllers/UserControllerTest.cs b/Timeline.Tests/Controllers/UserControllerTest.cs index 471ed851..781ec111 100644 --- a/Timeline.Tests/Controllers/UserControllerTest.cs +++ b/Timeline.Tests/Controllers/UserControllerTest.cs @@ -90,23 +90,6 @@ namespace Timeline.Tests.Controllers }
[Fact]
- public async Task Put_BadUsername()
- {
- const string username = "aaa";
- const string password = "ppp";
- const bool administrator = true;
- _mockUserService.Setup(s => s.PutUser(username, password, administrator)).ThrowsAsync(new UsernameBadFormatException());
- var action = await _controller.Put(new UserPutRequest
- {
- Password = password,
- Administrator = administrator
- }, username);
- action.Result.Should().BeAssignableTo<BadRequestObjectResult>()
- .Which.Value.Should().BeAssignableTo<CommonResponse>()
- .Which.Code.Should().Be(Put.BadUsername);
- }
-
- [Fact]
public async Task Patch_Success()
{
const string username = "aaa";
diff --git a/Timeline.Tests/DatabaseTest.cs b/Timeline.Tests/DatabaseTest.cs index f75ab71b..c45c0f66 100644 --- a/Timeline.Tests/DatabaseTest.cs +++ b/Timeline.Tests/DatabaseTest.cs @@ -32,21 +32,5 @@ namespace Timeline.Tests _context.SaveChanges();
_context.UserAvatars.Count().Should().Be(1);
}
-
- [Fact]
- public void DeleteUserShouldAlsoDeleteDetail()
- {
- var user = _context.Users.First();
- _context.UserDetails.Add(new UserDetailEntity
- {
- UserId = user.Id
- });
- _context.SaveChanges();
- _context.UserDetails.Count().Should().Be(1);
-
- _context.Users.Remove(user);
- _context.SaveChanges();
- _context.UserDetails.Count().Should().Be(0);
- }
}
}
diff --git a/Timeline.Tests/IntegratedTests/AuthorizationUnitTest.cs b/Timeline.Tests/IntegratedTests/AuthorizationTest.cs index 588e4349..a31d98f5 100644 --- a/Timeline.Tests/IntegratedTests/AuthorizationUnitTest.cs +++ b/Timeline.Tests/IntegratedTests/AuthorizationTest.cs @@ -9,12 +9,12 @@ using Xunit; namespace Timeline.Tests.IntegratedTests
{
- public class AuthorizationUnitTest : IClassFixture<WebApplicationFactory<Startup>>, IDisposable
+ public class AuthorizationTest : IClassFixture<WebApplicationFactory<Startup>>, IDisposable
{
private readonly TestApplication _testApp;
private readonly WebApplicationFactory<Startup> _factory;
- public AuthorizationUnitTest(WebApplicationFactory<Startup> factory)
+ public AuthorizationTest(WebApplicationFactory<Startup> factory)
{
_testApp = new TestApplication(factory);
_factory = _testApp.Factory;
diff --git a/Timeline.Tests/IntegratedTests/TokenUnitTest.cs b/Timeline.Tests/IntegratedTests/TokenTest.cs index d30b9311..e9b6e1e9 100644 --- a/Timeline.Tests/IntegratedTests/TokenUnitTest.cs +++ b/Timeline.Tests/IntegratedTests/TokenTest.cs @@ -15,7 +15,7 @@ using static Timeline.ErrorCodes.Http.Token; namespace Timeline.Tests.IntegratedTests
{
- public class TokenUnitTest : IClassFixture<WebApplicationFactory<Startup>>, IDisposable
+ public class TokenTest : IClassFixture<WebApplicationFactory<Startup>>, IDisposable
{
private const string CreateTokenUrl = "token/create";
private const string VerifyTokenUrl = "token/verify";
@@ -23,7 +23,7 @@ namespace Timeline.Tests.IntegratedTests private readonly TestApplication _testApp;
private readonly WebApplicationFactory<Startup> _factory;
- public TokenUnitTest(WebApplicationFactory<Startup> factory)
+ public TokenTest(WebApplicationFactory<Startup> factory)
{
_testApp = new TestApplication(factory);
_factory = _testApp.Factory;
diff --git a/Timeline.Tests/IntegratedTests/UserUnitTest.cs b/Timeline.Tests/IntegratedTests/UserTest.cs index b00648de..ec70b7e8 100644 --- a/Timeline.Tests/IntegratedTests/UserUnitTest.cs +++ b/Timeline.Tests/IntegratedTests/UserTest.cs @@ -14,12 +14,12 @@ using static Timeline.ErrorCodes.Http.User; namespace Timeline.Tests.IntegratedTests
{
- public class UserUnitTest : IClassFixture<WebApplicationFactory<Startup>>, IDisposable
+ public class UserTest : IClassFixture<WebApplicationFactory<Startup>>, IDisposable
{
private readonly TestApplication _testApp;
private readonly WebApplicationFactory<Startup> _factory;
- public UserUnitTest(WebApplicationFactory<Startup> factory)
+ public UserTest(WebApplicationFactory<Startup> factory)
{
_testApp = new TestApplication(factory);
_factory = _testApp.Factory;
@@ -31,7 +31,7 @@ namespace Timeline.Tests.IntegratedTests }
[Fact]
- public async Task Get_Users_List()
+ public async Task Get_List_Success()
{
using var client = await _factory.CreateClientAsAdmin();
var res = await client.GetAsync("users");
@@ -41,7 +41,7 @@ namespace Timeline.Tests.IntegratedTests }
[Fact]
- public async Task Get_Users_User()
+ public async Task Get_Single_Success()
{
using var client = await _factory.CreateClientAsAdmin();
var res = await client.GetAsync("users/" + MockUser.User.Username);
@@ -51,6 +51,14 @@ namespace Timeline.Tests.IntegratedTests }
[Fact]
+ public async Task Get_InvalidModel()
+ {
+ using var client = await _factory.CreateClientAsAdmin();
+ var res = await client.GetAsync("users/aaa!a");
+ res.Should().BeInvalidModel();
+ }
+
+ [Fact]
public async Task Get_Users_404()
{
using var client = await _factory.CreateClientAsAdmin();
@@ -62,35 +70,21 @@ namespace Timeline.Tests.IntegratedTests public static IEnumerable<object[]> Put_InvalidModel_Data()
{
- yield return new object[] { null, false };
- yield return new object[] { "p", null };
+ yield return new object[] { "aaa", null, false };
+ yield return new object[] { "aaa", "p", null };
+ yield return new object[] { "aa!a", "p", false };
}
[Theory]
[MemberData(nameof(Put_InvalidModel_Data))]
- public async Task Put_InvalidModel(string password, bool? administrator)
+ public async Task Put_InvalidModel(string username, string password, bool? administrator)
{
using var client = await _factory.CreateClientAsAdmin();
- const string url = "users/aaaaaaaa";
- (await client.PutAsJsonAsync(url,
+ (await client.PutAsJsonAsync("users/" + username,
new UserPutRequest { Password = password, Administrator = administrator }))
.Should().BeInvalidModel();
}
- [Fact]
- public async Task Put_BadUsername()
- {
- using var client = await _factory.CreateClientAsAdmin();
- var res = await client.PutAsJsonAsync("users/dsf fddf", new UserPutRequest
- {
- Password = "???",
- Administrator = false
- });
- res.Should().HaveStatusCode(400)
- .And.Should().HaveCommonBody()
- .Which.Code.Should().Be(Put.BadUsername);
- }
-
private async Task CheckAdministrator(HttpClient client, string username, bool administrator)
{
var res = await client.GetAsync("users/" + username);
@@ -139,6 +133,14 @@ namespace Timeline.Tests.IntegratedTests }
[Fact]
+ public async Task Patch_InvalidModel()
+ {
+ using var client = await _factory.CreateClientAsAdmin();
+ var res = await client.PatchAsJsonAsync("users/aaa!a", new UserPatchRequest { });
+ res.Should().BeInvalidModel();
+ }
+
+ [Fact]
public async Task Patch_Success()
{
using var client = await _factory.CreateClientAsAdmin();
@@ -151,6 +153,15 @@ namespace Timeline.Tests.IntegratedTests }
[Fact]
+ public async Task Delete_InvalidModel()
+ {
+ using var client = await _factory.CreateClientAsAdmin();
+ var url = "users/aaa!a";
+ var res = await client.DeleteAsync(url);
+ res.Should().BeInvalidModel();
+ }
+
+ [Fact]
public async Task Delete_Deleted()
{
using var client = await _factory.CreateClientAsAdmin();
@@ -176,7 +187,8 @@ namespace Timeline.Tests.IntegratedTests {
yield return new[] { null, "uuu" };
yield return new[] { "uuu", null };
- yield return new[] { "uuu", "???" };
+ yield return new[] { "a!a", "uuu" };
+ yield return new[] { "uuu", "a!a" };
}
[Theory]
@@ -258,7 +270,8 @@ namespace Timeline.Tests.IntegratedTests var res = await client.PostAsJsonAsync(changePasswordUrl,
new ChangePasswordRequest { OldPassword = MockUser.User.Password, NewPassword = newPassword });
res.Should().HaveStatusCode(200);
- await client.CreateUserTokenAsync(MockUser.User.Username, newPassword);
+ await _factory.CreateDefaultClient() // don't use client above, because it sets authorization header
+ .CreateUserTokenAsync(MockUser.User.Username, newPassword);
}
}
}
diff --git a/Timeline.Tests/Mock/Data/TestUsers.cs b/Timeline.Tests/Mock/Data/TestUsers.cs index bc2df469..6b0a9997 100644 --- a/Timeline.Tests/Mock/Data/TestUsers.cs +++ b/Timeline.Tests/Mock/Data/TestUsers.cs @@ -35,7 +35,7 @@ namespace Timeline.Tests.Mock.Data {
Name = user.Username,
EncryptedPassword = passwordService.HashPassword(user.Password),
- RoleString = UserUtility.IsAdminToRoleString(user.Administrator),
+ RoleString = UserRoleConvert.ToString(user.Administrator),
Avatar = UserAvatar.Create(DateTime.Now)
};
}
diff --git a/Timeline/Authenticate/PrincipalExtensions.cs b/Timeline/Authenticate/PrincipalExtensions.cs deleted file mode 100644 index fa39ea89..00000000 --- a/Timeline/Authenticate/PrincipalExtensions.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System.Security.Principal;
-using Timeline.Entities;
-
-namespace Timeline.Authenticate
-{
- public static class PrincipalExtensions
- {
- public static bool IsAdmin(this IPrincipal principal)
- {
- return principal.IsInRole(UserRoles.Admin);
- }
- }
-}
diff --git a/Timeline/Authenticate/Attribute.cs b/Timeline/Authentication/Attribute.cs index 239a2a1c..370b37e1 100644 --- a/Timeline/Authenticate/Attribute.cs +++ b/Timeline/Authentication/Attribute.cs @@ -1,7 +1,7 @@ using Microsoft.AspNetCore.Authorization;
using Timeline.Entities;
-namespace Timeline.Authenticate
+namespace Timeline.Authentication
{
public class AdminAuthorizeAttribute : AuthorizeAttribute
{
diff --git a/Timeline/Authenticate/AuthHandler.cs b/Timeline/Authentication/AuthHandler.cs index f9409c1a..47ed1d71 100644 --- a/Timeline/Authenticate/AuthHandler.cs +++ b/Timeline/Authentication/AuthHandler.cs @@ -10,7 +10,7 @@ using System.Threading.Tasks; using Timeline.Models;
using Timeline.Services;
-namespace Timeline.Authenticate
+namespace Timeline.Authentication
{
static class AuthConstants
{
@@ -18,7 +18,7 @@ namespace Timeline.Authenticate public const string DisplayName = "My Jwt Auth Scheme";
}
- class AuthOptions : AuthenticationSchemeOptions
+ public class AuthOptions : AuthenticationSchemeOptions
{
/// <summary>
/// The query param key to search for token. If null then query params are not searched for token. Default to <c>"token"</c>.
@@ -26,7 +26,7 @@ namespace Timeline.Authenticate public string TokenQueryParamKey { get; set; } = "token";
}
- class AuthHandler : AuthenticationHandler<AuthOptions>
+ public class AuthHandler : AuthenticationHandler<AuthOptions>
{
private readonly ILogger<AuthHandler> _logger;
private readonly IUserService _userService;
@@ -39,14 +39,14 @@ namespace Timeline.Authenticate }
// return null if no token is found
- private string ExtractToken()
+ private string? ExtractToken()
{
// check the authorization header
string header = Request.Headers[HeaderNames.Authorization];
- if (!string.IsNullOrEmpty(header) && header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
+ if (!string.IsNullOrEmpty(header) && header.StartsWith("Bearer ", StringComparison.InvariantCultureIgnoreCase))
{
var token = header.Substring("Bearer ".Length).Trim();
- _logger.LogInformation("Token is found in authorization header. Token is {} .", token);
+ _logger.LogInformation(Resources.Authentication.AuthHandler.LogTokenFoundInHeader, token);
return token;
}
@@ -57,7 +57,7 @@ namespace Timeline.Authenticate string token = Request.Query[paramQueryKey];
if (!string.IsNullOrEmpty(token))
{
- _logger.LogInformation("Token is found in query param with key \"{}\". Token is {} .", paramQueryKey, token);
+ _logger.LogInformation(Resources.Authentication.AuthHandler.LogTokenFoundInQuery, paramQueryKey, token);
return token;
}
}
@@ -71,7 +71,7 @@ namespace Timeline.Authenticate var token = ExtractToken();
if (string.IsNullOrEmpty(token))
{
- _logger.LogInformation("No jwt token is found.");
+ _logger.LogInformation(Resources.Authentication.AuthHandler.LogTokenNotFound);
return AuthenticateResult.NoResult();
}
@@ -81,20 +81,16 @@ namespace Timeline.Authenticate var identity = new ClaimsIdentity(AuthConstants.Scheme);
identity.AddClaim(new Claim(identity.NameClaimType, userInfo.Username, ClaimValueTypes.String));
- identity.AddClaims(UserUtility.IsAdminToRoleArray(userInfo.Administrator).Select(role => new Claim(identity.RoleClaimType, role, ClaimValueTypes.String)));
+ identity.AddClaims(UserRoleConvert.ToArray(userInfo.Administrator).Select(role => new Claim(identity.RoleClaimType, role, ClaimValueTypes.String)));
var principal = new ClaimsPrincipal();
principal.AddIdentity(identity);
return AuthenticateResult.Success(new AuthenticationTicket(principal, AuthConstants.Scheme));
}
- catch (ArgumentException)
+ catch (Exception e) when (e! is ArgumentException)
{
- throw; // this exception usually means server error.
- }
- catch (Exception e)
- {
- _logger.LogInformation(e, "A jwt token validation failed.");
+ _logger.LogInformation(e, Resources.Authentication.AuthHandler.LogTokenValidationFail);
return AuthenticateResult.Fail(e);
}
}
diff --git a/Timeline/Authentication/PrincipalExtensions.cs b/Timeline/Authentication/PrincipalExtensions.cs new file mode 100644 index 00000000..8d77ab62 --- /dev/null +++ b/Timeline/Authentication/PrincipalExtensions.cs @@ -0,0 +1,13 @@ +using System.Security.Principal;
+using Timeline.Entities;
+
+namespace Timeline.Authentication
+{
+ internal static class PrincipalExtensions
+ {
+ internal static bool IsAdministrator(this IPrincipal principal)
+ {
+ return principal.IsInRole(UserRoles.Admin);
+ }
+ }
+}
diff --git a/Timeline/Configs/DatabaseConfig.cs b/Timeline/Configs/DatabaseConfig.cs index e24ecdfb..c9309b08 100644 --- a/Timeline/Configs/DatabaseConfig.cs +++ b/Timeline/Configs/DatabaseConfig.cs @@ -2,6 +2,6 @@ namespace Timeline.Configs {
public class DatabaseConfig
{
- public string ConnectionString { get; set; }
+ public string ConnectionString { get; set; } = default!;
}
}
diff --git a/Timeline/Configs/JwtConfig.cs b/Timeline/Configs/JwtConfig.cs index 8c61d7bc..8a17825e 100644 --- a/Timeline/Configs/JwtConfig.cs +++ b/Timeline/Configs/JwtConfig.cs @@ -2,9 +2,9 @@ namespace Timeline.Configs {
public class JwtConfig
{
- public string Issuer { get; set; }
- public string Audience { get; set; }
- public string SigningKey { get; set; }
+ public string Issuer { get; set; } = default!;
+ public string Audience { get; set; } = default!;
+ public string SigningKey { get; set; } = default!;
/// <summary>
/// Set the default value of expire offset of jwt token.
diff --git a/Timeline/Controllers/Testing/TestingAuthController.cs b/Timeline/Controllers/Testing/TestingAuthController.cs index 488a3cff..67b5b2ef 100644 --- a/Timeline/Controllers/Testing/TestingAuthController.cs +++ b/Timeline/Controllers/Testing/TestingAuthController.cs @@ -1,6 +1,6 @@ using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
-using Timeline.Authenticate;
+using Timeline.Authentication;
namespace Timeline.Controllers.Testing
{
diff --git a/Timeline/Controllers/UserAvatarController.cs b/Timeline/Controllers/UserAvatarController.cs index e77076ca..5cba1d93 100644 --- a/Timeline/Controllers/UserAvatarController.cs +++ b/Timeline/Controllers/UserAvatarController.cs @@ -6,7 +6,7 @@ using Microsoft.Net.Http.Headers; using System;
using System.Linq;
using System.Threading.Tasks;
-using Timeline.Authenticate;
+using Timeline.Authentication;
using Timeline.Filters;
using Timeline.Models.Http;
using Timeline.Services;
@@ -106,7 +106,7 @@ namespace Timeline.Controllers return BadRequest(new CommonResponse(ErrorCodes.Put_Content_TooBig,
"Content can't be bigger than 10MB."));
- if (!User.IsAdmin() && User.Identity.Name != username)
+ if (!User.IsAdministrator() && User.Identity.Name != username)
{
_logger.LogInformation($"Attempt to put a avatar of other user as a non-admin failed. Operator Username: {User.Identity.Name} ; Username To Put Avatar: {username} .");
return StatusCode(StatusCodes.Status403Forbidden,
@@ -152,7 +152,7 @@ namespace Timeline.Controllers [Authorize]
public async Task<IActionResult> Delete([FromRoute] string username)
{
- if (!User.IsAdmin() && User.Identity.Name != username)
+ if (!User.IsAdministrator() && User.Identity.Name != username)
{
_logger.LogInformation($"Attempt to delete a avatar of other user as a non-admin failed. Operator Username: {User.Identity.Name} ; Username To Put Avatar: {username} .");
return StatusCode(StatusCodes.Status403Forbidden,
diff --git a/Timeline/Controllers/UserController.cs b/Timeline/Controllers/UserController.cs index b8d1d659..1771dc85 100644 --- a/Timeline/Controllers/UserController.cs +++ b/Timeline/Controllers/UserController.cs @@ -3,10 +3,11 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
-using Timeline.Authenticate;
+using Timeline.Authentication;
using Timeline.Helpers;
using Timeline.Models;
using Timeline.Models.Http;
+using Timeline.Models.Validation;
using Timeline.Services;
using static Timeline.Resources.Controllers.UserController;
@@ -23,11 +24,6 @@ namespace Timeline public const int NotExist = 10020101; // dd = 01
}
- public static class Put // cc = 02
- {
- public const int BadUsername = 10020201; // dd = 01
- }
-
public static class Patch // cc = 03
{
public const int NotExist = 10020301; // dd = 01
@@ -78,7 +74,7 @@ namespace Timeline.Controllers }
[HttpGet("users/{username}"), AdminAuthorize]
- public async Task<ActionResult<UserInfo>> Get([FromRoute] string username)
+ public async Task<ActionResult<UserInfo>> Get([FromRoute][Username] string username)
{
var user = await _userService.GetUser(username);
if (user == null)
@@ -90,32 +86,24 @@ namespace Timeline.Controllers }
[HttpPut("users/{username}"), AdminAuthorize]
- public async Task<ActionResult<CommonPutResponse>> Put([FromBody] UserPutRequest request, [FromRoute] string username)
+ public async Task<ActionResult<CommonPutResponse>> Put([FromBody] UserPutRequest request, [FromRoute][Username] string username)
{
- try
- {
- var result = await _userService.PutUser(username, request.Password, request.Administrator!.Value);
- switch (result)
- {
- case PutResult.Create:
- _logger.LogInformation(Log.Format(LogPutCreate, ("Username", username)));
- return CreatedAtAction("Get", new { username }, CommonPutResponse.Create(_localizerFactory));
- case PutResult.Modify:
- _logger.LogInformation(Log.Format(LogPutModify, ("Username", username)));
- return Ok(CommonPutResponse.Modify(_localizerFactory));
- default:
- throw new InvalidBranchException();
- }
- }
- catch (UsernameBadFormatException e)
+ var result = await _userService.PutUser(username, request.Password, request.Administrator!.Value);
+ switch (result)
{
- _logger.LogInformation(e, Log.Format(LogPutBadUsername, ("Username", username)));
- return BadRequest(new CommonResponse(ErrorCodes.Http.User.Put.BadUsername, _localizer["ErrorPutBadUsername"]));
+ case PutResult.Create:
+ _logger.LogInformation(Log.Format(LogPutCreate, ("Username", username)));
+ return CreatedAtAction("Get", new { username }, CommonPutResponse.Create(_localizerFactory));
+ case PutResult.Modify:
+ _logger.LogInformation(Log.Format(LogPutModify, ("Username", username)));
+ return Ok(CommonPutResponse.Modify(_localizerFactory));
+ default:
+ throw new InvalidBranchException();
}
}
[HttpPatch("users/{username}"), AdminAuthorize]
- public async Task<ActionResult> Patch([FromBody] UserPatchRequest request, [FromRoute] string username)
+ public async Task<ActionResult> Patch([FromBody] UserPatchRequest request, [FromRoute][Username] string username)
{
try
{
@@ -130,7 +118,7 @@ namespace Timeline.Controllers }
[HttpDelete("users/{username}"), AdminAuthorize]
- public async Task<ActionResult<CommonDeleteResponse>> Delete([FromRoute] string username)
+ public async Task<ActionResult<CommonDeleteResponse>> Delete([FromRoute][Username] string username)
{
try
{
diff --git a/Timeline/Entities/DatabaseContext.cs b/Timeline/Entities/DatabaseContext.cs index 550db216..e1b98e7d 100644 --- a/Timeline/Entities/DatabaseContext.cs +++ b/Timeline/Entities/DatabaseContext.cs @@ -1,38 +1,7 @@ using Microsoft.EntityFrameworkCore;
-using System.ComponentModel.DataAnnotations;
-using System.ComponentModel.DataAnnotations.Schema;
namespace Timeline.Entities
{
- public static class UserRoles
- {
- public const string Admin = "admin";
- public const string User = "user";
- }
-
- [Table("users")]
- public class User
- {
- [Column("id"), Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
- public long Id { get; set; }
-
- [Column("name"), MaxLength(26), Required]
- public string Name { get; set; } = default!;
-
- [Column("password"), Required]
- public string EncryptedPassword { get; set; } = default!;
-
- [Column("roles"), Required]
- public string RoleString { get; set; } = default!;
-
- [Column("version"), Required]
- public long Version { get; set; }
-
- public UserAvatar? Avatar { get; set; }
-
- public UserDetailEntity? Detail { get; set; }
- }
-
public class DatabaseContext : DbContext
{
public DatabaseContext(DbContextOptions<DatabaseContext> options)
@@ -41,14 +10,14 @@ namespace Timeline.Entities }
+ [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1062:Validate arguments of public methods")]
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().Property(e => e.Version).HasDefaultValue(0);
modelBuilder.Entity<User>().HasIndex(e => e.Name).IsUnique();
}
- public DbSet<User> Users { get; set; }
- public DbSet<UserAvatar> UserAvatars { get; set; }
- public DbSet<UserDetailEntity> UserDetails { get; set; }
+ public DbSet<User> Users { get; set; } = default!;
+ public DbSet<UserAvatar> UserAvatars { get; set; } = default!;
}
}
diff --git a/Timeline/Entities/User.cs b/Timeline/Entities/User.cs new file mode 100644 index 00000000..6e8e4967 --- /dev/null +++ b/Timeline/Entities/User.cs @@ -0,0 +1,32 @@ +using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
+
+namespace Timeline.Entities
+{
+ public static class UserRoles
+ {
+ public const string Admin = "admin";
+ public const string User = "user";
+ }
+
+ [Table("users")]
+ public class User
+ {
+ [Column("id"), Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
+ public long Id { get; set; }
+
+ [Column("name"), MaxLength(26), Required]
+ public string Name { get; set; } = default!;
+
+ [Column("password"), Required]
+ public string EncryptedPassword { get; set; } = default!;
+
+ [Column("roles"), Required]
+ public string RoleString { get; set; } = default!;
+
+ [Column("version"), Required]
+ public long Version { get; set; }
+
+ public UserAvatar? Avatar { get; set; }
+ }
+}
diff --git a/Timeline/Entities/UserDetail.cs b/Timeline/Entities/UserDetail.cs deleted file mode 100644 index e02d15c4..00000000 --- a/Timeline/Entities/UserDetail.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System.ComponentModel.DataAnnotations;
-using System.ComponentModel.DataAnnotations.Schema;
-
-namespace Timeline.Entities
-{
- [Table("user_details")]
- public class UserDetailEntity
- {
- [Column("id"), Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
- public long Id { get; set; }
-
- [Column("nickname"), MaxLength(15)]
- public string? Nickname { get; set; }
-
- [Column("qq"), MaxLength(15)]
- public string? QQ { get; set; }
-
- [Column("email"), MaxLength(50)]
- public string? Email { get; set; }
-
- [Column("phone_number"), MaxLength(15)]
- public string? PhoneNumber { get; set; }
-
- [Column("description")]
- public string? Description { get; set; }
-
- public long UserId { get; set; }
- }
-}
diff --git a/Timeline/GlobalSuppressions.cs b/Timeline/GlobalSuppressions.cs index 6c89b230..44ad3af5 100644 --- a/Timeline/GlobalSuppressions.cs +++ b/Timeline/GlobalSuppressions.cs @@ -6,5 +6,6 @@ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Reliability", "CA2007:Consider calling ConfigureAwait on the awaited task", Justification = "This is not a UI application.")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1034:Nested types should not be visible", Justification = "This is not bad.")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1062:Validate arguments of public methods", Justification = "No need to check the null because it's ASP.Net's duty.", Scope = "namespaceanddescendants", Target = "Timeline.Controllers")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1062:Validate arguments of public methods", Justification = "Migrations code are auto generated.", Scope = "namespaceanddescendants", Target = "Timeline.Migrations")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "CA1707:Identifiers should not contain underscores", Justification = "Error code constant identifiers.", Scope = "type", Target = "Timeline.ErrorCodes")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "CA1716:Identifiers should not match keywords", Justification = "Error code constant identifiers.", Scope = "type", Target = "Timeline.ErrorCodes")]
diff --git a/Timeline/Helpers/StringLocalizerFactoryExtensions.cs b/Timeline/Helpers/StringLocalizerFactoryExtensions.cs index 3cb561f5..c2252b2c 100644 --- a/Timeline/Helpers/StringLocalizerFactoryExtensions.cs +++ b/Timeline/Helpers/StringLocalizerFactoryExtensions.cs @@ -10,5 +10,10 @@ namespace Timeline.Helpers {
return factory.Create(basename, new AssemblyName(typeof(StringLocalizerFactoryExtensions).Assembly.FullName!).Name);
}
+
+ internal static StringLocalizer<T> Create<T>(this IStringLocalizerFactory factory)
+ {
+ return new StringLocalizer<T>(factory);
+ }
}
}
\ No newline at end of file diff --git a/Timeline/Models/Http/User.cs b/Timeline/Models/Http/User.cs index 98406fec..516c1329 100644 --- a/Timeline/Models/Http/User.cs +++ b/Timeline/Models/Http/User.cs @@ -20,9 +20,11 @@ namespace Timeline.Models.Http public class ChangeUsernameRequest
{
[Required]
+ [Username]
public string OldUsername { get; set; } = default!;
- [Required, ValidateWith(typeof(UsernameValidator))]
+ [Required]
+ [Username]
public string NewUsername { get; set; } = default!;
}
diff --git a/Timeline/Models/UserConvert.cs b/Timeline/Models/UserConvert.cs new file mode 100644 index 00000000..5b132421 --- /dev/null +++ b/Timeline/Models/UserConvert.cs @@ -0,0 +1,67 @@ +using System;
+using System.Collections.Generic;
+using System.Linq;
+using Timeline.Entities;
+using Timeline.Services;
+
+namespace Timeline.Models
+{
+ public static class UserConvert
+ {
+ public static UserInfo CreateUserInfo(User user)
+ {
+ if (user == null)
+ throw new ArgumentNullException(nameof(user));
+ return new UserInfo(user.Name, UserRoleConvert.ToBool(user.RoleString));
+ }
+
+ internal static UserCache CreateUserCache(User user)
+ {
+ if (user == null)
+ throw new ArgumentNullException(nameof(user));
+ return new UserCache
+ {
+ Username = user.Name,
+ Administrator = UserRoleConvert.ToBool(user.RoleString),
+ Version = user.Version
+ };
+ }
+ }
+
+ [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1062:Validate arguments of public methods", Justification = "No need.")]
+ public static class UserRoleConvert
+ {
+ public const string UserRole = UserRoles.User;
+ public const string AdminRole = UserRoles.Admin;
+
+ public static string[] ToArray(bool administrator)
+ {
+ return administrator ? new string[] { UserRole, AdminRole } : new string[] { UserRole };
+ }
+
+ public static string[] ToArray(string s)
+ {
+ return s.Split(',').ToArray();
+ }
+
+ public static bool ToBool(IReadOnlyCollection<string> roles)
+ {
+ return roles.Contains(AdminRole);
+ }
+
+ public static string ToString(IReadOnlyCollection<string> roles)
+ {
+ return string.Join(',', roles);
+ }
+
+ public static string ToString(bool administrator)
+ {
+ return administrator ? UserRole + "," + AdminRole : UserRole;
+ }
+
+ public static bool ToBool(string s)
+ {
+ return s.Contains("admin", StringComparison.InvariantCulture);
+ }
+ }
+}
diff --git a/Timeline/Models/UserInfo.cs b/Timeline/Models/UserInfo.cs index e502855b..b60bdfa2 100644 --- a/Timeline/Models/UserInfo.cs +++ b/Timeline/Models/UserInfo.cs @@ -12,8 +12,8 @@ namespace Timeline.Models Administrator = administrator;
}
- public string Username { get; set; }
- public bool Administrator { get; set; }
+ public string Username { get; set; } = default!;
+ public bool Administrator { get; set; } = default!;
public override string ToString()
{
diff --git a/Timeline/Models/UserUtility.cs b/Timeline/Models/UserUtility.cs deleted file mode 100644 index 405987b5..00000000 --- a/Timeline/Models/UserUtility.cs +++ /dev/null @@ -1,60 +0,0 @@ -using System;
-using System.Linq;
-using Timeline.Entities;
-using Timeline.Services;
-
-namespace Timeline.Models
-{
- public static class UserUtility
- {
- public const string UserRole = UserRoles.User;
- public const string AdminRole = UserRoles.Admin;
-
- public static string[] UserRoleArray { get; } = new string[] { UserRole };
- public static string[] AdminRoleArray { get; } = new string[] { UserRole, AdminRole };
-
- public static string[] IsAdminToRoleArray(bool isAdmin)
- {
- return isAdmin ? AdminRoleArray : UserRoleArray;
- }
-
- public static bool RoleArrayToIsAdmin(string[] roles)
- {
- return roles.Contains(AdminRole);
- }
-
- public static string[] RoleStringToRoleArray(string roleString)
- {
- return roleString.Split(',').ToArray();
- }
-
- public static string RoleArrayToRoleString(string[] roles)
- {
- return string.Join(',', roles);
- }
-
- public static string IsAdminToRoleString(bool isAdmin)
- {
- return RoleArrayToRoleString(IsAdminToRoleArray(isAdmin));
- }
-
- public static bool RoleStringToIsAdmin(string roleString)
- {
- return RoleArrayToIsAdmin(RoleStringToRoleArray(roleString));
- }
-
- public static UserInfo CreateUserInfo(User user)
- {
- if (user == null)
- throw new ArgumentNullException(nameof(user));
- return new UserInfo(user.Name, RoleStringToIsAdmin(user.RoleString));
- }
-
- internal static UserCache CreateUserCache(User user)
- {
- if (user == null)
- throw new ArgumentNullException(nameof(user));
- return new UserCache { Username = user.Name, Administrator = RoleStringToIsAdmin(user.RoleString), Version = user.Version };
- }
- }
-}
diff --git a/Timeline/Models/Validation/UsernameValidator.cs b/Timeline/Models/Validation/UsernameValidator.cs index 65d4da71..dc237add 100644 --- a/Timeline/Models/Validation/UsernameValidator.cs +++ b/Timeline/Models/Validation/UsernameValidator.cs @@ -1,4 +1,5 @@ -using System.Linq;
+using System;
+using System.Linq;
namespace Timeline.Models.Validation
{
@@ -36,4 +37,15 @@ namespace Timeline.Models.Validation return (true, SuccessMessageGenerator);
}
}
+
+ [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter,
+ AllowMultiple = false)]
+ public class UsernameAttribute : ValidateWithAttribute
+ {
+ public UsernameAttribute()
+ : base(typeof(UsernameValidator))
+ {
+
+ }
+ }
}
diff --git a/Timeline/Models/Validation/Validator.cs b/Timeline/Models/Validation/Validator.cs index 606ba7b4..d2c7c377 100644 --- a/Timeline/Models/Validation/Validator.cs +++ b/Timeline/Models/Validation/Validator.cs @@ -8,7 +8,7 @@ namespace Timeline.Models.Validation {
/// <summary>
/// Generate a message from a localizer factory.
- /// If localizerFactory is null, it should return a neutral-cultural message.
+ /// If localizerFactory is null, it should return a culture-invariant message.
/// </summary>
/// <param name="localizerFactory">The localizer factory. Could be null.</param>
/// <returns>The message.</returns>
diff --git a/Timeline/Program.cs b/Timeline/Program.cs index 7474fe2f..4a098adf 100644 --- a/Timeline/Program.cs +++ b/Timeline/Program.cs @@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
+using System.Resources;
namespace Timeline
{
diff --git a/Timeline/Resources/Authentication/AuthHandler.Designer.cs b/Timeline/Resources/Authentication/AuthHandler.Designer.cs new file mode 100644 index 00000000..fd4540ea --- /dev/null +++ b/Timeline/Resources/Authentication/AuthHandler.Designer.cs @@ -0,0 +1,99 @@ +//------------------------------------------------------------------------------
+// <auto-generated>
+// This code was generated by a tool.
+// Runtime Version:4.0.30319.42000
+//
+// Changes to this file may cause incorrect behavior and will be lost if
+// the code is regenerated.
+// </auto-generated>
+//------------------------------------------------------------------------------
+
+namespace Timeline.Resources.Authentication {
+ using System;
+
+
+ /// <summary>
+ /// A strongly-typed resource class, for looking up localized strings, etc.
+ /// </summary>
+ // This class was auto-generated by the StronglyTypedResourceBuilder
+ // class via a tool like ResGen or Visual Studio.
+ // To add or remove a member, edit your .ResX file then rerun ResGen
+ // with the /str option, or rebuild your VS project.
+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+ internal class AuthHandler {
+
+ private static global::System.Resources.ResourceManager resourceMan;
+
+ private static global::System.Globalization.CultureInfo resourceCulture;
+
+ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
+ internal AuthHandler() {
+ }
+
+ /// <summary>
+ /// Returns the cached ResourceManager instance used by this class.
+ /// </summary>
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Resources.ResourceManager ResourceManager {
+ get {
+ if (object.ReferenceEquals(resourceMan, null)) {
+ global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Timeline.Resources.Authentication.AuthHandler", typeof(AuthHandler).Assembly);
+ resourceMan = temp;
+ }
+ return resourceMan;
+ }
+ }
+
+ /// <summary>
+ /// Overrides the current thread's CurrentUICulture property for all
+ /// resource lookups using this strongly typed resource class.
+ /// </summary>
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Globalization.CultureInfo Culture {
+ get {
+ return resourceCulture;
+ }
+ set {
+ resourceCulture = value;
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Token is found in authorization header. Token is {0} ..
+ /// </summary>
+ internal static string LogTokenFoundInHeader {
+ get {
+ return ResourceManager.GetString("LogTokenFoundInHeader", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Token is found in query param with key "{0}". Token is {1} ..
+ /// </summary>
+ internal static string LogTokenFoundInQuery {
+ get {
+ return ResourceManager.GetString("LogTokenFoundInQuery", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to No jwt token is found..
+ /// </summary>
+ internal static string LogTokenNotFound {
+ get {
+ return ResourceManager.GetString("LogTokenNotFound", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to A jwt token validation failed..
+ /// </summary>
+ internal static string LogTokenValidationFail {
+ get {
+ return ResourceManager.GetString("LogTokenValidationFail", resourceCulture);
+ }
+ }
+ }
+}
diff --git a/Timeline/Resources/Authentication/AuthHandler.resx b/Timeline/Resources/Authentication/AuthHandler.resx new file mode 100644 index 00000000..4cddc8ce --- /dev/null +++ b/Timeline/Resources/Authentication/AuthHandler.resx @@ -0,0 +1,132 @@ +<?xml version="1.0" encoding="utf-8"?>
+<root>
+ <!--
+ Microsoft ResX Schema
+
+ Version 2.0
+
+ The primary goals of this format is to allow a simple XML format
+ that is mostly human readable. The generation and parsing of the
+ various data types are done through the TypeConverter classes
+ associated with the data types.
+
+ Example:
+
+ ... ado.net/XML headers & schema ...
+ <resheader name="resmimetype">text/microsoft-resx</resheader>
+ <resheader name="version">2.0</resheader>
+ <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
+ <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
+ <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
+ <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
+ <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
+ <value>[base64 mime encoded serialized .NET Framework object]</value>
+ </data>
+ <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
+ <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
+ <comment>This is a comment</comment>
+ </data>
+
+ There are any number of "resheader" rows that contain simple
+ name/value pairs.
+
+ Each data row contains a name, and value. The row also contains a
+ type or mimetype. Type corresponds to a .NET class that support
+ text/value conversion through the TypeConverter architecture.
+ Classes that don't support this are serialized and stored with the
+ mimetype set.
+
+ The mimetype is used for serialized objects, and tells the
+ ResXResourceReader how to depersist the object. This is currently not
+ extensible. For a given mimetype the value must be set accordingly:
+
+ Note - application/x-microsoft.net.object.binary.base64 is the format
+ that the ResXResourceWriter will generate, however the reader can
+ read any of the formats listed below.
+
+ mimetype: application/x-microsoft.net.object.binary.base64
+ value : The object must be serialized with
+ : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
+ : and then encoded with base64 encoding.
+
+ mimetype: application/x-microsoft.net.object.soap.base64
+ value : The object must be serialized with
+ : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
+ : and then encoded with base64 encoding.
+
+ mimetype: application/x-microsoft.net.object.bytearray.base64
+ value : The object must be serialized into a byte array
+ : using a System.ComponentModel.TypeConverter
+ : and then encoded with base64 encoding.
+ -->
+ <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
+ <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
+ <xsd:element name="root" msdata:IsDataSet="true">
+ <xsd:complexType>
+ <xsd:choice maxOccurs="unbounded">
+ <xsd:element name="metadata">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" />
+ </xsd:sequence>
+ <xsd:attribute name="name" use="required" type="xsd:string" />
+ <xsd:attribute name="type" type="xsd:string" />
+ <xsd:attribute name="mimetype" type="xsd:string" />
+ <xsd:attribute ref="xml:space" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="assembly">
+ <xsd:complexType>
+ <xsd:attribute name="alias" type="xsd:string" />
+ <xsd:attribute name="name" type="xsd:string" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="data">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+ <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
+ </xsd:sequence>
+ <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
+ <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
+ <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
+ <xsd:attribute ref="xml:space" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="resheader">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+ </xsd:sequence>
+ <xsd:attribute name="name" type="xsd:string" use="required" />
+ </xsd:complexType>
+ </xsd:element>
+ </xsd:choice>
+ </xsd:complexType>
+ </xsd:element>
+ </xsd:schema>
+ <resheader name="resmimetype">
+ <value>text/microsoft-resx</value>
+ </resheader>
+ <resheader name="version">
+ <value>2.0</value>
+ </resheader>
+ <resheader name="reader">
+ <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+ </resheader>
+ <resheader name="writer">
+ <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+ </resheader>
+ <data name="LogTokenFoundInHeader" xml:space="preserve">
+ <value>Token is found in authorization header. Token is {0} .</value>
+ </data>
+ <data name="LogTokenFoundInQuery" xml:space="preserve">
+ <value>Token is found in query param with key "{0}". Token is {1} .</value>
+ </data>
+ <data name="LogTokenNotFound" xml:space="preserve">
+ <value>No jwt token is found.</value>
+ </data>
+ <data name="LogTokenValidationFail" xml:space="preserve">
+ <value>A jwt token validation failed.</value>
+ </data>
+</root>
\ No newline at end of file diff --git a/Timeline/Resources/Services/Exception.Designer.cs b/Timeline/Resources/Services/Exception.Designer.cs index 15a8169e..24f6b8e6 100644 --- a/Timeline/Resources/Services/Exception.Designer.cs +++ b/Timeline/Resources/Services/Exception.Designer.cs @@ -70,6 +70,69 @@ namespace Timeline.Resources.Services { }
/// <summary>
+ /// Looks up a localized string similar to The hashes password is of bad format. It might not be created by server..
+ /// </summary>
+ internal static string HashedPasswordBadFromatException {
+ get {
+ return ResourceManager.GetString("HashedPasswordBadFromatException", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Not of valid base64 format. See inner exception..
+ /// </summary>
+ internal static string HashedPasswordBadFromatExceptionNotBase64 {
+ get {
+ return ResourceManager.GetString("HashedPasswordBadFromatExceptionNotBase64", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Decoded hashed password is of length 0..
+ /// </summary>
+ internal static string HashedPasswordBadFromatExceptionNotLength0 {
+ get {
+ return ResourceManager.GetString("HashedPasswordBadFromatExceptionNotLength0", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to See inner exception..
+ /// </summary>
+ internal static string HashedPasswordBadFromatExceptionNotOthers {
+ get {
+ return ResourceManager.GetString("HashedPasswordBadFromatExceptionNotOthers", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Salt length < 128 bits..
+ /// </summary>
+ internal static string HashedPasswordBadFromatExceptionNotSaltTooShort {
+ get {
+ return ResourceManager.GetString("HashedPasswordBadFromatExceptionNotSaltTooShort", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Subkey length < 128 bits..
+ /// </summary>
+ internal static string HashedPasswordBadFromatExceptionNotSubkeyTooShort {
+ get {
+ return ResourceManager.GetString("HashedPasswordBadFromatExceptionNotSubkeyTooShort", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Unknown format marker..
+ /// </summary>
+ internal static string HashedPasswordBadFromatExceptionNotUnknownMarker {
+ get {
+ return ResourceManager.GetString("HashedPasswordBadFromatExceptionNotUnknownMarker", resourceCulture);
+ }
+ }
+
+ /// <summary>
/// Looks up a localized string similar to The version of the jwt token is old..
/// </summary>
internal static string JwtBadVersionException {
diff --git a/Timeline/Resources/Services/Exception.resx b/Timeline/Resources/Services/Exception.resx index af771393..408c45a1 100644 --- a/Timeline/Resources/Services/Exception.resx +++ b/Timeline/Resources/Services/Exception.resx @@ -120,6 +120,27 @@ <data name="BadPasswordException" xml:space="preserve">
<value>The password is wrong.</value>
</data>
+ <data name="HashedPasswordBadFromatException" xml:space="preserve">
+ <value>The hashes password is of bad format. It might not be created by server.</value>
+ </data>
+ <data name="HashedPasswordBadFromatExceptionNotBase64" xml:space="preserve">
+ <value>Not of valid base64 format. See inner exception.</value>
+ </data>
+ <data name="HashedPasswordBadFromatExceptionNotLength0" xml:space="preserve">
+ <value>Decoded hashed password is of length 0.</value>
+ </data>
+ <data name="HashedPasswordBadFromatExceptionNotOthers" xml:space="preserve">
+ <value>See inner exception.</value>
+ </data>
+ <data name="HashedPasswordBadFromatExceptionNotSaltTooShort" xml:space="preserve">
+ <value>Salt length < 128 bits.</value>
+ </data>
+ <data name="HashedPasswordBadFromatExceptionNotSubkeyTooShort" xml:space="preserve">
+ <value>Subkey length < 128 bits.</value>
+ </data>
+ <data name="HashedPasswordBadFromatExceptionNotUnknownMarker" xml:space="preserve">
+ <value>Unknown format marker.</value>
+ </data>
<data name="JwtBadVersionException" xml:space="preserve">
<value>The version of the jwt token is old.</value>
</data>
diff --git a/Timeline/Resources/Services/UserService.Designer.cs b/Timeline/Resources/Services/UserService.Designer.cs new file mode 100644 index 00000000..2a04dded --- /dev/null +++ b/Timeline/Resources/Services/UserService.Designer.cs @@ -0,0 +1,126 @@ +//------------------------------------------------------------------------------
+// <auto-generated>
+// This code was generated by a tool.
+// Runtime Version:4.0.30319.42000
+//
+// Changes to this file may cause incorrect behavior and will be lost if
+// the code is regenerated.
+// </auto-generated>
+//------------------------------------------------------------------------------
+
+namespace Timeline.Resources.Services {
+ using System;
+
+
+ /// <summary>
+ /// A strongly-typed resource class, for looking up localized strings, etc.
+ /// </summary>
+ // This class was auto-generated by the StronglyTypedResourceBuilder
+ // class via a tool like ResGen or Visual Studio.
+ // To add or remove a member, edit your .ResX file then rerun ResGen
+ // with the /str option, or rebuild your VS project.
+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+ internal class UserService {
+
+ private static global::System.Resources.ResourceManager resourceMan;
+
+ private static global::System.Globalization.CultureInfo resourceCulture;
+
+ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
+ internal UserService() {
+ }
+
+ /// <summary>
+ /// Returns the cached ResourceManager instance used by this class.
+ /// </summary>
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Resources.ResourceManager ResourceManager {
+ get {
+ if (object.ReferenceEquals(resourceMan, null)) {
+ global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Timeline.Resources.Services.UserService", typeof(UserService).Assembly);
+ resourceMan = temp;
+ }
+ return resourceMan;
+ }
+ }
+
+ /// <summary>
+ /// Overrides the current thread's CurrentUICulture property for all
+ /// resource lookups using this strongly typed resource class.
+ /// </summary>
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Globalization.CultureInfo Culture {
+ get {
+ return resourceCulture;
+ }
+ set {
+ resourceCulture = value;
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to New username is of bad format..
+ /// </summary>
+ internal static string ExceptionNewUsernameBadFormat {
+ get {
+ return ResourceManager.GetString("ExceptionNewUsernameBadFormat", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Old username is of bad format..
+ /// </summary>
+ internal static string ExceptionOldUsernameBadFormat {
+ get {
+ return ResourceManager.GetString("ExceptionOldUsernameBadFormat", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to A cache entry is created..
+ /// </summary>
+ internal static string LogCacheCreate {
+ get {
+ return ResourceManager.GetString("LogCacheCreate", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to A cache entry is removed..
+ /// </summary>
+ internal static string LogCacheRemove {
+ get {
+ return ResourceManager.GetString("LogCacheRemove", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to A new user entry is added to the database..
+ /// </summary>
+ internal static string LogDatabaseCreate {
+ get {
+ return ResourceManager.GetString("LogDatabaseCreate", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to A user entry is removed from the database..
+ /// </summary>
+ internal static string LogDatabaseRemove {
+ get {
+ return ResourceManager.GetString("LogDatabaseRemove", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to A user entry is updated to the database..
+ /// </summary>
+ internal static string LogDatabaseUpdate {
+ get {
+ return ResourceManager.GetString("LogDatabaseUpdate", resourceCulture);
+ }
+ }
+ }
+}
diff --git a/Timeline/Resources/Services/UserService.resx b/Timeline/Resources/Services/UserService.resx new file mode 100644 index 00000000..3670d8f9 --- /dev/null +++ b/Timeline/Resources/Services/UserService.resx @@ -0,0 +1,141 @@ +<?xml version="1.0" encoding="utf-8"?>
+<root>
+ <!--
+ Microsoft ResX Schema
+
+ Version 2.0
+
+ The primary goals of this format is to allow a simple XML format
+ that is mostly human readable. The generation and parsing of the
+ various data types are done through the TypeConverter classes
+ associated with the data types.
+
+ Example:
+
+ ... ado.net/XML headers & schema ...
+ <resheader name="resmimetype">text/microsoft-resx</resheader>
+ <resheader name="version">2.0</resheader>
+ <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
+ <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
+ <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
+ <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
+ <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
+ <value>[base64 mime encoded serialized .NET Framework object]</value>
+ </data>
+ <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
+ <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
+ <comment>This is a comment</comment>
+ </data>
+
+ There are any number of "resheader" rows that contain simple
+ name/value pairs.
+
+ Each data row contains a name, and value. The row also contains a
+ type or mimetype. Type corresponds to a .NET class that support
+ text/value conversion through the TypeConverter architecture.
+ Classes that don't support this are serialized and stored with the
+ mimetype set.
+
+ The mimetype is used for serialized objects, and tells the
+ ResXResourceReader how to depersist the object. This is currently not
+ extensible. For a given mimetype the value must be set accordingly:
+
+ Note - application/x-microsoft.net.object.binary.base64 is the format
+ that the ResXResourceWriter will generate, however the reader can
+ read any of the formats listed below.
+
+ mimetype: application/x-microsoft.net.object.binary.base64
+ value : The object must be serialized with
+ : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
+ : and then encoded with base64 encoding.
+
+ mimetype: application/x-microsoft.net.object.soap.base64
+ value : The object must be serialized with
+ : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
+ : and then encoded with base64 encoding.
+
+ mimetype: application/x-microsoft.net.object.bytearray.base64
+ value : The object must be serialized into a byte array
+ : using a System.ComponentModel.TypeConverter
+ : and then encoded with base64 encoding.
+ -->
+ <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
+ <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
+ <xsd:element name="root" msdata:IsDataSet="true">
+ <xsd:complexType>
+ <xsd:choice maxOccurs="unbounded">
+ <xsd:element name="metadata">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" />
+ </xsd:sequence>
+ <xsd:attribute name="name" use="required" type="xsd:string" />
+ <xsd:attribute name="type" type="xsd:string" />
+ <xsd:attribute name="mimetype" type="xsd:string" />
+ <xsd:attribute ref="xml:space" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="assembly">
+ <xsd:complexType>
+ <xsd:attribute name="alias" type="xsd:string" />
+ <xsd:attribute name="name" type="xsd:string" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="data">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+ <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
+ </xsd:sequence>
+ <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
+ <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
+ <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
+ <xsd:attribute ref="xml:space" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="resheader">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+ </xsd:sequence>
+ <xsd:attribute name="name" type="xsd:string" use="required" />
+ </xsd:complexType>
+ </xsd:element>
+ </xsd:choice>
+ </xsd:complexType>
+ </xsd:element>
+ </xsd:schema>
+ <resheader name="resmimetype">
+ <value>text/microsoft-resx</value>
+ </resheader>
+ <resheader name="version">
+ <value>2.0</value>
+ </resheader>
+ <resheader name="reader">
+ <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+ </resheader>
+ <resheader name="writer">
+ <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+ </resheader>
+ <data name="ExceptionNewUsernameBadFormat" xml:space="preserve">
+ <value>New username is of bad format.</value>
+ </data>
+ <data name="ExceptionOldUsernameBadFormat" xml:space="preserve">
+ <value>Old username is of bad format.</value>
+ </data>
+ <data name="LogCacheCreate" xml:space="preserve">
+ <value>A cache entry is created.</value>
+ </data>
+ <data name="LogCacheRemove" xml:space="preserve">
+ <value>A cache entry is removed.</value>
+ </data>
+ <data name="LogDatabaseCreate" xml:space="preserve">
+ <value>A new user entry is added to the database.</value>
+ </data>
+ <data name="LogDatabaseRemove" xml:space="preserve">
+ <value>A user entry is removed from the database.</value>
+ </data>
+ <data name="LogDatabaseUpdate" xml:space="preserve">
+ <value>A user entry is updated to the database.</value>
+ </data>
+</root>
\ No newline at end of file diff --git a/Timeline/Services/PasswordService.cs b/Timeline/Services/PasswordService.cs index e09a1365..e04a861b 100644 --- a/Timeline/Services/PasswordService.cs +++ b/Timeline/Services/PasswordService.cs @@ -12,13 +12,23 @@ namespace Timeline.Services [Serializable]
public class HashedPasswordBadFromatException : Exception
{
- public HashedPasswordBadFromatException(string hashedPassword, string message) : base(message) { HashedPassword = hashedPassword; }
- public HashedPasswordBadFromatException(string hashedPassword, string message, Exception inner) : base(message, inner) { HashedPassword = hashedPassword; }
+ private static string MakeMessage(string reason)
+ {
+ return Resources.Services.Exception.HashedPasswordBadFromatException + " Reason: " + reason;
+ }
+
+ public HashedPasswordBadFromatException() : base(Resources.Services.Exception.HashedPasswordBadFromatException) { }
+
+ public HashedPasswordBadFromatException(string message) : base(message) { }
+ public HashedPasswordBadFromatException(string message, Exception inner) : base(message, inner) { }
+
+ public HashedPasswordBadFromatException(string hashedPassword, string reason) : base(MakeMessage(reason)) { HashedPassword = hashedPassword; }
+ public HashedPasswordBadFromatException(string hashedPassword, string reason, Exception inner) : base(MakeMessage(reason), inner) { HashedPassword = hashedPassword; }
protected HashedPasswordBadFromatException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context) : base(info, context) { }
- public string HashedPassword { get; private set; }
+ public string? HashedPassword { get; set; }
}
public interface IPasswordService
@@ -140,22 +150,20 @@ namespace Timeline.Services }
catch (FormatException e)
{
- throw new HashedPasswordBadFromatException(hashedPassword, "Not of valid base64 format. See inner exception.", e);
+ throw new HashedPasswordBadFromatException(hashedPassword, Resources.Services.Exception.HashedPasswordBadFromatExceptionNotBase64, e);
}
// read the format marker from the hashed password
if (decodedHashedPassword.Length == 0)
{
- throw new HashedPasswordBadFromatException(hashedPassword, "Decoded hashed password is of length 0.");
+ throw new HashedPasswordBadFromatException(hashedPassword, Resources.Services.Exception.HashedPasswordBadFromatExceptionNotLength0);
}
- switch (decodedHashedPassword[0])
- {
- case 0x01:
- return VerifyHashedPasswordV3(decodedHashedPassword, providedPassword, hashedPassword);
- default:
- throw new HashedPasswordBadFromatException(hashedPassword, "Unknown format marker.");
- }
+ return (decodedHashedPassword[0]) switch
+ {
+ 0x01 => VerifyHashedPasswordV3(decodedHashedPassword, providedPassword, hashedPassword),
+ _ => throw new HashedPasswordBadFromatException(hashedPassword, Resources.Services.Exception.HashedPasswordBadFromatExceptionNotUnknownMarker),
+ };
}
private bool VerifyHashedPasswordV3(byte[] hashedPassword, string password, string hashedPasswordString)
@@ -170,7 +178,7 @@ namespace Timeline.Services // Read the salt: must be >= 128 bits
if (saltLength < 128 / 8)
{
- throw new HashedPasswordBadFromatException(hashedPasswordString, "Salt length < 128 bits.");
+ throw new HashedPasswordBadFromatException(hashedPasswordString, Resources.Services.Exception.HashedPasswordBadFromatExceptionNotSaltTooShort);
}
byte[] salt = new byte[saltLength];
Buffer.BlockCopy(hashedPassword, 13, salt, 0, salt.Length);
@@ -179,7 +187,7 @@ namespace Timeline.Services int subkeyLength = hashedPassword.Length - 13 - salt.Length;
if (subkeyLength < 128 / 8)
{
- throw new HashedPasswordBadFromatException(hashedPasswordString, "Subkey length < 128 bits.");
+ throw new HashedPasswordBadFromatException(hashedPasswordString, Resources.Services.Exception.HashedPasswordBadFromatExceptionNotSubkeyTooShort);
}
byte[] expectedSubkey = new byte[subkeyLength];
Buffer.BlockCopy(hashedPassword, 13 + salt.Length, expectedSubkey, 0, expectedSubkey.Length);
@@ -193,7 +201,7 @@ namespace Timeline.Services // This should never occur except in the case of a malformed payload, where
// we might go off the end of the array. Regardless, a malformed payload
// implies verification failed.
- throw new HashedPasswordBadFromatException(hashedPasswordString, "See inner exception.", e);
+ throw new HashedPasswordBadFromatException(hashedPasswordString, Resources.Services.Exception.HashedPasswordBadFromatExceptionNotOthers, e);
}
}
diff --git a/Timeline/Services/UserService.cs b/Timeline/Services/UserService.cs index 45ef8a5c..d706d05e 100644 --- a/Timeline/Services/UserService.cs +++ b/Timeline/Services/UserService.cs @@ -1,15 +1,13 @@ using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
-using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading.Tasks;
using Timeline.Entities;
+using Timeline.Helpers;
using Timeline.Models;
using Timeline.Models.Validation;
-using static Timeline.Helpers.MyLogHelper;
-using static Timeline.Models.UserUtility;
namespace Timeline.Services
{
@@ -30,6 +28,7 @@ namespace Timeline.Services /// <param name="expires">The expired time point. Null then use default. See <see cref="JwtService.GenerateJwtToken(TokenInfo, DateTime?)"/> for what is default.</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="UsernameBadFormatException">Thrown when username is of bad format.</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, DateTime? expires = null);
@@ -50,6 +49,8 @@ namespace Timeline.Services /// </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>
+ /// <exception cref="ArgumentNullException">Thrown when <paramref name="username"/> is null.</exception>
+ /// <exception cref="UsernameBadFormatException">Thrown when <paramref name="username"/> is of bad format.</exception>
Task<UserInfo> GetUser(string username);
/// <summary>
@@ -82,6 +83,7 @@ namespace Timeline.Services /// <param name="password">New password. Null if not modify.</param>
/// <param name="administrator">Whether the user is administrator. Null if not modify.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="username"/> is null.</exception>
+ /// <exception cref="UsernameBadFormatException">Thrown when <paramref name="username"/> is of bad format.</exception>
/// <exception cref="UserNotExistException">Thrown if the user with given username does not exist.</exception>
Task PatchUser(string username, string? password, bool? administrator);
@@ -90,6 +92,7 @@ namespace Timeline.Services /// </summary>
/// <param name="username">Username of thet user to delete. Can't be null.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="username"/> is null.</exception>
+ /// <exception cref="UsernameBadFormatException">Thrown when <paramref name="username"/> is of bad format.</exception>
/// <exception cref="UserNotExistException">Thrown if the user with given username does not exist.</exception>
Task DeleteUser(string username);
@@ -100,6 +103,7 @@ namespace Timeline.Services /// <param name="oldPassword">The user's old password.</param>
/// <param name="newPassword">The user's new password.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="username"/> or <paramref name="oldPassword"/> or <paramref name="newPassword"/> is null.</exception>
+ /// <exception cref="UsernameBadFormatException">Thrown when <paramref name="username"/> is of bad format.</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(string username, string oldPassword, string newPassword);
@@ -109,9 +113,9 @@ namespace Timeline.Services /// </summary>
/// <param name="oldUsername">The user's old username.</param>
/// <param name="newUsername">The new username.</param>
- /// <exception cref="ArgumentException">Thrown if <paramref name="oldUsername"/> or <paramref name="newUsername"/> is null or empty.</exception>
+ /// <exception cref="ArgumentNullException">Thrown if <paramref name="oldUsername"/> or <paramref name="newUsername"/> is null.</exception>
/// <exception cref="UserNotExistException">Thrown if the user with old username does not exist.</exception>
- /// <exception cref="UsernameBadFormatException">Thrown if the new username is not accepted because of bad format.</exception>
+ /// <exception cref="UsernameBadFormatException">Thrown if the <paramref name="oldUsername"/> or <paramref name="newUsername"/> is of bad format.</exception>
/// <exception cref="UsernameConfictException">Thrown if user with the new username already exists.</exception>
Task ChangeUsername(string oldUsername, string newUsername);
}
@@ -157,7 +161,19 @@ namespace Timeline.Services {
var key = GenerateCacheKeyByUserId(id);
_memoryCache.Remove(key);
- _logger.LogInformation(FormatLogMessage("A cache entry is removed.", Pair("Key", key)));
+ _logger.LogInformation(Log.Format(Resources.Services.UserService.LogCacheRemove, ("Key", key)));
+ }
+
+ private void CheckUsernameFormat(string username, string? message = null)
+ {
+ var (result, messageGenerator) = _usernameValidator.Validate(username);
+ if (!result)
+ {
+ if (message == null)
+ throw new UsernameBadFormatException(username, messageGenerator(null));
+ else
+ throw new UsernameBadFormatException(username, message + messageGenerator(null));
+ }
}
public async Task<CreateTokenResult> CreateToken(string username, string password, DateTime? expires)
@@ -166,6 +182,7 @@ namespace Timeline.Services throw new ArgumentNullException(nameof(username));
if (password == null)
throw new ArgumentNullException(nameof(password));
+ CheckUsernameFormat(username);
// We need password info, so always check the database.
var user = await _databaseContext.Users.Where(u => u.Name == username).SingleOrDefaultAsync();
@@ -185,7 +202,7 @@ namespace Timeline.Services return new CreateTokenResult
{
Token = token,
- User = CreateUserInfo(user)
+ User = UserConvert.CreateUserInfo(user)
};
}
@@ -208,9 +225,9 @@ namespace Timeline.Services throw new UserNotExistException(id);
// create cache
- cache = CreateUserCache(user);
+ cache = UserConvert.CreateUserCache(user);
_memoryCache.CreateEntry(key).SetValue(cache);
- _logger.LogInformation(FormatLogMessage("A cache entry is created.", Pair("Key", key)));
+ _logger.LogInformation(Log.Format(Resources.Services.UserService.LogCacheCreate, ("Key", key)));
}
if (tokenInfo.Version != cache.Version)
@@ -221,16 +238,20 @@ namespace Timeline.Services public async Task<UserInfo> GetUser(string username)
{
+ if (username == null)
+ throw new ArgumentNullException(nameof(username));
+ CheckUsernameFormat(username);
+
return await _databaseContext.Users
.Where(user => user.Name == username)
- .Select(user => CreateUserInfo(user))
+ .Select(user => UserConvert.CreateUserInfo(user))
.SingleOrDefaultAsync();
}
public async Task<UserInfo[]> ListUsers()
{
return await _databaseContext.Users
- .Select(user => CreateUserInfo(user))
+ .Select(user => UserConvert.CreateUserInfo(user))
.ToArrayAsync();
}
@@ -240,12 +261,7 @@ namespace Timeline.Services throw new ArgumentNullException(nameof(username));
if (password == null)
throw new ArgumentNullException(nameof(password));
-
- var (result, messageGenerator) = _usernameValidator.Validate(username);
- if (!result)
- {
- throw new UsernameBadFormatException(username, messageGenerator(null));
- }
+ CheckUsernameFormat(username);
var user = await _databaseContext.Users.Where(u => u.Name == username).SingleOrDefaultAsync();
@@ -255,20 +271,22 @@ namespace Timeline.Services {
Name = username,
EncryptedPassword = _passwordService.HashPassword(password),
- RoleString = IsAdminToRoleString(administrator),
+ RoleString = UserRoleConvert.ToString(administrator),
Avatar = UserAvatar.Create(DateTime.Now)
};
await _databaseContext.AddAsync(newUser);
await _databaseContext.SaveChangesAsync();
- _logger.LogInformation(FormatLogMessage("A new user entry is added to the database.", Pair("Id", newUser.Id)));
+ _logger.LogInformation(Log.Format(Resources.Services.UserService.LogDatabaseCreate,
+ ("Id", newUser.Id), ("Username", username), ("Administrator", administrator)));
return PutResult.Create;
}
user.EncryptedPassword = _passwordService.HashPassword(password);
- user.RoleString = IsAdminToRoleString(administrator);
+ user.RoleString = UserRoleConvert.ToString(administrator);
user.Version += 1;
await _databaseContext.SaveChangesAsync();
- _logger.LogInformation(FormatLogMessage("A user entry is updated to the database.", Pair("Id", user.Id)));
+ _logger.LogInformation(Log.Format(Resources.Services.UserService.LogDatabaseUpdate,
+ ("Id", user.Id), ("Username", username), ("Administrator", administrator)));
//clear cache
RemoveCache(user.Id);
@@ -276,10 +294,11 @@ namespace Timeline.Services return PutResult.Modify;
}
- public async Task PatchUser(string username, string password, bool? administrator)
+ public async Task PatchUser(string username, string? password, bool? administrator)
{
if (username == null)
throw new ArgumentNullException(nameof(username));
+ CheckUsernameFormat(username);
var user = await _databaseContext.Users.Where(u => u.Name == username).SingleOrDefaultAsync();
if (user == null)
@@ -292,12 +311,12 @@ namespace Timeline.Services if (administrator != null)
{
- user.RoleString = IsAdminToRoleString(administrator.Value);
+ user.RoleString = UserRoleConvert.ToString(administrator.Value);
}
user.Version += 1;
await _databaseContext.SaveChangesAsync();
- _logger.LogInformation(FormatLogMessage("A user entry is updated to the database.", Pair("Id", user.Id)));
+ _logger.LogInformation(Resources.Services.UserService.LogDatabaseUpdate, ("Id", user.Id));
//clear cache
RemoveCache(user.Id);
@@ -307,6 +326,7 @@ namespace Timeline.Services {
if (username == null)
throw new ArgumentNullException(nameof(username));
+ CheckUsernameFormat(username);
var user = await _databaseContext.Users.Where(u => u.Name == username).SingleOrDefaultAsync();
if (user == null)
@@ -314,7 +334,8 @@ namespace Timeline.Services _databaseContext.Users.Remove(user);
await _databaseContext.SaveChangesAsync();
- _logger.LogInformation(FormatLogMessage("A user entry is removed from the database.", Pair("Id", user.Id)));
+ _logger.LogInformation(Log.Format(Resources.Services.UserService.LogDatabaseRemove,
+ ("Id", user.Id)));
//clear cache
RemoveCache(user.Id);
@@ -328,6 +349,7 @@ namespace Timeline.Services throw new ArgumentNullException(nameof(oldPassword));
if (newPassword == null)
throw new ArgumentNullException(nameof(newPassword));
+ CheckUsernameFormat(username);
var user = await _databaseContext.Users.Where(u => u.Name == username).SingleOrDefaultAsync();
if (user == null)
@@ -340,23 +362,20 @@ namespace Timeline.Services user.EncryptedPassword = _passwordService.HashPassword(newPassword);
user.Version += 1;
await _databaseContext.SaveChangesAsync();
+ _logger.LogInformation(Log.Format(Resources.Services.UserService.LogDatabaseUpdate,
+ ("Id", user.Id), ("Operation", "Change password")));
//clear cache
RemoveCache(user.Id);
}
public async Task ChangeUsername(string oldUsername, string newUsername)
{
- if (string.IsNullOrEmpty(oldUsername))
- throw new ArgumentException("Old username is null or empty", nameof(oldUsername));
- if (string.IsNullOrEmpty(newUsername))
- throw new ArgumentException("New username is null or empty", nameof(newUsername));
-
-
- var (result, messageGenerator) = _usernameValidator.Validate(newUsername);
- if (!result)
- {
- throw new UsernameBadFormatException(newUsername, $"New username is of bad format. {messageGenerator(null)}");
- }
+ if (oldUsername == null)
+ throw new ArgumentNullException(nameof(oldUsername));
+ if (newUsername == null)
+ throw new ArgumentNullException(nameof(newUsername));
+ CheckUsernameFormat(oldUsername, Resources.Services.UserService.ExceptionOldUsernameBadFormat);
+ CheckUsernameFormat(newUsername, Resources.Services.UserService.ExceptionNewUsernameBadFormat);
var user = await _databaseContext.Users.Where(u => u.Name == oldUsername).SingleOrDefaultAsync();
if (user == null)
@@ -369,8 +388,8 @@ namespace Timeline.Services user.Name = newUsername;
user.Version += 1;
await _databaseContext.SaveChangesAsync();
- _logger.LogInformation(FormatLogMessage("A user entry changed name field.",
- Pair("Id", user.Id), Pair("Old Username", oldUsername), Pair("New Username", newUsername)));
+ _logger.LogInformation(Log.Format(Resources.Services.UserService.LogDatabaseUpdate,
+ ("Id", user.Id), ("Old Username", oldUsername), ("New Username", newUsername)));
RemoveCache(user.Id);
}
}
diff --git a/Timeline/Startup.cs b/Timeline/Startup.cs index be5bce7c..d54ea6ca 100644 --- a/Timeline/Startup.cs +++ b/Timeline/Startup.cs @@ -8,7 +8,7 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection;
using System.Collections.Generic;
using System.Globalization;
-using Timeline.Authenticate;
+using Timeline.Authentication;
using Timeline.Configs;
using Timeline.Entities;
using Timeline.Helpers;
diff --git a/Timeline/Timeline.csproj b/Timeline/Timeline.csproj index e29c4e4b..0ba34471 100644 --- a/Timeline/Timeline.csproj +++ b/Timeline/Timeline.csproj @@ -34,6 +34,11 @@ </ItemGroup>
<ItemGroup>
+ <Compile Update="Resources\Authentication\AuthHandler.Designer.cs">
+ <DesignTime>True</DesignTime>
+ <AutoGen>True</AutoGen>
+ <DependentUpon>AuthHandler.resx</DependentUpon>
+ </Compile>
<Compile Update="Resources\Common.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
@@ -64,9 +69,18 @@ <AutoGen>True</AutoGen>
<DependentUpon>Exception.resx</DependentUpon>
</Compile>
+ <Compile Update="Resources\Services\UserService.Designer.cs">
+ <DesignTime>True</DesignTime>
+ <AutoGen>True</AutoGen>
+ <DependentUpon>UserService.resx</DependentUpon>
+ </Compile>
</ItemGroup>
<ItemGroup>
+ <EmbeddedResource Update="Resources\Authentication\AuthHandler.resx">
+ <Generator>ResXFileCodeGenerator</Generator>
+ <LastGenOutput>AuthHandler.Designer.cs</LastGenOutput>
+ </EmbeddedResource>
<EmbeddedResource Update="Resources\Common.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Common.Designer.cs</LastGenOutput>
@@ -102,5 +116,9 @@ <Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Exception.Designer.cs</LastGenOutput>
</EmbeddedResource>
+ <EmbeddedResource Update="Resources\Services\UserService.resx">
+ <Generator>ResXFileCodeGenerator</Generator>
+ <LastGenOutput>UserService.Designer.cs</LastGenOutput>
+ </EmbeddedResource>
</ItemGroup>
</Project>
|