From 325d4c7dbfba45e9c5a7518279831f54c4690d20 Mon Sep 17 00:00:00 2001 From: crupest Date: Thu, 18 Apr 2019 21:23:21 +0800 Subject: Add user management REST api. --- Timeline/Controllers/UserController.cs | 17 ----------------- 1 file changed, 17 deletions(-) (limited to 'Timeline/Controllers/UserController.cs') diff --git a/Timeline/Controllers/UserController.cs b/Timeline/Controllers/UserController.cs index 147724c1..285e0146 100644 --- a/Timeline/Controllers/UserController.cs +++ b/Timeline/Controllers/UserController.cs @@ -1,7 +1,6 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; -using System; using System.Threading.Tasks; using Timeline.Entities; using Timeline.Services; @@ -71,21 +70,5 @@ namespace Timeline.Controllers UserInfo = result }); } - - [HttpPost("[action]")] - [Authorize(Roles = "admin")] - public async Task> CreateUser([FromBody] CreateUserRequest request) - { - var result = await _userService.CreateUser(request.Username, request.Password, request.Roles); - switch (result) - { - case CreateUserResult.Success: - return Ok(new CreateUserResponse { ReturnCode = CreateUserResponse.SuccessCode }); - case CreateUserResult.AlreadyExists: - return Ok(new CreateUserResponse { ReturnCode = CreateUserResponse.AlreadyExistsCode }); - default: - throw new Exception("Unreachable code."); - } - } } } -- cgit v1.2.3 From 076e0131dff71a9f76fff13c92fffa0ef408935f Mon Sep 17 00:00:00 2001 From: crupest Date: Sun, 21 Apr 2019 00:08:59 +0800 Subject: Reorgnize api. Add basic unit test. --- Timeline.Tests/AuthorizationUnitTest.cs | 14 ++-- .../Authentication/AuthenticationExtensions.cs | 47 +++++++++++ .../AuthenticationHttpClientExtensions.cs | 38 --------- Timeline.Tests/Helpers/TestUsers.cs | 40 ++++++++++ .../Helpers/WebApplicationFactoryExtensions.cs | 21 +---- Timeline.Tests/JwtTokenUnitTest.cs | 4 +- Timeline.Tests/Timeline.Tests.csproj | 2 +- Timeline.Tests/UserUnitTest.cs | 36 +++++++++ Timeline/Configs/DatabaseConfig.cs | 7 +- Timeline/Controllers/AdminUserController.cs | 83 ------------------- Timeline/Controllers/TokenController.cs | 74 +++++++++++++++++ Timeline/Controllers/UserController.cs | 93 ++++++++++++---------- Timeline/Entities/AdminUser.cs | 14 ++-- Timeline/Entities/UserInfo.cs | 64 ++++++++++++++- nuget.config | 3 +- 15 files changed, 328 insertions(+), 212 deletions(-) create mode 100644 Timeline.Tests/Helpers/Authentication/AuthenticationExtensions.cs delete mode 100644 Timeline.Tests/Helpers/Authentication/AuthenticationHttpClientExtensions.cs create mode 100644 Timeline.Tests/Helpers/TestUsers.cs create mode 100644 Timeline.Tests/UserUnitTest.cs delete mode 100644 Timeline/Controllers/AdminUserController.cs create mode 100644 Timeline/Controllers/TokenController.cs (limited to 'Timeline/Controllers/UserController.cs') diff --git a/Timeline.Tests/AuthorizationUnitTest.cs b/Timeline.Tests/AuthorizationUnitTest.cs index e450af06..28715ada 100644 --- a/Timeline.Tests/AuthorizationUnitTest.cs +++ b/Timeline.Tests/AuthorizationUnitTest.cs @@ -26,7 +26,7 @@ namespace Timeline.Tests { using (var client = _factory.CreateDefaultClient()) { - var response = await client.GetAsync(NeedAuthorizeUrl); + var response = await client.GetAsync(NeedAuthorizeUrl); Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); } } @@ -34,10 +34,9 @@ namespace Timeline.Tests [Fact] public async Task AuthenticationTest() { - using (var client = _factory.CreateDefaultClient()) + using (var client = await _factory.CreateClientWithUser("user", "user")) { - var token = (await client.CreateUserTokenAsync("user", "user")).Token; - var response = await client.SendWithAuthenticationAsync(token, NeedAuthorizeUrl); + var response = await client.GetAsync(NeedAuthorizeUrl); Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } @@ -58,12 +57,11 @@ namespace Timeline.Tests [Fact] public async Task AdminAuthorizationTest() { - using (var client = _factory.CreateDefaultClient()) + using (var client = await _factory.CreateClientWithUser("admin", "admin")) { - var token = (await client.CreateUserTokenAsync("admin", "admin")).Token; - var response1 = await client.SendWithAuthenticationAsync(token, BothUserAndAdminUrl); + var response1 = await client.GetAsync(BothUserAndAdminUrl); Assert.Equal(HttpStatusCode.OK, response1.StatusCode); - var response2 = await client.SendWithAuthenticationAsync(token, OnlyAdminUrl); + var response2 = await client.GetAsync(OnlyAdminUrl); Assert.Equal(HttpStatusCode.OK, response2.StatusCode); } } diff --git a/Timeline.Tests/Helpers/Authentication/AuthenticationExtensions.cs b/Timeline.Tests/Helpers/Authentication/AuthenticationExtensions.cs new file mode 100644 index 00000000..40191009 --- /dev/null +++ b/Timeline.Tests/Helpers/Authentication/AuthenticationExtensions.cs @@ -0,0 +1,47 @@ +using Microsoft.AspNetCore.Mvc.Testing; +using Newtonsoft.Json; +using System; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +using Timeline.Entities; +using Xunit; + +namespace Timeline.Tests.Helpers.Authentication +{ + public static class AuthenticationExtensions + { + private const string CreateTokenUrl = "/token/create"; + + public static async Task CreateUserTokenAsync(this HttpClient client, string username, string password, bool assertSuccess = true) + { + var response = await client.PostAsJsonAsync(CreateTokenUrl, new CreateTokenRequest { Username = username, Password = password }); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + var result = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); + if (assertSuccess) + Assert.True(result.Success); + + return result; + } + + public static async Task CreateClientWithUser(this WebApplicationFactory factory, string username, string password) where T : class + { + var client = factory.CreateDefaultClient(); + var token = (await client.CreateUserTokenAsync(username, password)).Token; + client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token); + return client; + } + + public static async Task SendWithAuthenticationAsync(this HttpClient client, string token, string path, Action requestBuilder = null) + { + var request = new HttpRequestMessage + { + RequestUri = new Uri(client.BaseAddress, path), + }; + request.Headers.Add("Authorization", "Bearer " + token); + requestBuilder?.Invoke(request); + return await client.SendAsync(request); + } + } +} diff --git a/Timeline.Tests/Helpers/Authentication/AuthenticationHttpClientExtensions.cs b/Timeline.Tests/Helpers/Authentication/AuthenticationHttpClientExtensions.cs deleted file mode 100644 index c0051c53..00000000 --- a/Timeline.Tests/Helpers/Authentication/AuthenticationHttpClientExtensions.cs +++ /dev/null @@ -1,38 +0,0 @@ -using Newtonsoft.Json; -using System; -using System.Net; -using System.Net.Http; -using System.Threading.Tasks; -using Timeline.Entities; -using Xunit; - -namespace Timeline.Tests.Helpers.Authentication -{ - public static class AuthenticationHttpClientExtensions - { - private const string CreateTokenUrl = "/User/CreateToken"; - - public static async Task CreateUserTokenAsync(this HttpClient client, string username, string password, bool assertSuccess = true) - { - var response = await client.PostAsJsonAsync(CreateTokenUrl, new CreateTokenRequest { Username = username, Password = password }); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - - var result = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); - if (assertSuccess) - Assert.True(result.Success); - - return result; - } - - public static async Task SendWithAuthenticationAsync(this HttpClient client, string token, string path, Action requestBuilder = null) - { - var request = new HttpRequestMessage - { - RequestUri = new Uri(client.BaseAddress, path), - }; - request.Headers.Add("Authorization", "Bearer " + token); - requestBuilder?.Invoke(request); - return await client.SendAsync(request); - } - } -} diff --git a/Timeline.Tests/Helpers/TestUsers.cs b/Timeline.Tests/Helpers/TestUsers.cs new file mode 100644 index 00000000..b7005d54 --- /dev/null +++ b/Timeline.Tests/Helpers/TestUsers.cs @@ -0,0 +1,40 @@ +using System.Collections.Generic; +using System.Linq; +using Timeline.Entities; +using Timeline.Models; +using Timeline.Services; + +namespace Timeline.Tests.Helpers +{ + public static class TestMockUsers + { + static TestMockUsers() + { + var mockUsers = new List(); + var passwordService = new PasswordService(null); + + mockUsers.Add(new User + { + Name = "user", + EncryptedPassword = passwordService.HashPassword("user"), + RoleString = "user" + }); + mockUsers.Add(new User + { + Name = "admin", + EncryptedPassword = passwordService.HashPassword("admin"), + RoleString = "user,admin" + }); + + MockUsers = mockUsers; + + var mockUserInfos = mockUsers.Select(u => new UserInfo(u)).ToList(); + mockUserInfos.Sort(UserInfo.Comparer); + MockUserInfos = mockUserInfos; + } + + public static List MockUsers { get; } + + public static IReadOnlyList MockUserInfos { get; } + } +} diff --git a/Timeline.Tests/Helpers/WebApplicationFactoryExtensions.cs b/Timeline.Tests/Helpers/WebApplicationFactoryExtensions.cs index 4a7f87fb..a34217f4 100644 --- a/Timeline.Tests/Helpers/WebApplicationFactoryExtensions.cs +++ b/Timeline.Tests/Helpers/WebApplicationFactoryExtensions.cs @@ -4,7 +4,6 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Timeline.Models; -using Timeline.Services; using Xunit.Abstractions; namespace Timeline.Tests.Helpers @@ -42,28 +41,10 @@ namespace Timeline.Tests.Helpers var scopedServices = scope.ServiceProvider; var db = scopedServices.GetRequiredService(); - var passwordService = new PasswordService(null); - // Ensure the database is created. db.Database.EnsureCreated(); - db.Users.AddRange(new User[] { - new User - { - Id = 0, - Name = "user", - EncryptedPassword = passwordService.HashPassword("user"), - RoleString = "user" - }, - new User - { - Id = 0, - Name = "admin", - EncryptedPassword = passwordService.HashPassword("admin"), - RoleString = "user,admin" - } - }); - + db.Users.AddRange(TestMockUsers.MockUsers); db.SaveChanges(); } }); diff --git a/Timeline.Tests/JwtTokenUnitTest.cs b/Timeline.Tests/JwtTokenUnitTest.cs index fa9c7628..39ffc928 100644 --- a/Timeline.Tests/JwtTokenUnitTest.cs +++ b/Timeline.Tests/JwtTokenUnitTest.cs @@ -12,8 +12,8 @@ namespace Timeline.Tests { public class JwtTokenUnitTest : IClassFixture> { - private const string CreateTokenUrl = "User/CreateToken"; - private const string VerifyTokenUrl = "User/VerifyToken"; + private const string CreateTokenUrl = "token/create"; + private const string VerifyTokenUrl = "token/verify"; private readonly WebApplicationFactory _factory; diff --git a/Timeline.Tests/Timeline.Tests.csproj b/Timeline.Tests/Timeline.Tests.csproj index 57e04fc0..820737cc 100644 --- a/Timeline.Tests/Timeline.Tests.csproj +++ b/Timeline.Tests/Timeline.Tests.csproj @@ -8,7 +8,7 @@ - + all diff --git a/Timeline.Tests/UserUnitTest.cs b/Timeline.Tests/UserUnitTest.cs new file mode 100644 index 00000000..7d8cc824 --- /dev/null +++ b/Timeline.Tests/UserUnitTest.cs @@ -0,0 +1,36 @@ +using Microsoft.AspNetCore.Mvc.Testing; +using Newtonsoft.Json; +using System.Linq; +using System.Net; +using System.Threading.Tasks; +using Timeline.Entities; +using Timeline.Tests.Helpers; +using Timeline.Tests.Helpers.Authentication; +using Xunit; +using Xunit.Abstractions; + +namespace Timeline.Tests +{ + public class UserUnitTest : IClassFixture> + { + private readonly WebApplicationFactory _factory; + + public UserUnitTest(WebApplicationFactory factory, ITestOutputHelper outputHelper) + { + _factory = factory.WithTestConfig(outputHelper); + } + + [Fact] + public async Task UserTest() + { + using (var client = await _factory.CreateClientWithUser("admin", "admin")) + { + var res1 = await client.GetAsync("users"); + Assert.Equal(HttpStatusCode.OK, res1.StatusCode); + var users = JsonConvert.DeserializeObject(await res1.Content.ReadAsStringAsync()).ToList(); + users.Sort(UserInfo.Comparer); + Assert.Equal(TestMockUsers.MockUserInfos, users, UserInfo.EqualityComparer); + } + } + } +} diff --git a/Timeline/Configs/DatabaseConfig.cs b/Timeline/Configs/DatabaseConfig.cs index 34e5e65f..05dc630e 100644 --- a/Timeline/Configs/DatabaseConfig.cs +++ b/Timeline/Configs/DatabaseConfig.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace Timeline.Configs +namespace Timeline.Configs { public class DatabaseConfig { diff --git a/Timeline/Controllers/AdminUserController.cs b/Timeline/Controllers/AdminUserController.cs deleted file mode 100644 index 7cc8c150..00000000 --- a/Timeline/Controllers/AdminUserController.cs +++ /dev/null @@ -1,83 +0,0 @@ -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; -using System; -using System.Threading.Tasks; -using Timeline.Entities; -using Timeline.Services; - -namespace Timeline.Controllers -{ - [Route("admin")] - [Authorize(Roles = "admin")] - public class AdminUserController : Controller - { - private readonly IUserService _userService; - - public AdminUserController(IUserService userService) - { - _userService = userService; - } - - [HttpGet("users")] - public async Task> List() - { - return Ok(await _userService.ListUsers()); - } - - [HttpGet("user/{username}")] - public async Task Get([FromRoute] string username) - { - var user = await _userService.GetUser(username); - if (user == null) - { - return NotFound(); - } - return Ok(user); - } - - [HttpPut("user/{username}")] - public async Task Put([FromBody] AdminUserEntityRequest request, [FromRoute] string username) - { - var result = await _userService.PutUser(username, request.Password, request.Roles); - switch (result) - { - case PutUserResult.Created: - return CreatedAtAction("Get", new { username }, AdminUserPutResponse.Created); - case PutUserResult.Modified: - return Ok(AdminUserPutResponse.Modified); - default: - throw new Exception("Unreachable code."); - } - } - - [HttpPatch("user/{username}")] - public async Task Patch([FromBody] AdminUserEntityRequest request, [FromRoute] string username) - { - var result = await _userService.PatchUser(username, request.Password, request.Roles); - switch (result) - { - case PatchUserResult.Success: - return Ok(); - case PatchUserResult.NotExists: - return NotFound(); - default: - throw new Exception("Unreachable code."); - } - } - - [HttpDelete("user/{username}")] - public async Task> Delete([FromRoute] string username) - { - var result = await _userService.DeleteUser(username); - switch (result) - { - case DeleteUserResult.Success: - return Ok(AdminUserDeleteResponse.Success); - case DeleteUserResult.NotExists: - return Ok(AdminUserDeleteResponse.NotExists); - default: - throw new Exception("Uncreachable code."); - } - } - } -} diff --git a/Timeline/Controllers/TokenController.cs b/Timeline/Controllers/TokenController.cs new file mode 100644 index 00000000..463fb83c --- /dev/null +++ b/Timeline/Controllers/TokenController.cs @@ -0,0 +1,74 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging; +using System.Threading.Tasks; +using Timeline.Entities; +using Timeline.Services; + +namespace Timeline.Controllers +{ + [Route("token")] + public class TokenController : Controller + { + private static class LoggingEventIds + { + public const int LogInSucceeded = 4000; + public const int LogInFailed = 4001; + } + + private readonly IUserService _userService; + private readonly ILogger _logger; + + public TokenController(IUserService userService, ILogger logger) + { + _userService = userService; + _logger = logger; + } + + [HttpPost("create")] + [AllowAnonymous] + public async Task> Create([FromBody] CreateTokenRequest request) + { + var result = await _userService.CreateToken(request.Username, request.Password); + + if (result == null) + { + _logger.LogInformation(LoggingEventIds.LogInFailed, "Attemp to login with username: {} and password: {} failed.", request.Username, request.Password); + return Ok(new CreateTokenResponse + { + Success = false + }); + } + + _logger.LogInformation(LoggingEventIds.LogInSucceeded, "Login with username: {} succeeded.", request.Username); + + return Ok(new CreateTokenResponse + { + Success = true, + Token = result.Token, + UserInfo = result.UserInfo + }); + } + + [HttpPost("verify")] + [AllowAnonymous] + public async Task> Verify([FromBody] VerifyTokenRequest request) + { + var result = await _userService.VerifyToken(request.Token); + + if (result == null) + { + return Ok(new VerifyTokenResponse + { + IsValid = false, + }); + } + + return Ok(new VerifyTokenResponse + { + IsValid = true, + UserInfo = result + }); + } + } +} diff --git a/Timeline/Controllers/UserController.cs b/Timeline/Controllers/UserController.cs index 285e0146..ab7e1b99 100644 --- a/Timeline/Controllers/UserController.cs +++ b/Timeline/Controllers/UserController.cs @@ -1,74 +1,81 @@ -using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Logging; +using System; using System.Threading.Tasks; using Timeline.Entities; using Timeline.Services; namespace Timeline.Controllers { - [Route("[controller]")] public class UserController : Controller { - private static class LoggingEventIds - { - public const int LogInSucceeded = 4000; - public const int LogInFailed = 4001; - } - private readonly IUserService _userService; - private readonly ILogger _logger; - public UserController(IUserService userService, ILogger logger) + public UserController(IUserService userService) { _userService = userService; - _logger = logger; } - [HttpPost("[action]")] - [AllowAnonymous] - public async Task> CreateToken([FromBody] CreateTokenRequest request) + [HttpGet("users"), Authorize(Roles = "admin")] + public async Task> List() { - var result = await _userService.CreateToken(request.Username, request.Password); + return Ok(await _userService.ListUsers()); + } - if (result == null) + [HttpGet("user/{username}"), Authorize] + public async Task Get([FromRoute] string username) + { + var user = await _userService.GetUser(username); + if (user == null) { - _logger.LogInformation(LoggingEventIds.LogInFailed, "Attemp to login with username: {} and password: {} failed.", request.Username, request.Password); - return Ok(new CreateTokenResponse - { - Success = false - }); + return NotFound(); } + return Ok(user); + } - _logger.LogInformation(LoggingEventIds.LogInSucceeded, "Login with username: {} succeeded.", request.Username); - - return Ok(new CreateTokenResponse + [HttpPut("user/{username}"), Authorize(Roles = "admin")] + public async Task Put([FromBody] UserModifyRequest request, [FromRoute] string username) + { + var result = await _userService.PutUser(username, request.Password, request.Roles); + switch (result) { - Success = true, - Token = result.Token, - UserInfo = result.UserInfo - }); + case PutUserResult.Created: + return CreatedAtAction("Get", new { username }, UserPutResponse.Created); + case PutUserResult.Modified: + return Ok(UserPutResponse.Modified); + default: + throw new Exception("Unreachable code."); + } } - [HttpPost("[action]")] - [AllowAnonymous] - public async Task> VerifyToken([FromBody] VerifyTokenRequest request) + [HttpPatch("user/{username}"), Authorize(Roles = "admin")] + public async Task Patch([FromBody] UserModifyRequest request, [FromRoute] string username) { - var result = await _userService.VerifyToken(request.Token); - - if (result == null) + var result = await _userService.PatchUser(username, request.Password, request.Roles); + switch (result) { - return Ok(new VerifyTokenResponse - { - IsValid = false, - }); + case PatchUserResult.Success: + return Ok(); + case PatchUserResult.NotExists: + return NotFound(); + default: + throw new Exception("Unreachable code."); } + } - return Ok(new VerifyTokenResponse + [HttpDelete("user/{username}"), Authorize(Roles = "admin")] + public async Task> Delete([FromRoute] string username) + { + var result = await _userService.DeleteUser(username); + switch (result) { - IsValid = true, - UserInfo = result - }); + case DeleteUserResult.Success: + return Ok(UserDeleteResponse.Success); + case DeleteUserResult.NotExists: + return Ok(UserDeleteResponse.NotExists); + default: + throw new Exception("Uncreachable code."); + } } } } diff --git a/Timeline/Entities/AdminUser.cs b/Timeline/Entities/AdminUser.cs index 7b8b7fb7..eb126165 100644 --- a/Timeline/Entities/AdminUser.cs +++ b/Timeline/Entities/AdminUser.cs @@ -1,29 +1,29 @@ namespace Timeline.Entities { - public class AdminUserEntityRequest + public class UserModifyRequest { public string Password { get; set; } public string[] Roles { get; set; } } - public class AdminUserPutResponse + public class UserPutResponse { public const int CreatedCode = 0; public const int ModifiedCode = 1; - public static AdminUserPutResponse Created { get; } = new AdminUserPutResponse { ReturnCode = CreatedCode }; - public static AdminUserPutResponse Modified { get; } = new AdminUserPutResponse { ReturnCode = ModifiedCode }; + public static UserPutResponse Created { get; } = new UserPutResponse { ReturnCode = CreatedCode }; + public static UserPutResponse Modified { get; } = new UserPutResponse { ReturnCode = ModifiedCode }; public int ReturnCode { get; set; } } - public class AdminUserDeleteResponse + public class UserDeleteResponse { public const int SuccessCode = 0; public const int NotExistsCode = 1; - public static AdminUserDeleteResponse Success { get; } = new AdminUserDeleteResponse { ReturnCode = SuccessCode }; - public static AdminUserDeleteResponse NotExists { get; } = new AdminUserDeleteResponse { ReturnCode = NotExistsCode }; + public static UserDeleteResponse Success { get; } = new UserDeleteResponse { ReturnCode = SuccessCode }; + public static UserDeleteResponse NotExists { get; } = new UserDeleteResponse { ReturnCode = NotExistsCode }; public int ReturnCode { get; set; } } diff --git a/Timeline/Entities/UserInfo.cs b/Timeline/Entities/UserInfo.cs index d9c5acad..a1860552 100644 --- a/Timeline/Entities/UserInfo.cs +++ b/Timeline/Entities/UserInfo.cs @@ -1,14 +1,20 @@ using System; +using System.Collections.Generic; using System.Linq; using Timeline.Models; namespace Timeline.Entities { - public class UserInfo + public sealed class UserInfo { public UserInfo() { + } + public UserInfo(string username, params string[] roles) + { + Username = username; + Roles = roles; } public UserInfo(User user) @@ -17,10 +23,64 @@ namespace Timeline.Entities throw new ArgumentNullException(nameof(user)); Username = user.Name; - Roles = user.RoleString.Split(',').Select(s => s.Trim()).ToArray(); + + if (user.RoleString == null) + Roles = null; + else + Roles = user.RoleString.Split(',').Select(r => r.Trim()).ToArray(); } public string Username { get; set; } public string[] Roles { get; set; } + + public static IEqualityComparer EqualityComparer { get; } = new EqualityComparerImpl(); + public static IComparer Comparer { get; } = Comparer.Create(Compare); + + private class EqualityComparerImpl : IEqualityComparer + { + bool IEqualityComparer.Equals(UserInfo x, UserInfo y) + { + return Compare(x, y) == 0; + } + + int IEqualityComparer.GetHashCode(UserInfo obj) + { + return obj.Username.GetHashCode() ^ NormalizeRoles(obj.Roles).GetHashCode(); + } + } + + private static string NormalizeRoles(string[] rawRoles) + { + var roles = rawRoles.Where(r => !string.IsNullOrWhiteSpace(r)).Select(r => r.Trim()).ToList(); + roles.Sort(); + return string.Join(',', roles); + } + + public static int Compare(UserInfo left, UserInfo right) + { + if (left == null) + { + if (right == null) + return 0; + return -1; + } + + if (right == null) + return 1; + + var uc = string.Compare(left.Username, right.Username); + if (uc != 0) + return uc; + + var leftRoles = NormalizeRoles(left.Roles); + var rightRoles = NormalizeRoles(right.Roles); + + return string.Compare(leftRoles, rightRoles); + } + + public override string ToString() + { + return $"Username: {Username} ; Roles: {Roles}"; + } } } diff --git a/nuget.config b/nuget.config index d4244526..194c0bbf 100644 --- a/nuget.config +++ b/nuget.config @@ -1,7 +1,6 @@ - + - -- cgit v1.2.3 From 0920d6ca8d8f92e612148aa1d3c4eaea5f407d94 Mon Sep 17 00:00:00 2001 From: crupest Date: Sun, 21 Apr 2019 23:23:49 +0800 Subject: Allow ordinary user to patch his password. --- Timeline/Controllers/UserController.cs | 39 ++++++++++++++++++++++++++-------- Timeline/Entities/AdminUser.cs | 30 -------------------------- Timeline/Entities/Common.cs | 12 +++++++++++ Timeline/Entities/Token.cs | 26 +++++++++++++++++++++++ Timeline/Entities/User.cs | 30 ++++++++++++++------------ Timeline/Services/JwtService.cs | 22 +++++++++++-------- Timeline/Services/UserService.cs | 21 +++++------------- 7 files changed, 103 insertions(+), 77 deletions(-) delete mode 100644 Timeline/Entities/AdminUser.cs create mode 100644 Timeline/Entities/Common.cs create mode 100644 Timeline/Entities/Token.cs (limited to 'Timeline/Controllers/UserController.cs') diff --git a/Timeline/Controllers/UserController.cs b/Timeline/Controllers/UserController.cs index ab7e1b99..d2708eeb 100644 --- a/Timeline/Controllers/UserController.cs +++ b/Timeline/Controllers/UserController.cs @@ -48,18 +48,39 @@ namespace Timeline.Controllers } } - [HttpPatch("user/{username}"), Authorize(Roles = "admin")] + [HttpPatch("user/{username}"), Authorize] public async Task Patch([FromBody] UserModifyRequest request, [FromRoute] string username) { - var result = await _userService.PatchUser(username, request.Password, request.Roles); - switch (result) + if (User.IsInRole("admin")) { - case PatchUserResult.Success: - return Ok(); - case PatchUserResult.NotExists: - return NotFound(); - default: - throw new Exception("Unreachable code."); + var result = await _userService.PatchUser(username, request.Password, request.Roles); + switch (result) + { + case PatchUserResult.Success: + return Ok(); + case PatchUserResult.NotExists: + return NotFound(); + default: + throw new Exception("Unreachable code."); + } + } + else + { + if (User.Identity.Name != username) + return StatusCode(403, new MessageResponse("Can't patch other user when you are not admin.")); + if (request.Roles != null) + return StatusCode(403, new MessageResponse("Can't patch roles when you are not admin.")); + + var result = await _userService.PatchUser(username, request.Password, null); + switch (result) + { + case PatchUserResult.Success: + return Ok(); + case PatchUserResult.NotExists: + return NotFound(new MessageResponse("This username no longer exists. Please update your token.")); + default: + throw new Exception("Unreachable code."); + } } } diff --git a/Timeline/Entities/AdminUser.cs b/Timeline/Entities/AdminUser.cs deleted file mode 100644 index eb126165..00000000 --- a/Timeline/Entities/AdminUser.cs +++ /dev/null @@ -1,30 +0,0 @@ -namespace Timeline.Entities -{ - public class UserModifyRequest - { - public string Password { get; set; } - public string[] Roles { get; set; } - } - - public class UserPutResponse - { - public const int CreatedCode = 0; - public const int ModifiedCode = 1; - - public static UserPutResponse Created { get; } = new UserPutResponse { ReturnCode = CreatedCode }; - public static UserPutResponse Modified { get; } = new UserPutResponse { ReturnCode = ModifiedCode }; - - public int ReturnCode { get; set; } - } - - public class UserDeleteResponse - { - public const int SuccessCode = 0; - public const int NotExistsCode = 1; - - public static UserDeleteResponse Success { get; } = new UserDeleteResponse { ReturnCode = SuccessCode }; - public static UserDeleteResponse NotExists { get; } = new UserDeleteResponse { ReturnCode = NotExistsCode }; - - public int ReturnCode { get; set; } - } -} diff --git a/Timeline/Entities/Common.cs b/Timeline/Entities/Common.cs new file mode 100644 index 00000000..235a2a20 --- /dev/null +++ b/Timeline/Entities/Common.cs @@ -0,0 +1,12 @@ +namespace Timeline.Entities +{ + public class MessageResponse + { + public MessageResponse(string message) + { + Message = message; + } + + public string Message { get; set; } + } +} diff --git a/Timeline/Entities/Token.cs b/Timeline/Entities/Token.cs new file mode 100644 index 00000000..1b5a469d --- /dev/null +++ b/Timeline/Entities/Token.cs @@ -0,0 +1,26 @@ +namespace Timeline.Entities +{ + public class CreateTokenRequest + { + public string Username { get; set; } + public string Password { get; set; } + } + + public class CreateTokenResponse + { + public bool Success { get; set; } + public string Token { get; set; } + public UserInfo UserInfo { get; set; } + } + + public class VerifyTokenRequest + { + public string Token { get; set; } + } + + public class VerifyTokenResponse + { + public bool IsValid { get; set; } + public UserInfo UserInfo { get; set; } + } +} diff --git a/Timeline/Entities/User.cs b/Timeline/Entities/User.cs index 1b5a469d..eb126165 100644 --- a/Timeline/Entities/User.cs +++ b/Timeline/Entities/User.cs @@ -1,26 +1,30 @@ namespace Timeline.Entities { - public class CreateTokenRequest + public class UserModifyRequest { - public string Username { get; set; } public string Password { get; set; } + public string[] Roles { get; set; } } - public class CreateTokenResponse + public class UserPutResponse { - public bool Success { get; set; } - public string Token { get; set; } - public UserInfo UserInfo { get; set; } - } + public const int CreatedCode = 0; + public const int ModifiedCode = 1; - public class VerifyTokenRequest - { - public string Token { get; set; } + public static UserPutResponse Created { get; } = new UserPutResponse { ReturnCode = CreatedCode }; + public static UserPutResponse Modified { get; } = new UserPutResponse { ReturnCode = ModifiedCode }; + + public int ReturnCode { get; set; } } - public class VerifyTokenResponse + public class UserDeleteResponse { - public bool IsValid { get; set; } - public UserInfo UserInfo { get; set; } + public const int SuccessCode = 0; + public const int NotExistsCode = 1; + + public static UserDeleteResponse Success { get; } = new UserDeleteResponse { ReturnCode = SuccessCode }; + public static UserDeleteResponse NotExists { get; } = new UserDeleteResponse { ReturnCode = NotExistsCode }; + + public int ReturnCode { get; set; } } } diff --git a/Timeline/Services/JwtService.cs b/Timeline/Services/JwtService.cs index 91e7f879..bf470354 100644 --- a/Timeline/Services/JwtService.cs +++ b/Timeline/Services/JwtService.cs @@ -7,25 +7,28 @@ using System.Linq; using System.Security.Claims; using System.Text; using Timeline.Configs; +using Timeline.Entities; namespace Timeline.Services { public interface IJwtService { /// - /// Create a JWT token for a given user id. + /// Create a JWT token for a given user info. /// - /// The user id used to generate token. + /// The user id contained in generate token. + /// The username contained in token. + /// The roles contained in token. /// Return the generated token. - string GenerateJwtToken(long userId, string[] roles); + string GenerateJwtToken(long userId, string username, string[] roles); /// /// Verify a JWT token. /// Return null is is null. /// /// The token string to verify. - /// Return null if is null or token is invalid. Return the saved user id otherwise. - long? VerifyJwtToken(string token); + /// Return null if is null or token is invalid. Return the saved user info otherwise. + UserInfo VerifyJwtToken(string token); } @@ -41,12 +44,13 @@ namespace Timeline.Services _logger = logger; } - public string GenerateJwtToken(long id, string[] roles) + public string GenerateJwtToken(long id, string username, string[] roles) { var jwtConfig = _jwtConfig.CurrentValue; var identity = new ClaimsIdentity(); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, id.ToString())); + identity.AddClaim(new Claim(identity.NameClaimType, username)); identity.AddClaims(roles.Select(role => new Claim(identity.RoleClaimType, role))); var tokenDescriptor = new SecurityTokenDescriptor() @@ -67,13 +71,12 @@ namespace Timeline.Services } - public long? VerifyJwtToken(string token) + public UserInfo VerifyJwtToken(string token) { if (token == null) return null; var config = _jwtConfig.CurrentValue; - try { var principal = _tokenHandler.ValidateToken(token, new TokenValidationParameters @@ -87,7 +90,8 @@ namespace Timeline.Services IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(config.SigningKey)) }, out SecurityToken validatedToken); - return long.Parse(principal.FindAll(ClaimTypes.NameIdentifier).Single().Value); + return new UserInfo(principal.Identity.Name, + principal.FindAll(ClaimTypes.Role).Select(c => c.Value).ToArray()); } catch (Exception e) { diff --git a/Timeline/Services/UserService.cs b/Timeline/Services/UserService.cs index 34eeb1ad..a0d358dd 100644 --- a/Timeline/Services/UserService.cs +++ b/Timeline/Services/UserService.cs @@ -101,7 +101,7 @@ namespace Timeline.Services /// New roles. If not modify, then null. /// Return if modification succeeds. /// Return if the user of given username doesn't exist. - Task PatchUser(string username, string password, string[] roles); + Task PatchUser(string username, string password, string[] roles); /// /// Delete a user of given username. @@ -148,7 +148,7 @@ namespace Timeline.Services return new CreateTokenResult { - Token = _jwtService.GenerateJwtToken(user.Id, userInfo.Roles), + Token = _jwtService.GenerateJwtToken(user.Id, userInfo.Username, userInfo.Roles), UserInfo = userInfo }; } @@ -161,26 +161,15 @@ namespace Timeline.Services public async Task VerifyToken(string token) { - var userId = _jwtService.VerifyJwtToken(token); + var userInfo = _jwtService.VerifyJwtToken(token); - if (userId == null) + if (userInfo == null) { _logger.LogInformation($"Verify token falied. Reason: invalid token. Token: {token} ."); return null; } - var user = await _databaseContext.Users - .Where(u => u.Id == userId.Value) - .Select(u => UserInfo.Create(u.Name, u.RoleString)) - .SingleOrDefaultAsync(); - - if (user == null) - { - _logger.LogInformation($"Verify token falied. Reason: invalid user id. UserId: {userId} Token: {token} ."); - return null; - } - - return user; + return await Task.FromResult(userInfo); } public async Task GetUser(string username) -- cgit v1.2.3 From a2d8695d1e46d271bab40ea192afffee65f7538f Mon Sep 17 00:00:00 2001 From: crupest Date: Mon, 22 Apr 2019 14:45:52 +0800 Subject: Move http models in to a new namespace. Revert last commit. --- .../Authentication/AuthenticationExtensions.cs | 2 +- Timeline.Tests/JwtTokenUnitTest.cs | 2 +- Timeline/Controllers/TokenController.cs | 2 +- Timeline/Controllers/UserController.cs | 46 ++++++---------------- Timeline/Entities/Common.cs | 12 ------ Timeline/Entities/Http/Common.cs | 29 ++++++++++++++ Timeline/Entities/Http/Token.cs | 26 ++++++++++++ Timeline/Entities/Http/User.cs | 26 ++++++++++++ Timeline/Entities/Token.cs | 26 ------------ Timeline/Entities/User.cs | 30 -------------- Timeline/Services/UserService.cs | 10 ++--- 11 files changed, 102 insertions(+), 109 deletions(-) delete mode 100644 Timeline/Entities/Common.cs create mode 100644 Timeline/Entities/Http/Common.cs create mode 100644 Timeline/Entities/Http/Token.cs create mode 100644 Timeline/Entities/Http/User.cs delete mode 100644 Timeline/Entities/Token.cs delete mode 100644 Timeline/Entities/User.cs (limited to 'Timeline/Controllers/UserController.cs') diff --git a/Timeline.Tests/Helpers/Authentication/AuthenticationExtensions.cs b/Timeline.Tests/Helpers/Authentication/AuthenticationExtensions.cs index 40191009..cda9fe99 100644 --- a/Timeline.Tests/Helpers/Authentication/AuthenticationExtensions.cs +++ b/Timeline.Tests/Helpers/Authentication/AuthenticationExtensions.cs @@ -4,7 +4,7 @@ using System; using System.Net; using System.Net.Http; using System.Threading.Tasks; -using Timeline.Entities; +using Timeline.Entities.Http; using Xunit; namespace Timeline.Tests.Helpers.Authentication diff --git a/Timeline.Tests/JwtTokenUnitTest.cs b/Timeline.Tests/JwtTokenUnitTest.cs index 39ffc928..8a503bd7 100644 --- a/Timeline.Tests/JwtTokenUnitTest.cs +++ b/Timeline.Tests/JwtTokenUnitTest.cs @@ -2,7 +2,7 @@ using Newtonsoft.Json; using System.Net; using System.Net.Http; -using Timeline.Entities; +using Timeline.Entities.Http; using Timeline.Tests.Helpers; using Timeline.Tests.Helpers.Authentication; using Xunit; diff --git a/Timeline/Controllers/TokenController.cs b/Timeline/Controllers/TokenController.cs index 463fb83c..0be5fb2f 100644 --- a/Timeline/Controllers/TokenController.cs +++ b/Timeline/Controllers/TokenController.cs @@ -2,7 +2,7 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System.Threading.Tasks; -using Timeline.Entities; +using Timeline.Entities.Http; using Timeline.Services; namespace Timeline.Controllers diff --git a/Timeline/Controllers/UserController.cs b/Timeline/Controllers/UserController.cs index d2708eeb..59c7a48c 100644 --- a/Timeline/Controllers/UserController.cs +++ b/Timeline/Controllers/UserController.cs @@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Mvc; using System; using System.Threading.Tasks; using Timeline.Entities; +using Timeline.Entities.Http; using Timeline.Services; namespace Timeline.Controllers @@ -48,50 +49,29 @@ namespace Timeline.Controllers } } - [HttpPatch("user/{username}"), Authorize] + [HttpPatch("user/{username}"), Authorize(Roles = "admin")] public async Task Patch([FromBody] UserModifyRequest request, [FromRoute] string username) { - if (User.IsInRole("admin")) - { - var result = await _userService.PatchUser(username, request.Password, request.Roles); - switch (result) - { - case PatchUserResult.Success: - return Ok(); - case PatchUserResult.NotExists: - return NotFound(); - default: - throw new Exception("Unreachable code."); - } - } - else + var result = await _userService.PatchUser(username, request.Password, request.Roles); + switch (result) { - if (User.Identity.Name != username) - return StatusCode(403, new MessageResponse("Can't patch other user when you are not admin.")); - if (request.Roles != null) - return StatusCode(403, new MessageResponse("Can't patch roles when you are not admin.")); - - var result = await _userService.PatchUser(username, request.Password, null); - switch (result) - { - case PatchUserResult.Success: - return Ok(); - case PatchUserResult.NotExists: - return NotFound(new MessageResponse("This username no longer exists. Please update your token.")); - default: - throw new Exception("Unreachable code."); - } + case PatchUserResult.Success: + return Ok(); + case PatchUserResult.NotExists: + return NotFound(); + default: + throw new Exception("Unreachable code."); } } [HttpDelete("user/{username}"), Authorize(Roles = "admin")] - public async Task> Delete([FromRoute] string username) + public async Task Delete([FromRoute] string username) { var result = await _userService.DeleteUser(username); switch (result) { - case DeleteUserResult.Success: - return Ok(UserDeleteResponse.Success); + case DeleteUserResult.Deleted: + return Ok(UserDeleteResponse.Deleted); case DeleteUserResult.NotExists: return Ok(UserDeleteResponse.NotExists); default: diff --git a/Timeline/Entities/Common.cs b/Timeline/Entities/Common.cs deleted file mode 100644 index 235a2a20..00000000 --- a/Timeline/Entities/Common.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace Timeline.Entities -{ - public class MessageResponse - { - public MessageResponse(string message) - { - Message = message; - } - - public string Message { get; set; } - } -} diff --git a/Timeline/Entities/Http/Common.cs b/Timeline/Entities/Http/Common.cs new file mode 100644 index 00000000..9575e6fa --- /dev/null +++ b/Timeline/Entities/Http/Common.cs @@ -0,0 +1,29 @@ +namespace Timeline.Entities.Http +{ + public class ReturnCodeMessageResponse + { + public ReturnCodeMessageResponse() + { + + } + + public ReturnCodeMessageResponse(int code) + { + ReturnCode = code; + } + + public ReturnCodeMessageResponse(string message) + { + Message = message; + } + + public ReturnCodeMessageResponse(int code, string message) + { + ReturnCode = code; + Message = message; + } + + public int? ReturnCode { get; set; } = null; + public string Message { get; set; } = null; + } +} diff --git a/Timeline/Entities/Http/Token.cs b/Timeline/Entities/Http/Token.cs new file mode 100644 index 00000000..45ee0fc5 --- /dev/null +++ b/Timeline/Entities/Http/Token.cs @@ -0,0 +1,26 @@ +namespace Timeline.Entities.Http +{ + public class CreateTokenRequest + { + public string Username { get; set; } + public string Password { get; set; } + } + + public class CreateTokenResponse + { + public bool Success { get; set; } + public string Token { get; set; } + public UserInfo UserInfo { get; set; } + } + + public class VerifyTokenRequest + { + public string Token { get; set; } + } + + public class VerifyTokenResponse + { + public bool IsValid { get; set; } + public UserInfo UserInfo { get; set; } + } +} diff --git a/Timeline/Entities/Http/User.cs b/Timeline/Entities/Http/User.cs new file mode 100644 index 00000000..24952ac7 --- /dev/null +++ b/Timeline/Entities/Http/User.cs @@ -0,0 +1,26 @@ +namespace Timeline.Entities.Http +{ + public class UserModifyRequest + { + public string Password { get; set; } + public string[] Roles { get; set; } + } + + public static class UserPutResponse + { + public const int CreatedCode = 0; + public const int ModifiedCode = 1; + + public static ReturnCodeMessageResponse Created { get; } = new ReturnCodeMessageResponse(CreatedCode, "A new user is created."); + public static ReturnCodeMessageResponse Modified { get; } = new ReturnCodeMessageResponse(ModifiedCode, "A existing user is modified."); + } + + public static class UserDeleteResponse + { + public const int DeletedCode = 0; + public const int NotExistsCode = 1; + + public static ReturnCodeMessageResponse Deleted { get; } = new ReturnCodeMessageResponse(DeletedCode, "A existing user is deleted."); + public static ReturnCodeMessageResponse NotExists { get; } = new ReturnCodeMessageResponse(NotExistsCode, "User with given name does not exists."); + } +} diff --git a/Timeline/Entities/Token.cs b/Timeline/Entities/Token.cs deleted file mode 100644 index 1b5a469d..00000000 --- a/Timeline/Entities/Token.cs +++ /dev/null @@ -1,26 +0,0 @@ -namespace Timeline.Entities -{ - public class CreateTokenRequest - { - public string Username { get; set; } - public string Password { get; set; } - } - - public class CreateTokenResponse - { - public bool Success { get; set; } - public string Token { get; set; } - public UserInfo UserInfo { get; set; } - } - - public class VerifyTokenRequest - { - public string Token { get; set; } - } - - public class VerifyTokenResponse - { - public bool IsValid { get; set; } - public UserInfo UserInfo { get; set; } - } -} diff --git a/Timeline/Entities/User.cs b/Timeline/Entities/User.cs deleted file mode 100644 index eb126165..00000000 --- a/Timeline/Entities/User.cs +++ /dev/null @@ -1,30 +0,0 @@ -namespace Timeline.Entities -{ - public class UserModifyRequest - { - public string Password { get; set; } - public string[] Roles { get; set; } - } - - public class UserPutResponse - { - public const int CreatedCode = 0; - public const int ModifiedCode = 1; - - public static UserPutResponse Created { get; } = new UserPutResponse { ReturnCode = CreatedCode }; - public static UserPutResponse Modified { get; } = new UserPutResponse { ReturnCode = ModifiedCode }; - - public int ReturnCode { get; set; } - } - - public class UserDeleteResponse - { - public const int SuccessCode = 0; - public const int NotExistsCode = 1; - - public static UserDeleteResponse Success { get; } = new UserDeleteResponse { ReturnCode = SuccessCode }; - public static UserDeleteResponse NotExists { get; } = new UserDeleteResponse { ReturnCode = NotExistsCode }; - - public int ReturnCode { get; set; } - } -} diff --git a/Timeline/Services/UserService.cs b/Timeline/Services/UserService.cs index a0d358dd..8615d0c5 100644 --- a/Timeline/Services/UserService.cs +++ b/Timeline/Services/UserService.cs @@ -40,9 +40,9 @@ namespace Timeline.Services public enum DeleteUserResult { /// - /// Succeed to delete user. + /// A existing user is deleted. /// - Success, + Deleted, /// /// A user of given username does not exist. /// @@ -105,12 +105,12 @@ namespace Timeline.Services /// /// Delete a user of given username. - /// Return if success to delete. + /// Return if the user is deleted. /// Return if the user of given username /// does not exist. /// /// Username of thet user to delete. - /// if success to delete. + /// if the user is deleted. /// if the user doesn't exist. Task DeleteUser(string username); } @@ -250,7 +250,7 @@ namespace Timeline.Services _databaseContext.Users.Remove(user); await _databaseContext.SaveChangesAsync(); - return DeleteUserResult.Success; + return DeleteUserResult.Deleted; } } } -- cgit v1.2.3 From 58edbb6661c8f7d147f438716b286aa84c6bcb14 Mon Sep 17 00:00:00 2001 From: crupest Date: Mon, 22 Apr 2019 15:47:52 +0800 Subject: Add change password api. --- Timeline/Controllers/UserController.cs | 17 ++++++++++++++ Timeline/Entities/Http/User.cs | 17 ++++++++++++++ Timeline/Services/UserService.cs | 42 ++++++++++++++++++++++++++++++++++ 3 files changed, 76 insertions(+) (limited to 'Timeline/Controllers/UserController.cs') diff --git a/Timeline/Controllers/UserController.cs b/Timeline/Controllers/UserController.cs index 59c7a48c..552bfb2f 100644 --- a/Timeline/Controllers/UserController.cs +++ b/Timeline/Controllers/UserController.cs @@ -78,5 +78,22 @@ namespace Timeline.Controllers throw new Exception("Uncreachable code."); } } + + [HttpPost("userop/changepassword"), Authorize] + public async Task ChangePassword([FromBody] ChangePasswordRequest request) + { + var result = await _userService.ChangePassword(User.Identity.Name, request.OldPassword, request.NewPassword); + switch (result) + { + case ChangePasswordResult.Success: + return Ok(ChangePasswordResponse.Success); + case ChangePasswordResult.BadOldPassword: + return Ok(ChangePasswordResponse.BadOldPassword); + case ChangePasswordResult.NotExists: + return Ok(ChangePasswordResponse.NotExists); + default: + throw new Exception("Uncreachable code."); + } + } } } diff --git a/Timeline/Entities/Http/User.cs b/Timeline/Entities/Http/User.cs index 24952ac7..d42ca088 100644 --- a/Timeline/Entities/Http/User.cs +++ b/Timeline/Entities/Http/User.cs @@ -23,4 +23,21 @@ public static ReturnCodeMessageResponse Deleted { get; } = new ReturnCodeMessageResponse(DeletedCode, "A existing user is deleted."); public static ReturnCodeMessageResponse NotExists { get; } = new ReturnCodeMessageResponse(NotExistsCode, "User with given name does not exists."); } + + public class ChangePasswordRequest + { + public string OldPassword { get; set; } + public string NewPassword { get; set; } + } + + public static class ChangePasswordResponse + { + public const int SuccessCode = 0; + public const int BadOldPasswordCode = 1; + public const int NotExistsCode = 2; + + public static ReturnCodeMessageResponse Success { get; } = new ReturnCodeMessageResponse(SuccessCode, "Success to change password."); + public static ReturnCodeMessageResponse BadOldPassword { get; } = new ReturnCodeMessageResponse(BadOldPasswordCode, "Old password is wrong."); + public static ReturnCodeMessageResponse NotExists { get; } = new ReturnCodeMessageResponse(NotExistsCode, "Username does not exists, please update token."); + } } diff --git a/Timeline/Services/UserService.cs b/Timeline/Services/UserService.cs index 8615d0c5..75ad3331 100644 --- a/Timeline/Services/UserService.cs +++ b/Timeline/Services/UserService.cs @@ -49,6 +49,22 @@ namespace Timeline.Services NotExists } + public enum ChangePasswordResult + { + /// + /// Success to change password. + /// + Success, + /// + /// The user does not exists. + /// + NotExists, + /// + /// Old password is wrong. + /// + BadOldPassword + } + public interface IUserService { /// @@ -113,6 +129,17 @@ namespace Timeline.Services /// if the user is deleted. /// if the user doesn't exist. Task DeleteUser(string username); + + /// + /// Try to change a user's password with old password. + /// + /// The name of user to change password of. + /// The user's old password. + /// The user's new password. + /// if success. + /// if user does not exist. + /// if old password is wrong. + Task ChangePassword(string username, string oldPassword, string newPassword); } public class UserService : IUserService @@ -252,5 +279,20 @@ namespace Timeline.Services await _databaseContext.SaveChangesAsync(); return DeleteUserResult.Deleted; } + + public async Task 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(); + return ChangePasswordResult.Success; + } } } -- cgit v1.2.3 From c288638f3805ef3d8028c75cb248f641a91c835d Mon Sep 17 00:00:00 2001 From: crupest Date: Mon, 22 Apr 2019 17:15:06 +0800 Subject: Fix a bug in cos service. Add avatar api. --- Timeline/Controllers/UserController.cs | 8 ++++++++ Timeline/Services/TencentCloudCosService.cs | 5 +++++ Timeline/Services/UserService.cs | 15 ++++++++++++++- 3 files changed, 27 insertions(+), 1 deletion(-) (limited to 'Timeline/Controllers/UserController.cs') diff --git a/Timeline/Controllers/UserController.cs b/Timeline/Controllers/UserController.cs index 552bfb2f..1231befb 100644 --- a/Timeline/Controllers/UserController.cs +++ b/Timeline/Controllers/UserController.cs @@ -79,6 +79,14 @@ namespace Timeline.Controllers } } + [HttpGet("user/{username}/avatar"), Authorize] + public async Task GetAvatar([FromRoute] string username) + { + // TODO: test user existence. + var url = await _userService.GetAvatarUrl(username); + return Redirect(url); + } + [HttpPost("userop/changepassword"), Authorize] public async Task ChangePassword([FromBody] ChangePasswordRequest request) { diff --git a/Timeline/Services/TencentCloudCosService.cs b/Timeline/Services/TencentCloudCosService.cs index f1f52ec5..bc812e57 100644 --- a/Timeline/Services/TencentCloudCosService.cs +++ b/Timeline/Services/TencentCloudCosService.cs @@ -66,6 +66,11 @@ namespace Timeline.Services } if (serverException != null) { + if (serverException.statusCode == 404) + { + t.SetResult(false); + return; + } _logger.LogError(serverException, "An server error occured when test cos object existence. Bucket : {} . Key : {} .", bucket, key); t.SetException(serverException); return; diff --git a/Timeline/Services/UserService.cs b/Timeline/Services/UserService.cs index 75ad3331..a444d434 100644 --- a/Timeline/Services/UserService.cs +++ b/Timeline/Services/UserService.cs @@ -140,6 +140,8 @@ namespace Timeline.Services /// if user does not exist. /// if old password is wrong. Task ChangePassword(string username, string oldPassword, string newPassword); + + Task GetAvatarUrl(string username); } public class UserService : IUserService @@ -148,13 +150,15 @@ namespace Timeline.Services private readonly DatabaseContext _databaseContext; private readonly IJwtService _jwtService; private readonly IPasswordService _passwordService; + private readonly ITencentCloudCosService _cosService; - public UserService(ILogger logger, DatabaseContext databaseContext, IJwtService jwtService, IPasswordService passwordService) + public UserService(ILogger logger, DatabaseContext databaseContext, IJwtService jwtService, IPasswordService passwordService, ITencentCloudCosService cosService) { _logger = logger; _databaseContext = databaseContext; _jwtService = jwtService; _passwordService = passwordService; + _cosService = cosService; } public async Task CreateToken(string username, string password) @@ -294,5 +298,14 @@ namespace Timeline.Services await _databaseContext.SaveChangesAsync(); return ChangePasswordResult.Success; } + + public async Task GetAvatarUrl(string username) + { + var exists = await _cosService.Exists("avatar", username); + if (exists) + return _cosService.GetObjectUrl("avatar", username); + else + return _cosService.GetObjectUrl("avatar", "__default"); + } } } -- cgit v1.2.3 From 79f5053b3a2140a2633b2b0a88fb95d5594267ec Mon Sep 17 00:00:00 2001 From: crupest Date: Fri, 26 Apr 2019 14:04:24 +0800 Subject: Test user existence in get avatar. --- Timeline/Controllers/UserController.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'Timeline/Controllers/UserController.cs') diff --git a/Timeline/Controllers/UserController.cs b/Timeline/Controllers/UserController.cs index 1231befb..eaa205de 100644 --- a/Timeline/Controllers/UserController.cs +++ b/Timeline/Controllers/UserController.cs @@ -82,7 +82,10 @@ namespace Timeline.Controllers [HttpGet("user/{username}/avatar"), Authorize] public async Task GetAvatar([FromRoute] string username) { - // TODO: test user existence. + var existence = (await _userService.GetUser(username)) != null; + if (!existence) + return NotFound(); + var url = await _userService.GetAvatarUrl(username); return Redirect(url); } -- cgit v1.2.3 From 2c9ee904731d3c931607ba99f1bab21fcb1e1bb4 Mon Sep 17 00:00:00 2001 From: crupest Date: Tue, 30 Apr 2019 19:49:27 +0800 Subject: Add avatar upload function. --- Timeline/Controllers/UserController.cs | 34 ++++++++++++++-- Timeline/Entities/Http/User.cs | 11 ++++++ Timeline/Services/QCloudCosService.cs | 71 ++++++++++++++++++++++++++++++++++ Timeline/Services/UserService.cs | 42 ++++++++++++++++++++ 4 files changed, 154 insertions(+), 4 deletions(-) (limited to 'Timeline/Controllers/UserController.cs') diff --git a/Timeline/Controllers/UserController.cs b/Timeline/Controllers/UserController.cs index eaa205de..a18e36e9 100644 --- a/Timeline/Controllers/UserController.cs +++ b/Timeline/Controllers/UserController.cs @@ -1,6 +1,8 @@ using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; +using System.IO; using System.Threading.Tasks; using Timeline.Entities; using Timeline.Entities.Http; @@ -82,14 +84,38 @@ namespace Timeline.Controllers [HttpGet("user/{username}/avatar"), Authorize] public async Task GetAvatar([FromRoute] string username) { - var existence = (await _userService.GetUser(username)) != null; - if (!existence) - return NotFound(); - var url = await _userService.GetAvatarUrl(username); + if (url == null) + return NotFound(); return Redirect(url); } + [HttpPut("user/{username}/avatar"), Authorize] + [Consumes("image/png", "image/gif", "image/jpeg", "image/svg+xml")] + public async Task PutAvatar([FromRoute] string username, [FromHeader(Name="Content-Type")] string contentType) + { + bool isAdmin = User.IsInRole("admin"); + if (!isAdmin) + { + if (username != User.Identity.Name) + return StatusCode(StatusCodes.Status403Forbidden, PutAvatarResponse.Forbidden); + } + + var stream = new MemoryStream(); + await Request.Body.CopyToAsync(stream); + var result = await _userService.PutAvatar(username, stream.ToArray(), contentType); + switch (result) + { + case PutAvatarResult.Success: + return Ok(PutAvatarResponse.Success); + case PutAvatarResult.UserNotExists: + return BadRequest(PutAvatarResponse.NotExists); + default: + throw new Exception("Unknown put avatar result."); + } + } + + [HttpPost("userop/changepassword"), Authorize] public async Task ChangePassword([FromBody] ChangePasswordRequest request) { diff --git a/Timeline/Entities/Http/User.cs b/Timeline/Entities/Http/User.cs index d42ca088..31cafaa3 100644 --- a/Timeline/Entities/Http/User.cs +++ b/Timeline/Entities/Http/User.cs @@ -40,4 +40,15 @@ public static ReturnCodeMessageResponse BadOldPassword { get; } = new ReturnCodeMessageResponse(BadOldPasswordCode, "Old password is wrong."); public static ReturnCodeMessageResponse NotExists { get; } = new ReturnCodeMessageResponse(NotExistsCode, "Username does not exists, please update token."); } + + public static class PutAvatarResponse + { + public const int SuccessCode = 0; + public const int ForbiddenCode = 1; + public const int NotExistsCode = 2; + + public static ReturnCodeMessageResponse Success {get;} = new ReturnCodeMessageResponse(SuccessCode, "Success to upload avatar."); + public static ReturnCodeMessageResponse Forbidden {get;} = new ReturnCodeMessageResponse(ForbiddenCode, "You are not allowed to upload the user's avatar."); + public static ReturnCodeMessageResponse NotExists {get;} = new ReturnCodeMessageResponse(NotExistsCode, "The username does not exists. If you are a user, try update your token."); + } } diff --git a/Timeline/Services/QCloudCosService.cs b/Timeline/Services/QCloudCosService.cs index f4358714..078dd37b 100644 --- a/Timeline/Services/QCloudCosService.cs +++ b/Timeline/Services/QCloudCosService.cs @@ -6,6 +6,7 @@ using System.Diagnostics; using System.Linq; using System.Net; using System.Net.Http; +using System.Net.Http.Headers; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; @@ -24,6 +25,14 @@ namespace Timeline.Services /// True if exists. False if not. Task IsObjectExists(string bucket, string key); + /// + /// Upload an object use put method. + /// + /// The bucket name. + /// The object key. + /// The data to upload. + Task PutObject(string bucket, string key, byte[] data, string contentType); + /// /// Generate a presignated url to access the object. /// @@ -229,6 +238,68 @@ namespace Timeline.Services } } + public async Task PutObject(string bucket, string key, byte[] data, string contentType) + { + if (bucket == null) + throw new ArgumentNullException(nameof(bucket)); + if (key == null) + throw new ArgumentNullException(nameof(key)); + if (!ValidateBucketName(bucket)) + throw new ArgumentException($"Bucket name is not valid. Param is {bucket} .", nameof(bucket)); + if (data == null) + throw new ArgumentNullException(nameof(data)); + + var host = GetHost(bucket); + var encodedKey = WebUtility.UrlEncode(key); + var md5 = Convert.ToBase64String(MD5.Create().ComputeHash(data)); + + const string kContentMD5HeaderName = "Content-MD5"; + const string kContentTypeHeaderName = "Content-Type"; + + var httpRequest = new HttpRequestMessage() + { + Method = HttpMethod.Put, + RequestUri = new Uri($"https://{host}/{encodedKey}") + }; + httpRequest.Headers.Host = host; + httpRequest.Headers.Date = DateTimeOffset.Now; + var httpContent = new ByteArrayContent(data); + httpContent.Headers.Add(kContentMD5HeaderName, md5); + httpRequest.Content = httpContent; + + var signedHeaders = new Dictionary + { + ["Host"] = host, + [kContentMD5HeaderName] = md5 + }; + + if (contentType != null) + { + httpContent.Headers.Add(kContentTypeHeaderName, contentType); + signedHeaders.Add(kContentTypeHeaderName, contentType); + } + + httpRequest.Headers.TryAddWithoutValidation("Authorization", GenerateSign(GetCredentials(), new RequestInfo + { + Method = "put", + Uri = "/" + encodedKey, + Headers = signedHeaders + }, new TimeDuration(DateTimeOffset.Now, DateTimeOffset.Now.AddMinutes(10)))); + + var client = _httpClientFactory.CreateClient(); + + try + { + var response = await client.SendAsync(httpRequest); + if (!response.IsSuccessStatusCode) + throw new Exception($"Not success status code. {response.ToString()}"); + } + catch (Exception e) + { + _logger.LogError(e, "An error occured when test a cos object existence."); + } + } + public string GenerateObjectGetUrl(string bucket, string key) { if (bucket == null) diff --git a/Timeline/Services/UserService.cs b/Timeline/Services/UserService.cs index 4a47ca0f..9ebf2668 100644 --- a/Timeline/Services/UserService.cs +++ b/Timeline/Services/UserService.cs @@ -1,5 +1,6 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; +using System; using System.Linq; using System.Threading.Tasks; using Timeline.Entities; @@ -65,6 +66,18 @@ namespace Timeline.Services BadOldPassword } + public enum PutAvatarResult + { + /// + /// Success to upload avatar. + /// + Success, + /// + /// The user does not exists. + /// + UserNotExists + } + public interface IUserService { /// @@ -141,7 +154,14 @@ namespace Timeline.Services /// if old password is wrong. Task ChangePassword(string username, string oldPassword, string newPassword); + /// + /// Get the true avatar url of a user. + /// + /// The name of user. + /// The url if user exists. Null if user does not exist. Task GetAvatarUrl(string username); + + Task PutAvatar(string username, byte[] data, string mimeType); } public class UserService : IUserService @@ -301,11 +321,33 @@ namespace Timeline.Services public async Task 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 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; + } } } -- cgit v1.2.3