From e4c4a284571d51dcda373a0a1c047e634b17882d Mon Sep 17 00:00:00 2001 From: crupest Date: Thu, 12 Nov 2020 21:38:43 +0800 Subject: ... --- BackEnd/Timeline/Services/UserService.cs | 230 +++++++++---------------------- 1 file changed, 64 insertions(+), 166 deletions(-) (limited to 'BackEnd/Timeline/Services/UserService.cs') diff --git a/BackEnd/Timeline/Services/UserService.cs b/BackEnd/Timeline/Services/UserService.cs index 821bc33d..ed637ba3 100644 --- a/BackEnd/Timeline/Services/UserService.cs +++ b/BackEnd/Timeline/Services/UserService.cs @@ -1,6 +1,7 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading.Tasks; @@ -13,6 +14,11 @@ using static Timeline.Resources.Services.UserService; namespace Timeline.Services { + /// + /// Null means not change. + /// + public record ModifyUserParams(string? Username, string? Password, string? Nickname); + public interface IUserService { /// @@ -33,17 +39,7 @@ namespace Timeline.Services /// The id of the user. /// The user info. /// Thrown when the user with given id does not exist. - Task GetUserById(long id); - - /// - /// Get the user info of given username. - /// - /// Username of the user. - /// The info of the user. - /// Thrown when is null. - /// Thrown when is of bad format. - /// Thrown when the user with given username does not exist. - Task GetUserByUsername(string username); + Task GetUser(long id); /// /// Get the user id of given username. @@ -59,71 +55,31 @@ namespace Timeline.Services /// List all users. /// /// The user info of users. - Task GetUsers(); + Task> GetUsers(); /// /// Create a user with given info. /// - /// The info of new user. + /// The username of new user. + /// The password of new user. /// The the new user. - /// Thrown when is null. - /// Thrown when some fields in is bad. + /// Thrown when or is null. + /// Thrown when or is of bad format. /// Thrown when a user with given username already exists. - /// - /// must not be null and must be a valid username. - /// must not be null or empty. - /// is false by default (null). - /// must be a valid nickname if set. It is empty by default. - /// Other fields are ignored. - /// - Task CreateUser(User info); + Task CreateUser(string username, string password); /// - /// Modify a user's info. + /// Modify a user. /// /// The id of the user. - /// The new info. May be null. + /// The new information. /// The new user info. /// Thrown when some fields in is bad. /// Thrown when user with given id does not exist. /// - /// Only , , and will be used. - /// If null, then not change. - /// Other fields are ignored. /// Version will increase if password is changed. - /// - /// must be a valid username if set. - /// can't be empty if set. - /// must be a valid nickname if set. - /// - /// - /// - Task ModifyUser(long id, User? info); - - /// - /// Modify a user's info. - /// - /// The username of the user. - /// The new info. May be null. - /// The new user info. - /// Thrown when is null. - /// Thrown when is of bad format or some fields in is bad. - /// Thrown when user with given id does not exist. - /// Thrown when user with the newusername already exist. - /// - /// Only , and will be used. - /// If null, then not change. - /// Other fields are ignored. - /// After modified, even if nothing is changed, version will increase. - /// - /// must be a valid username if set. - /// can't be empty if set. - /// must be a valid nickname if set. - /// - /// Note: Whether is set or not, version will increase and not set to the specified value if there is one. /// - /// - Task ModifyUser(string username, User? info); + Task ModifyUser(long id, ModifyUserParams? param); /// /// Try to change a user's password with old password. @@ -146,15 +102,18 @@ namespace Timeline.Services private readonly DatabaseContext _databaseContext; private readonly IPasswordService _passwordService; + private readonly IUserPermissionService _userPermissionService; private readonly UsernameValidator _usernameValidator = new UsernameValidator(); private readonly NicknameValidator _nicknameValidator = new NicknameValidator(); - public UserService(ILogger logger, DatabaseContext databaseContext, IPasswordService passwordService, IClock clock) + + public UserService(ILogger logger, DatabaseContext databaseContext, IPasswordService passwordService, IClock clock, IUserPermissionService userPermissionService) { _logger = logger; _clock = clock; _databaseContext = databaseContext; _passwordService = passwordService; + _userPermissionService = userPermissionService; } private void CheckUsernameFormat(string username, string? paramName) @@ -186,13 +145,15 @@ namespace Timeline.Services throw new EntityAlreadyExistException(EntityNames.User, ExceptionUsernameConflict); } - private static User CreateUserFromEntity(UserEntity entity) + private async Task CreateUserFromEntity(UserEntity entity) { + var permission = await _userPermissionService.GetPermissionsOfUserAsync(entity.Id); return new User { UniqueId = entity.UniqueId, Username = entity.Username, - Administrator = UserRoleConvert.ToBool(entity.Roles), + Administrator = permission.Contains(UserPermission.UserManagement), + Permissions = permission, Nickname = string.IsNullOrEmpty(entity.Nickname) ? entity.Username : entity.Nickname, Id = entity.Id, Version = entity.Version, @@ -220,32 +181,17 @@ namespace Timeline.Services if (!_passwordService.VerifyPassword(entity.Password, password)) throw new BadPasswordException(password); - return CreateUserFromEntity(entity); + return await CreateUserFromEntity(entity); } - public async Task GetUserById(long id) + public async Task GetUser(long id) { var user = await _databaseContext.Users.Where(u => u.Id == id).SingleOrDefaultAsync(); if (user == null) throw new UserNotExistException(id); - return CreateUserFromEntity(user); - } - - public async Task GetUserByUsername(string username) - { - if (username == null) - throw new ArgumentNullException(nameof(username)); - - CheckUsernameFormat(username, nameof(username)); - - var entity = await _databaseContext.Users.Where(user => user.Username == username).SingleOrDefaultAsync(); - - if (entity == null) - throw new UserNotExistException(username); - - return CreateUserFromEntity(entity); + return await CreateUserFromEntity(user); } public async Task GetUserIdByUsername(string username) @@ -263,78 +209,69 @@ namespace Timeline.Services return entity.Id; } - public async Task GetUsers() + public async Task> GetUsers() { - var entities = await _databaseContext.Users.ToArrayAsync(); - return entities.Select(user => CreateUserFromEntity(user)).ToArray(); + List result = new(); + foreach (var entity in await _databaseContext.Users.ToArrayAsync()) + { + result.Add(await CreateUserFromEntity(entity)); + } + return result; } - public async Task CreateUser(User info) + public async Task CreateUser(string username, string password) { - if (info == null) - throw new ArgumentNullException(nameof(info)); - - if (info.Username == null) - throw new ArgumentException(ExceptionUsernameNull, nameof(info)); - CheckUsernameFormat(info.Username, nameof(info)); - - if (info.Password == null) - throw new ArgumentException(ExceptionPasswordNull, nameof(info)); - CheckPasswordFormat(info.Password, nameof(info)); - - if (info.Nickname != null) - CheckNicknameFormat(info.Nickname, nameof(info)); + if (username == null) + throw new ArgumentNullException(nameof(username)); + if (password == null) + throw new ArgumentNullException(nameof(password)); - var username = info.Username; + CheckUsernameFormat(username, nameof(username)); + CheckPasswordFormat(password, nameof(password)); var conflict = await _databaseContext.Users.AnyAsync(u => u.Username == username); if (conflict) ThrowUsernameConflict(); - var administrator = info.Administrator ?? false; - var password = info.Password; - var nickname = info.Nickname; - var newEntity = new UserEntity { Username = username, Password = _passwordService.HashPassword(password), - Roles = UserRoleConvert.ToString(administrator), - Nickname = nickname, + Roles = "", Version = 1 }; _databaseContext.Users.Add(newEntity); await _databaseContext.SaveChangesAsync(); - _logger.LogInformation(Log.Format(LogDatabaseCreate, - ("Id", newEntity.Id), ("Username", username), ("Administrator", administrator))); + _logger.LogInformation(Log.Format(LogDatabaseCreate, ("Id", newEntity.Id), ("Username", username))); - return CreateUserFromEntity(newEntity); + return await CreateUserFromEntity(newEntity); } - private void ValidateModifyUserInfo(User? info) + public async Task ModifyUser(long id, ModifyUserParams? param) { - if (info != null) + if (param != null) { - if (info.Username != null) - CheckUsernameFormat(info.Username, nameof(info)); + if (param.Username != null) + CheckUsernameFormat(param.Username, nameof(param)); - if (info.Password != null) - CheckPasswordFormat(info.Password, nameof(info)); + if (param.Password != null) + CheckPasswordFormat(param.Password, nameof(param)); - if (info.Nickname != null) - CheckNicknameFormat(info.Nickname, nameof(info)); + if (param.Nickname != null) + CheckNicknameFormat(param.Nickname, nameof(param)); } - } - private async Task UpdateUserEntity(UserEntity entity, User? info) - { - if (info != null) + var entity = await _databaseContext.Users.Where(u => u.Id == id).SingleOrDefaultAsync(); + if (entity == null) + throw new UserNotExistException(id); + + if (param != null) { var now = _clock.GetCurrentTime(); bool updateLastModified = false; - var username = info.Username; + var username = param.Username; if (username != null && username != entity.Username) { var conflict = await _databaseContext.Users.AnyAsync(u => u.Username == username); @@ -346,21 +283,14 @@ namespace Timeline.Services updateLastModified = true; } - var password = info.Password; + var password = param.Password; if (password != null) { entity.Password = _passwordService.HashPassword(password); entity.Version += 1; } - var administrator = info.Administrator; - if (administrator.HasValue && UserRoleConvert.ToBool(entity.Roles) != administrator) - { - entity.Roles = UserRoleConvert.ToString(administrator.Value); - updateLastModified = true; - } - - var nickname = info.Nickname; + var nickname = param.Nickname; if (nickname != null && nickname != entity.Nickname) { entity.Nickname = nickname; @@ -371,44 +301,12 @@ namespace Timeline.Services { entity.LastModified = now; } - } - } + await _databaseContext.SaveChangesAsync(); + _logger.LogInformation(LogDatabaseUpdate, ("Id", id)); + } - public async Task ModifyUser(long id, User? info) - { - ValidateModifyUserInfo(info); - - var entity = await _databaseContext.Users.Where(u => u.Id == id).SingleOrDefaultAsync(); - if (entity == null) - throw new UserNotExistException(id); - - await UpdateUserEntity(entity, info); - - await _databaseContext.SaveChangesAsync(); - _logger.LogInformation(LogDatabaseUpdate, ("Id", id)); - - return CreateUserFromEntity(entity); - } - - public async Task ModifyUser(string username, User? info) - { - if (username == null) - throw new ArgumentNullException(nameof(username)); - CheckUsernameFormat(username, nameof(username)); - - ValidateModifyUserInfo(info); - - var entity = await _databaseContext.Users.Where(u => u.Username == username).SingleOrDefaultAsync(); - if (entity == null) - throw new UserNotExistException(username); - - await UpdateUserEntity(entity, info); - - await _databaseContext.SaveChangesAsync(); - _logger.LogInformation(LogDatabaseUpdate, ("Username", username)); - - return CreateUserFromEntity(entity); + return await CreateUserFromEntity(entity); } public async Task ChangePassword(long id, string oldPassword, string newPassword) -- cgit v1.2.3 From 34dea0b713aaac265909fe24eeb9483c9ec8fe2a Mon Sep 17 00:00:00 2001 From: crupest Date: Thu, 12 Nov 2020 23:21:31 +0800 Subject: ... --- BackEnd/Timeline.Tests/Helpers/TestDatabase.cs | 21 +++---------- .../IntegratedTests/IntegratedTestBase.cs | 25 +++++---------- .../Timeline.Tests/IntegratedTests/TokenTest.cs | 3 +- BackEnd/Timeline.Tests/IntegratedTests/UserTest.cs | 36 +++++----------------- .../Timeline.Tests/Services/TimelineServiceTest.cs | 9 ++++-- .../Controllers/ControllerAuthExtensions.cs | 5 +-- BackEnd/Timeline/Controllers/TimelineController.cs | 20 ++++++------ .../Timeline/Controllers/UserAvatarController.cs | 6 ++-- BackEnd/Timeline/Controllers/UserController.cs | 24 +++++++-------- BackEnd/Timeline/Models/Http/UserController.cs | 21 ++----------- BackEnd/Timeline/Services/TimelineService.cs | 14 ++++----- BackEnd/Timeline/Services/UserService.cs | 4 +-- 12 files changed, 67 insertions(+), 121 deletions(-) (limited to 'BackEnd/Timeline/Services/UserService.cs') diff --git a/BackEnd/Timeline.Tests/Helpers/TestDatabase.cs b/BackEnd/Timeline.Tests/Helpers/TestDatabase.cs index f0c26180..74db74aa 100644 --- a/BackEnd/Timeline.Tests/Helpers/TestDatabase.cs +++ b/BackEnd/Timeline.Tests/Helpers/TestDatabase.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.Logging.Abstractions; using System.Threading.Tasks; using Timeline.Entities; using Timeline.Migrations; -using Timeline.Models; using Timeline.Services; using Xunit; @@ -36,23 +35,13 @@ namespace Timeline.Tests.Helpers if (_createUser) { var passwordService = new PasswordService(); - var userService = new UserService(NullLogger.Instance, context, passwordService, new Clock()); + var userService = new UserService(NullLogger.Instance, context, passwordService, new Clock(), new UserPermissionService(context)); - await userService.CreateUser(new User - { - Username = "admin", - Password = "adminpw", - Administrator = true, - Nickname = "administrator" - }); + var admin = await userService.CreateUser("admin", "adminpw"); + await userService.ModifyUser(admin.Id, new ModifyUserParams() { Nickname = "administrator" }); - await userService.CreateUser(new User - { - Username = "user", - Password = "userpw", - Administrator = false, - Nickname = "imuser" - }); + var user = await userService.CreateUser("user", "userpw"); + await userService.ModifyUser(user.Id, new ModifyUserParams() { Nickname = "imuser" }); } } } diff --git a/BackEnd/Timeline.Tests/IntegratedTests/IntegratedTestBase.cs b/BackEnd/Timeline.Tests/IntegratedTests/IntegratedTestBase.cs index 7cf27297..f75ce69c 100644 --- a/BackEnd/Timeline.Tests/IntegratedTests/IntegratedTestBase.cs +++ b/BackEnd/Timeline.Tests/IntegratedTests/IntegratedTestBase.cs @@ -7,7 +7,6 @@ using System.Net.Http; using System.Text.Json; using System.Text.Json.Serialization; using System.Threading.Tasks; -using Timeline.Models; using Timeline.Models.Converters; using Timeline.Models.Http; using Timeline.Services; @@ -60,26 +59,14 @@ namespace Timeline.Tests.IntegratedTests using (var scope = TestApp.Host.Services.CreateScope()) { - var users = new List() + var users = new List<(string username, string password, string nickname)>() { - new User - { - Username = "admin", - Password = "adminpw", - Administrator = true, - Nickname = "administrator" - } + ("admin", "adminpw", "administrator") }; for (int i = 1; i <= _userCount; i++) { - users.Add(new User - { - Username = $"user{i}", - Password = $"user{i}pw", - Administrator = false, - Nickname = $"imuser{i}" - }); + users.Add(($"user{i}", $"user{i}pw", $"imuser{i}")); } var userInfoList = new List(); @@ -87,7 +74,9 @@ namespace Timeline.Tests.IntegratedTests var userService = scope.ServiceProvider.GetRequiredService(); foreach (var user in users) { - await userService.CreateUser(user); + var (username, password, nickname) = user; + var u = await userService.CreateUser(username, password); + await userService.ModifyUser(u.Id, new ModifyUserParams() { Nickname = nickname }); } using var client = await CreateDefaultClient(); @@ -99,7 +88,7 @@ namespace Timeline.Tests.IntegratedTests options.Converters.Add(new JsonDateTimeConverter()); foreach (var user in users) { - var s = await client.GetStringAsync($"users/{user.Username}"); + var s = await client.GetStringAsync($"users/{user.username}"); userInfoList.Add(JsonSerializer.Deserialize(s, options)); } diff --git a/BackEnd/Timeline.Tests/IntegratedTests/TokenTest.cs b/BackEnd/Timeline.Tests/IntegratedTests/TokenTest.cs index 480d66cd..f4a406d1 100644 --- a/BackEnd/Timeline.Tests/IntegratedTests/TokenTest.cs +++ b/BackEnd/Timeline.Tests/IntegratedTests/TokenTest.cs @@ -103,7 +103,8 @@ namespace Timeline.Tests.IntegratedTests { // create a user for test var userService = scope.ServiceProvider.GetRequiredService(); - await userService.ModifyUser("user1", new User { Password = "user1pw" }); + var id = await userService.GetUserIdByUsername("user1"); + await userService.ModifyUser(id, new ModifyUserParams { Password = "user1pw" }); } (await client.PostAsJsonAsync(VerifyTokenUrl, diff --git a/BackEnd/Timeline.Tests/IntegratedTests/UserTest.cs b/BackEnd/Timeline.Tests/IntegratedTests/UserTest.cs index 9dfcc6a5..329e53f5 100644 --- a/BackEnd/Timeline.Tests/IntegratedTests/UserTest.cs +++ b/BackEnd/Timeline.Tests/IntegratedTests/UserTest.cs @@ -2,6 +2,7 @@ using FluentAssertions; using System.Collections.Generic; using System.Net; using System.Net.Http; +using System.Net.Http.Json; using System.Threading.Tasks; using Timeline.Models.Http; using Timeline.Tests.Helpers; @@ -129,13 +130,11 @@ namespace Timeline.Tests.IntegratedTests { Username = "newuser", Password = "newpw", - Administrator = true, Nickname = "aaa" }); var body = res.Should().HaveStatusCode(200) .And.HaveJsonBody() .Which; - body.Administrator.Should().Be(true); body.Nickname.Should().Be("aaa"); } @@ -144,14 +143,14 @@ namespace Timeline.Tests.IntegratedTests var body = res.Should().HaveStatusCode(200) .And.HaveJsonBody() .Which; - body.Administrator.Should().Be(true); body.Nickname.Should().Be("aaa"); } { + var token = userClient.DefaultRequestHeaders.Authorization.Parameter; // Token should expire. - var res = await userClient.GetAsync("testing/auth/Authorize"); - res.Should().HaveStatusCode(HttpStatusCode.Unauthorized); + var res = await userClient.PostAsJsonAsync("token/verify", new() { Token = token }); + res.Should().HaveStatusCode(HttpStatusCode.BadRequest); } { @@ -235,14 +234,6 @@ namespace Timeline.Tests.IntegratedTests res.Should().HaveStatusCode(HttpStatusCode.Forbidden); } - [Fact] - public async Task Patch_Administrator_Forbid() - { - using var client = await CreateClientAsUser(); - var res = await client.PatchAsJsonAsync("users/user1", new UserPatchRequest { Administrator = true }); - res.Should().HaveStatusCode(HttpStatusCode.Forbidden); - } - [Fact] public async Task Delete_Deleted() { @@ -301,22 +292,16 @@ namespace Timeline.Tests.IntegratedTests { Username = "aaa", Password = "bbb", - Administrator = true, - Nickname = "ccc" }); var body = res.Should().HaveStatusCode(200) .And.HaveJsonBody().Which; body.Username.Should().Be("aaa"); - body.Nickname.Should().Be("ccc"); - body.Administrator.Should().BeTrue(); } { var res = await client.GetAsync("users/aaa"); var body = res.Should().HaveStatusCode(200) .And.HaveJsonBody().Which; body.Username.Should().Be("aaa"); - body.Nickname.Should().Be("ccc"); - body.Administrator.Should().BeTrue(); } { // Test password. @@ -326,12 +311,10 @@ namespace Timeline.Tests.IntegratedTests public static IEnumerable Op_CreateUser_InvalidModel_Data() { - yield return new[] { new CreateUserRequest { Username = "aaa", Password = "bbb" } }; - yield return new[] { new CreateUserRequest { Username = "aaa", Administrator = true } }; - yield return new[] { new CreateUserRequest { Password = "bbb", Administrator = true } }; - yield return new[] { new CreateUserRequest { Username = "a!a", Password = "bbb", Administrator = true } }; - yield return new[] { new CreateUserRequest { Username = "aaa", Password = "", Administrator = true } }; - yield return new[] { new CreateUserRequest { Username = "aaa", Password = "bbb", Administrator = true, Nickname = new string('a', 40) } }; + yield return new[] { new CreateUserRequest { Username = "aaa" } }; + yield return new[] { new CreateUserRequest { Password = "bbb" } }; + yield return new[] { new CreateUserRequest { Username = "a!a", Password = "bbb" } }; + yield return new[] { new CreateUserRequest { Username = "aaa", Password = "" } }; } [Theory] @@ -354,7 +337,6 @@ namespace Timeline.Tests.IntegratedTests { Username = "user1", Password = "bbb", - Administrator = false }); res.Should().HaveStatusCode(400) .And.HaveCommonBody(ErrorCodes.UserController.UsernameConflict); @@ -370,7 +352,6 @@ namespace Timeline.Tests.IntegratedTests { Username = "aaa", Password = "bbb", - Administrator = false }); res.Should().HaveStatusCode(HttpStatusCode.Unauthorized); } @@ -385,7 +366,6 @@ namespace Timeline.Tests.IntegratedTests { Username = "aaa", Password = "bbb", - Administrator = false }); res.Should().HaveStatusCode(HttpStatusCode.Forbidden); } diff --git a/BackEnd/Timeline.Tests/Services/TimelineServiceTest.cs b/BackEnd/Timeline.Tests/Services/TimelineServiceTest.cs index 19d2781a..73fdd32f 100644 --- a/BackEnd/Timeline.Tests/Services/TimelineServiceTest.cs +++ b/BackEnd/Timeline.Tests/Services/TimelineServiceTest.cs @@ -24,6 +24,8 @@ namespace Timeline.Tests.Services private DataManager _dataManager; + private UserPermissionService _userPermissionService; + private UserService _userService; private TimelineService _timelineService; @@ -37,7 +39,8 @@ namespace Timeline.Tests.Services protected override void OnDatabaseCreated() { _dataManager = new DataManager(Database, _eTagGenerator); - _userService = new UserService(NullLogger.Instance, Database, _passwordService, _clock); + _userPermissionService = new UserPermissionService(Database); + _userService = new UserService(NullLogger.Instance, Database, _passwordService, _clock, _userPermissionService); _timelineService = new TimelineService(NullLogger.Instance, Database, _dataManager, _userService, _imageValidator, _clock); _userDeleteService = new UserDeleteService(NullLogger.Instance, Database, _timelineService); } @@ -207,13 +210,13 @@ namespace Timeline.Tests.Services } { - await _userService.ModifyUser(userId, new User { Nickname = "haha" }); + await _userService.ModifyUser(userId, new ModifyUserParams { Nickname = "haha" }); var posts = await _timelineService.GetPosts(timelineName, time2); posts.Should().HaveCount(0); } { - await _userService.ModifyUser(userId, new User { Username = "haha" }); + await _userService.ModifyUser(userId, new ModifyUserParams { Username = "haha" }); var posts = await _timelineService.GetPosts(timelineName, time2); posts.Should().HaveCount(4); } diff --git a/BackEnd/Timeline/Controllers/ControllerAuthExtensions.cs b/BackEnd/Timeline/Controllers/ControllerAuthExtensions.cs index 00a65454..9096978d 100644 --- a/BackEnd/Timeline/Controllers/ControllerAuthExtensions.cs +++ b/BackEnd/Timeline/Controllers/ControllerAuthExtensions.cs @@ -2,15 +2,16 @@ using System; using System.Security.Claims; using Timeline.Auth; +using Timeline.Services; using static Timeline.Resources.Controllers.ControllerAuthExtensions; namespace Timeline.Controllers { public static class ControllerAuthExtensions { - public static bool IsAdministrator(this ControllerBase controller) + public static bool UserHasPermission(this ControllerBase controller, UserPermission permission) { - return controller.User != null && controller.User.IsAdministrator(); + return controller.User != null && controller.User.HasPermission(permission); } public static long GetUserId(this ControllerBase controller) diff --git a/BackEnd/Timeline/Controllers/TimelineController.cs b/BackEnd/Timeline/Controllers/TimelineController.cs index 9a3147ea..45060b5d 100644 --- a/BackEnd/Timeline/Controllers/TimelineController.cs +++ b/BackEnd/Timeline/Controllers/TimelineController.cs @@ -43,6 +43,8 @@ namespace Timeline.Controllers _mapper = mapper; } + private bool UserHasAllTimelineManagementPermission => this.UserHasPermission(UserPermission.AllTimelineManagement); + /// /// List all timelines. /// @@ -180,7 +182,7 @@ namespace Timeline.Controllers [ProducesResponseType(StatusCodes.Status404NotFound)] public async Task>> PostListGet([FromRoute][GeneralTimelineName] string name, [FromQuery] DateTime? modifiedSince, [FromQuery] bool? includeDeleted) { - if (!this.IsAdministrator() && !await _service.HasReadPermission(name, this.GetOptionalUserId())) + if (!UserHasAllTimelineManagementPermission && !await _service.HasReadPermission(name, this.GetOptionalUserId())) { return StatusCode(StatusCodes.Status403Forbidden, ErrorResponse.Common.Forbid()); } @@ -208,7 +210,7 @@ namespace Timeline.Controllers public async Task PostDataGet([FromRoute][GeneralTimelineName] string name, [FromRoute] long id, [FromHeader(Name = "If-None-Match")] string? ifNoneMatch) { _ = ifNoneMatch; - if (!this.IsAdministrator() && !await _service.HasReadPermission(name, this.GetOptionalUserId())) + if (!UserHasAllTimelineManagementPermission && !await _service.HasReadPermission(name, this.GetOptionalUserId())) { return StatusCode(StatusCodes.Status403Forbidden, ErrorResponse.Common.Forbid()); } @@ -246,7 +248,7 @@ namespace Timeline.Controllers public async Task> PostPost([FromRoute][GeneralTimelineName] string name, [FromBody] TimelinePostCreateRequest body) { var id = this.GetUserId(); - if (!this.IsAdministrator() && !await _service.IsMemberOf(name, id)) + if (!UserHasAllTimelineManagementPermission && !await _service.IsMemberOf(name, id)) { return StatusCode(StatusCodes.Status403Forbidden, ErrorResponse.Common.Forbid()); } @@ -313,7 +315,7 @@ namespace Timeline.Controllers [ProducesResponseType(StatusCodes.Status403Forbidden)] public async Task> PostDelete([FromRoute][GeneralTimelineName] string name, [FromRoute] long id) { - if (!this.IsAdministrator() && !await _service.HasPostModifyPermission(name, id, this.GetUserId())) + if (!UserHasAllTimelineManagementPermission && !await _service.HasPostModifyPermission(name, id, this.GetUserId())) { return StatusCode(StatusCodes.Status403Forbidden, ErrorResponse.Common.Forbid()); } @@ -342,7 +344,7 @@ namespace Timeline.Controllers [ProducesResponseType(StatusCodes.Status403Forbidden)] public async Task> TimelinePatch([FromRoute][GeneralTimelineName] string name, [FromBody] TimelinePatchRequest body) { - if (!this.IsAdministrator() && !(await _service.HasManagePermission(name, this.GetUserId()))) + if (!UserHasAllTimelineManagementPermission && !(await _service.HasManagePermission(name, this.GetUserId()))) { return StatusCode(StatusCodes.Status403Forbidden, ErrorResponse.Common.Forbid()); } @@ -365,7 +367,7 @@ namespace Timeline.Controllers [ProducesResponseType(StatusCodes.Status403Forbidden)] public async Task TimelineMemberPut([FromRoute][GeneralTimelineName] string name, [FromRoute][Username] string member) { - if (!this.IsAdministrator() && !(await _service.HasManagePermission(name, this.GetUserId()))) + if (!UserHasAllTimelineManagementPermission && !(await _service.HasManagePermission(name, this.GetUserId()))) { return StatusCode(StatusCodes.Status403Forbidden, ErrorResponse.Common.Forbid()); } @@ -393,7 +395,7 @@ namespace Timeline.Controllers [ProducesResponseType(StatusCodes.Status403Forbidden)] public async Task TimelineMemberDelete([FromRoute][GeneralTimelineName] string name, [FromRoute][Username] string member) { - if (!this.IsAdministrator() && !(await _service.HasManagePermission(name, this.GetUserId()))) + if (!UserHasAllTimelineManagementPermission && !(await _service.HasManagePermission(name, this.GetUserId()))) { return StatusCode(StatusCodes.Status403Forbidden, ErrorResponse.Common.Forbid()); } @@ -448,7 +450,7 @@ namespace Timeline.Controllers [ProducesResponseType(StatusCodes.Status403Forbidden)] public async Task> TimelineDelete([FromRoute][TimelineName] string name) { - if (!this.IsAdministrator() && !(await _service.HasManagePermission(name, this.GetUserId()))) + if (!UserHasAllTimelineManagementPermission && !(await _service.HasManagePermission(name, this.GetUserId()))) { return StatusCode(StatusCodes.Status403Forbidden, ErrorResponse.Common.Forbid()); } @@ -472,7 +474,7 @@ namespace Timeline.Controllers [ProducesResponseType(StatusCodes.Status403Forbidden)] public async Task> TimelineOpChangeName([FromBody] TimelineChangeNameRequest body) { - if (!this.IsAdministrator() && !(await _service.HasManagePermission(body.OldName, this.GetUserId()))) + if (!UserHasAllTimelineManagementPermission && !(await _service.HasManagePermission(body.OldName, this.GetUserId()))) { return StatusCode(StatusCodes.Status403Forbidden, ErrorResponse.Common.Forbid()); } diff --git a/BackEnd/Timeline/Controllers/UserAvatarController.cs b/BackEnd/Timeline/Controllers/UserAvatarController.cs index bc4afa30..44d45b76 100644 --- a/BackEnd/Timeline/Controllers/UserAvatarController.cs +++ b/BackEnd/Timeline/Controllers/UserAvatarController.cs @@ -86,7 +86,7 @@ namespace Timeline.Controllers [ProducesResponseType(StatusCodes.Status403Forbidden)] public async Task Put([FromRoute][Username] string username, [FromBody] ByteData body) { - if (!User.IsAdministrator() && User.Identity.Name != username) + if (!this.UserHasPermission(UserPermission.UserManagement) && User.Identity!.Name != username) { _logger.LogInformation(Log.Format(LogPutForbid, ("Operator Username", User.Identity.Name), ("Username To Put Avatar", username))); @@ -149,10 +149,10 @@ namespace Timeline.Controllers [Authorize] public async Task Delete([FromRoute][Username] string username) { - if (!User.IsAdministrator() && User.Identity.Name != username) + if (!this.UserHasPermission(UserPermission.UserManagement) && User.Identity!.Name != username) { _logger.LogInformation(Log.Format(LogDeleteForbid, - ("Operator Username", User.Identity.Name), ("Username To Delete Avatar", username))); + ("Operator Username", User.Identity!.Name), ("Username To Delete Avatar", username))); return StatusCode(StatusCodes.Status403Forbidden, ErrorResponse.Common.Forbid()); } diff --git a/BackEnd/Timeline/Controllers/UserController.cs b/BackEnd/Timeline/Controllers/UserController.cs index 02c09aab..524e5559 100644 --- a/BackEnd/Timeline/Controllers/UserController.cs +++ b/BackEnd/Timeline/Controllers/UserController.cs @@ -65,7 +65,8 @@ namespace Timeline.Controllers { try { - var user = await _userService.GetUserByUsername(username); + var id = await _userService.GetUserIdByUsername(username); + var user = await _userService.GetUser(id); return Ok(ConvertToUserInfo(user)); } catch (UserNotExistException e) @@ -89,11 +90,12 @@ namespace Timeline.Controllers [ProducesResponseType(StatusCodes.Status404NotFound)] public async Task> Patch([FromBody] UserPatchRequest body, [FromRoute][Username] string username) { - if (this.IsAdministrator()) + if (this.UserHasPermission(UserPermission.UserManagement)) { try { - var user = await _userService.ModifyUser(username, _mapper.Map(body)); + var id = await _userService.GetUserIdByUsername(username); + var user = await _userService.ModifyUser(id, _mapper.Map(body)); return Ok(ConvertToUserInfo(user)); } catch (UserNotExistException e) @@ -108,7 +110,7 @@ namespace Timeline.Controllers } else { - if (User.Identity.Name != username) + if (User.Identity!.Name != username) return StatusCode(StatusCodes.Status403Forbidden, ErrorResponse.Common.CustomMessage_Forbid(Common_Forbid_NotSelf)); @@ -120,11 +122,7 @@ namespace Timeline.Controllers return StatusCode(StatusCodes.Status403Forbidden, ErrorResponse.Common.CustomMessage_Forbid(UserController_Patch_Forbid_Password)); - if (body.Administrator != null) - return StatusCode(StatusCodes.Status403Forbidden, - ErrorResponse.Common.CustomMessage_Forbid(UserController_Patch_Forbid_Administrator)); - - var user = await _userService.ModifyUser(this.GetUserId(), _mapper.Map(body)); + var user = await _userService.ModifyUser(this.GetUserId(), _mapper.Map(body)); return Ok(ConvertToUserInfo(user)); } } @@ -134,7 +132,7 @@ namespace Timeline.Controllers /// /// Username of the user to delete. /// Info of deletion. - [HttpDelete("users/{username}"), AdminAuthorize] + [HttpDelete("users/{username}"), PermissionAuthorize(UserPermission.UserManagement)] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] [ProducesResponseType(StatusCodes.Status403Forbidden)] @@ -151,7 +149,7 @@ namespace Timeline.Controllers /// Create a new user. You have to be administrator. /// /// The new user's info. - [HttpPost("userop/createuser"), AdminAuthorize] + [HttpPost("userop/createuser"), PermissionAuthorize(UserPermission.UserManagement)] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] @@ -160,7 +158,7 @@ namespace Timeline.Controllers { try { - var user = await _userService.CreateUser(_mapper.Map(body)); + var user = await _userService.CreateUser(body.Username, body.Password); return Ok(ConvertToUserInfo(user)); } catch (EntityAlreadyExistException e) when (e.EntityName == EntityNames.User) @@ -186,7 +184,7 @@ namespace Timeline.Controllers catch (BadPasswordException e) { _logger.LogInformation(e, Log.Format(LogChangePasswordBadPassword, - ("Username", User.Identity.Name), ("Old Password", request.OldPassword))); + ("Username", User.Identity!.Name), ("Old Password", request.OldPassword))); return BadRequest(ErrorResponse.UserController.ChangePassword_BadOldPassword()); } // User can't be non-existent or the token is bad. diff --git a/BackEnd/Timeline/Models/Http/UserController.cs b/BackEnd/Timeline/Models/Http/UserController.cs index 6bc5a66e..92a63874 100644 --- a/BackEnd/Timeline/Models/Http/UserController.cs +++ b/BackEnd/Timeline/Models/Http/UserController.cs @@ -2,6 +2,7 @@ using AutoMapper; using System.ComponentModel.DataAnnotations; using Timeline.Controllers; using Timeline.Models.Validation; +using Timeline.Services; namespace Timeline.Models.Http { @@ -27,11 +28,6 @@ namespace Timeline.Models.Http /// [Nickname] public string? Nickname { get; set; } - - /// - /// Whether to be administrator. Null if not change. Need to be administrator. - /// - public bool? Administrator { get; set; } } /// @@ -50,18 +46,6 @@ namespace Timeline.Models.Http /// [Required, MinLength(1)] public string Password { get; set; } = default!; - - /// - /// Whether the new user is administrator. - /// - [Required] - public bool? Administrator { get; set; } - - /// - /// Nickname of the new user. - /// - [Nickname] - public string? Nickname { get; set; } } /// @@ -86,8 +70,7 @@ namespace Timeline.Models.Http { public UserControllerAutoMapperProfile() { - CreateMap(MemberList.Source); - CreateMap(MemberList.Source); + CreateMap(); } } } diff --git a/BackEnd/Timeline/Services/TimelineService.cs b/BackEnd/Timeline/Services/TimelineService.cs index 4bcae596..04870dcf 100644 --- a/BackEnd/Timeline/Services/TimelineService.cs +++ b/BackEnd/Timeline/Services/TimelineService.cs @@ -414,12 +414,12 @@ namespace Timeline.Services /// Remember to include Members when query. private async Task MapTimelineFromEntity(TimelineEntity entity) { - var owner = await _userService.GetUserById(entity.OwnerId); + var owner = await _userService.GetUser(entity.OwnerId); var members = new List(); foreach (var memberEntity in entity.Members) { - members.Add(await _userService.GetUserById(memberEntity.UserId)); + members.Add(await _userService.GetUser(memberEntity.UserId)); } var name = entity.Name ?? ("@" + owner.Username); @@ -441,7 +441,7 @@ namespace Timeline.Services private async Task MapTimelinePostFromEntity(TimelinePostEntity entity, string timelineName) { - User? author = entity.AuthorId.HasValue ? await _userService.GetUserById(entity.AuthorId.Value) : null; + User? author = entity.AuthorId.HasValue ? await _userService.GetUser(entity.AuthorId.Value) : null; ITimelinePostContent? content = null; @@ -699,7 +699,7 @@ namespace Timeline.Services var timelineId = await FindTimelineId(timelineName); var timelineEntity = await _database.Timelines.Where(t => t.Id == timelineId).SingleAsync(); - var author = await _userService.GetUserById(authorId); + var author = await _userService.GetUser(authorId); var currentTime = _clock.GetCurrentTime(); var finalTime = time ?? currentTime; @@ -742,7 +742,7 @@ namespace Timeline.Services var timelineId = await FindTimelineId(timelineName); var timelineEntity = await _database.Timelines.Where(t => t.Id == timelineId).SingleAsync(); - var author = await _userService.GetUserById(authorId); + var author = await _userService.GetUser(authorId); var imageFormat = await _imageValidator.Validate(data); @@ -1098,14 +1098,14 @@ namespace Timeline.Services ValidateTimelineName(name, nameof(name)); - var user = await _userService.GetUserById(owner); + var user = await _userService.GetUser(owner); var conflict = await _database.Timelines.AnyAsync(t => t.Name == name); if (conflict) throw new EntityAlreadyExistException(EntityNames.Timeline, null, ExceptionTimelineNameConflict); - var newEntity = CreateNewTimelineEntity(name, user.Id!.Value); + var newEntity = CreateNewTimelineEntity(name, user.Id); _database.Timelines.Add(newEntity); await _database.SaveChangesAsync(); diff --git a/BackEnd/Timeline/Services/UserService.cs b/BackEnd/Timeline/Services/UserService.cs index ed637ba3..b925742e 100644 --- a/BackEnd/Timeline/Services/UserService.cs +++ b/BackEnd/Timeline/Services/UserService.cs @@ -17,7 +17,7 @@ namespace Timeline.Services /// /// Null means not change. /// - public record ModifyUserParams(string? Username, string? Password, string? Nickname); + public record ModifyUserParams(string? Username = null, string? Password = null, string? Nickname = null); public interface IUserService { @@ -74,7 +74,7 @@ namespace Timeline.Services /// The id of the user. /// The new information. /// The new user info. - /// Thrown when some fields in is bad. + /// Thrown when some fields in is bad. /// Thrown when user with given id does not exist. /// /// Version will increase if password is changed. -- cgit v1.2.3 From 774f8f018ccb48c538f6d972ed99571f13fc140e Mon Sep 17 00:00:00 2001 From: crupest Date: Thu, 12 Nov 2020 23:45:00 +0800 Subject: feat: Add REST API for user permission. --- BackEnd/Timeline/Controllers/UserController.cs | 48 +++++++++++++++++++++- .../Models/Converters/JsonDateTimeConverter.cs | 2 +- BackEnd/Timeline/Models/Validation/Validator.cs | 4 +- BackEnd/Timeline/Services/UserService.cs | 7 +++- 4 files changed, 55 insertions(+), 6 deletions(-) (limited to 'BackEnd/Timeline/Services/UserService.cs') diff --git a/BackEnd/Timeline/Controllers/UserController.cs b/BackEnd/Timeline/Controllers/UserController.cs index 524e5559..c5d1d4de 100644 --- a/BackEnd/Timeline/Controllers/UserController.cs +++ b/BackEnd/Timeline/Controllers/UserController.cs @@ -26,20 +26,24 @@ namespace Timeline.Controllers { private readonly ILogger _logger; private readonly IUserService _userService; + private readonly IUserPermissionService _userPermissionService; private readonly IUserDeleteService _userDeleteService; private readonly IMapper _mapper; /// - public UserController(ILogger logger, IUserService userService, IUserDeleteService userDeleteService, IMapper mapper) + public UserController(ILogger logger, IUserService userService, IUserPermissionService userPermissionService, IUserDeleteService userDeleteService, IMapper mapper) { _logger = logger; _userService = userService; + _userPermissionService = userPermissionService; _userDeleteService = userDeleteService; _mapper = mapper; } private UserInfo ConvertToUserInfo(User user) => _mapper.Map(user); + private bool UserHasUserManagementPermission => this.UserHasPermission(UserPermission.UserManagement); + /// /// Get all users. /// @@ -90,7 +94,7 @@ namespace Timeline.Controllers [ProducesResponseType(StatusCodes.Status404NotFound)] public async Task> Patch([FromBody] UserPatchRequest body, [FromRoute][Username] string username) { - if (this.UserHasPermission(UserPermission.UserManagement)) + if (UserHasUserManagementPermission) { try { @@ -189,5 +193,45 @@ namespace Timeline.Controllers } // User can't be non-existent or the token is bad. } + + [HttpPut("users/{username}/permissions/{permission}"), PermissionAuthorize(UserPermission.UserManagement)] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status401Unauthorized)] + [ProducesResponseType(StatusCodes.Status403Forbidden)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public async Task PutUserPermission([FromRoute] string username, [FromRoute] UserPermission permission) + { + try + { + var id = await _userService.GetUserIdByUsername(username); + await _userPermissionService.AddPermissionToUserAsync(id, permission); + return Ok(); + } + catch (UserNotExistException) + { + return NotFound(ErrorResponse.UserCommon.NotExist()); + } + } + + [HttpDelete("users/{username}/permissions/{permission}"), PermissionAuthorize(UserPermission.UserManagement)] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status401Unauthorized)] + [ProducesResponseType(StatusCodes.Status403Forbidden)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public async Task DeleteUserPermission([FromRoute] string username, [FromRoute] UserPermission permission) + { + try + { + var id = await _userService.GetUserIdByUsername(username); + await _userPermissionService.RemovePermissionFromUserAsync(id, permission); + return Ok(); + } + catch (UserNotExistException) + { + return NotFound(ErrorResponse.UserCommon.NotExist()); + } + } } } diff --git a/BackEnd/Timeline/Models/Converters/JsonDateTimeConverter.cs b/BackEnd/Timeline/Models/Converters/JsonDateTimeConverter.cs index 94b5cab0..72a2908c 100644 --- a/BackEnd/Timeline/Models/Converters/JsonDateTimeConverter.cs +++ b/BackEnd/Timeline/Models/Converters/JsonDateTimeConverter.cs @@ -12,7 +12,7 @@ namespace Timeline.Models.Converters public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { Debug.Assert(typeToConvert == typeof(DateTime)); - return DateTime.Parse(reader.GetString(), CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal); + return DateTime.Parse(reader.GetString()!, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal); } public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) diff --git a/BackEnd/Timeline/Models/Validation/Validator.cs b/BackEnd/Timeline/Models/Validation/Validator.cs index aef7891c..b7e754d3 100644 --- a/BackEnd/Timeline/Models/Validation/Validator.cs +++ b/BackEnd/Timeline/Models/Validation/Validator.cs @@ -111,12 +111,12 @@ namespace Timeline.Models.Validation } } - protected override ValidationResult IsValid(object value, ValidationContext validationContext) + protected override ValidationResult IsValid(object? value, ValidationContext validationContext) { var (result, message) = _validator.Validate(value); if (result) { - return ValidationResult.Success; + return ValidationResult.Success!; } else { diff --git a/BackEnd/Timeline/Services/UserService.cs b/BackEnd/Timeline/Services/UserService.cs index b925742e..915c9460 100644 --- a/BackEnd/Timeline/Services/UserService.cs +++ b/BackEnd/Timeline/Services/UserService.cs @@ -17,7 +17,12 @@ namespace Timeline.Services /// /// Null means not change. /// - public record ModifyUserParams(string? Username = null, string? Password = null, string? Nickname = null); + public record ModifyUserParams + { + public string? Username { get; set; } + public string? Password { get; set; } + public string? Nickname { get; set; } + } public interface IUserService { -- cgit v1.2.3 From a033b5b1511890f09faf3cdec59763aa8618e617 Mon Sep 17 00:00:00 2001 From: crupest Date: Fri, 13 Nov 2020 16:15:48 +0800 Subject: refactor(database): Remove roles from user table. --- BackEnd/Timeline/Entities/UserEntity.cs | 3 - .../20201113081411_RemoveRolesFromUser.Designer.cs | 402 +++++++++++++++++++++ .../20201113081411_RemoveRolesFromUser.cs | 24 ++ .../Migrations/DatabaseContextModelSnapshot.cs | 5 - BackEnd/Timeline/Services/UserService.cs | 1 - 5 files changed, 426 insertions(+), 9 deletions(-) create mode 100644 BackEnd/Timeline/Migrations/20201113081411_RemoveRolesFromUser.Designer.cs create mode 100644 BackEnd/Timeline/Migrations/20201113081411_RemoveRolesFromUser.cs (limited to 'BackEnd/Timeline/Services/UserService.cs') diff --git a/BackEnd/Timeline/Entities/UserEntity.cs b/BackEnd/Timeline/Entities/UserEntity.cs index 83fa8f89..6a256a31 100644 --- a/BackEnd/Timeline/Entities/UserEntity.cs +++ b/BackEnd/Timeline/Entities/UserEntity.cs @@ -23,9 +23,6 @@ namespace Timeline.Entities [Column("password"), Required] public string Password { get; set; } = default!; - [Column("roles"), Required] - public string Roles { get; set; } = default!; - [Column("version"), Required] public long Version { get; set; } diff --git a/BackEnd/Timeline/Migrations/20201113081411_RemoveRolesFromUser.Designer.cs b/BackEnd/Timeline/Migrations/20201113081411_RemoveRolesFromUser.Designer.cs new file mode 100644 index 00000000..324738a5 --- /dev/null +++ b/BackEnd/Timeline/Migrations/20201113081411_RemoveRolesFromUser.Designer.cs @@ -0,0 +1,402 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Timeline.Entities; + +namespace Timeline.Migrations +{ + [DbContext(typeof(DatabaseContext))] + [Migration("20201113081411_RemoveRolesFromUser")] + partial class RemoveRolesFromUser + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "5.0.0"); + + modelBuilder.Entity("Timeline.Entities.DataEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasColumnName("id"); + + b.Property("Data") + .IsRequired() + .HasColumnType("BLOB") + .HasColumnName("data"); + + b.Property("Ref") + .HasColumnType("INTEGER") + .HasColumnName("ref"); + + b.Property("Tag") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnName("tag"); + + b.HasKey("Id"); + + b.HasIndex("Tag") + .IsUnique(); + + b.ToTable("data"); + }); + + modelBuilder.Entity("Timeline.Entities.JwtTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasColumnName("id"); + + b.Property("Key") + .IsRequired() + .HasColumnType("BLOB") + .HasColumnName("key"); + + b.HasKey("Id"); + + b.ToTable("jwt_token"); + }); + + modelBuilder.Entity("Timeline.Entities.TimelineEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasColumnName("id"); + + b.Property("CreateTime") + .HasColumnType("TEXT") + .HasColumnName("create_time"); + + b.Property("CurrentPostLocalId") + .HasColumnType("INTEGER") + .HasColumnName("current_post_local_id"); + + b.Property("Description") + .HasColumnType("TEXT") + .HasColumnName("description"); + + b.Property("LastModified") + .HasColumnType("TEXT") + .HasColumnName("last_modified"); + + b.Property("Name") + .HasColumnType("TEXT") + .HasColumnName("name"); + + b.Property("NameLastModified") + .HasColumnType("TEXT") + .HasColumnName("name_last_modified"); + + b.Property("OwnerId") + .HasColumnType("INTEGER") + .HasColumnName("owner"); + + b.Property("Title") + .HasColumnType("TEXT") + .HasColumnName("title"); + + b.Property("UniqueId") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnName("unique_id") + .HasDefaultValueSql("lower(hex(randomblob(16)))"); + + b.Property("Visibility") + .HasColumnType("INTEGER") + .HasColumnName("visibility"); + + b.HasKey("Id"); + + b.HasIndex("OwnerId"); + + b.ToTable("timelines"); + }); + + modelBuilder.Entity("Timeline.Entities.TimelineMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasColumnName("id"); + + b.Property("TimelineId") + .HasColumnType("INTEGER") + .HasColumnName("timeline"); + + b.Property("UserId") + .HasColumnType("INTEGER") + .HasColumnName("user"); + + b.HasKey("Id"); + + b.HasIndex("TimelineId"); + + b.HasIndex("UserId"); + + b.ToTable("timeline_members"); + }); + + modelBuilder.Entity("Timeline.Entities.TimelinePostEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasColumnName("id"); + + b.Property("AuthorId") + .HasColumnType("INTEGER") + .HasColumnName("author"); + + b.Property("Content") + .HasColumnType("TEXT") + .HasColumnName("content"); + + b.Property("ContentType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnName("content_type"); + + b.Property("ExtraContent") + .HasColumnType("TEXT") + .HasColumnName("extra_content"); + + b.Property("LastUpdated") + .HasColumnType("TEXT") + .HasColumnName("last_updated"); + + b.Property("LocalId") + .HasColumnType("INTEGER") + .HasColumnName("local_id"); + + b.Property("Time") + .HasColumnType("TEXT") + .HasColumnName("time"); + + b.Property("TimelineId") + .HasColumnType("INTEGER") + .HasColumnName("timeline"); + + b.HasKey("Id"); + + b.HasIndex("AuthorId"); + + b.HasIndex("TimelineId"); + + b.ToTable("timeline_posts"); + }); + + modelBuilder.Entity("Timeline.Entities.UserAvatarEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasColumnName("id"); + + b.Property("DataTag") + .HasColumnType("TEXT") + .HasColumnName("data_tag"); + + b.Property("LastModified") + .HasColumnType("TEXT") + .HasColumnName("last_modified"); + + b.Property("Type") + .HasColumnType("TEXT") + .HasColumnName("type"); + + b.Property("UserId") + .HasColumnType("INTEGER") + .HasColumnName("user"); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("user_avatars"); + }); + + modelBuilder.Entity("Timeline.Entities.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasColumnName("id"); + + b.Property("CreateTime") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnName("create_time") + .HasDefaultValueSql("datetime('now', 'utc')"); + + b.Property("LastModified") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnName("last_modified") + .HasDefaultValueSql("datetime('now', 'utc')"); + + b.Property("Nickname") + .HasColumnType("TEXT") + .HasColumnName("nickname"); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnName("password"); + + b.Property("UniqueId") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnName("unique_id") + .HasDefaultValueSql("lower(hex(randomblob(16)))"); + + b.Property("Username") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnName("username"); + + b.Property("UsernameChangeTime") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnName("username_change_time") + .HasDefaultValueSql("datetime('now', 'utc')"); + + b.Property("Version") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(0L) + .HasColumnName("version"); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("users"); + }); + + modelBuilder.Entity("Timeline.Entities.UserPermissionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasColumnName("id"); + + b.Property("Permission") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnName("permission"); + + b.Property("UserId") + .HasColumnType("INTEGER") + .HasColumnName("user_id"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("user_permission"); + }); + + modelBuilder.Entity("Timeline.Entities.TimelineEntity", b => + { + b.HasOne("Timeline.Entities.UserEntity", "Owner") + .WithMany("Timelines") + .HasForeignKey("OwnerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Owner"); + }); + + modelBuilder.Entity("Timeline.Entities.TimelineMemberEntity", b => + { + b.HasOne("Timeline.Entities.TimelineEntity", "Timeline") + .WithMany("Members") + .HasForeignKey("TimelineId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Timeline.Entities.UserEntity", "User") + .WithMany("TimelinesJoined") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Timeline"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Timeline.Entities.TimelinePostEntity", b => + { + b.HasOne("Timeline.Entities.UserEntity", "Author") + .WithMany("TimelinePosts") + .HasForeignKey("AuthorId"); + + b.HasOne("Timeline.Entities.TimelineEntity", "Timeline") + .WithMany("Posts") + .HasForeignKey("TimelineId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Author"); + + b.Navigation("Timeline"); + }); + + modelBuilder.Entity("Timeline.Entities.UserAvatarEntity", b => + { + b.HasOne("Timeline.Entities.UserEntity", "User") + .WithOne("Avatar") + .HasForeignKey("Timeline.Entities.UserAvatarEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Timeline.Entities.UserPermissionEntity", b => + { + b.HasOne("Timeline.Entities.UserEntity", "User") + .WithMany("Permissions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Timeline.Entities.TimelineEntity", b => + { + b.Navigation("Members"); + + b.Navigation("Posts"); + }); + + modelBuilder.Entity("Timeline.Entities.UserEntity", b => + { + b.Navigation("Avatar"); + + b.Navigation("Permissions"); + + b.Navigation("TimelinePosts"); + + b.Navigation("Timelines"); + + b.Navigation("TimelinesJoined"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/BackEnd/Timeline/Migrations/20201113081411_RemoveRolesFromUser.cs b/BackEnd/Timeline/Migrations/20201113081411_RemoveRolesFromUser.cs new file mode 100644 index 00000000..33d79b33 --- /dev/null +++ b/BackEnd/Timeline/Migrations/20201113081411_RemoveRolesFromUser.cs @@ -0,0 +1,24 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +namespace Timeline.Migrations +{ + public partial class RemoveRolesFromUser : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "roles", + table: "users"); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "roles", + table: "users", + type: "TEXT", + nullable: false, + defaultValue: ""); + } + } +} diff --git a/BackEnd/Timeline/Migrations/DatabaseContextModelSnapshot.cs b/BackEnd/Timeline/Migrations/DatabaseContextModelSnapshot.cs index 95bb0ff5..2f0f75a2 100644 --- a/BackEnd/Timeline/Migrations/DatabaseContextModelSnapshot.cs +++ b/BackEnd/Timeline/Migrations/DatabaseContextModelSnapshot.cs @@ -251,11 +251,6 @@ namespace Timeline.Migrations .HasColumnType("TEXT") .HasColumnName("password"); - b.Property("Roles") - .IsRequired() - .HasColumnType("TEXT") - .HasColumnName("roles"); - b.Property("UniqueId") .IsRequired() .ValueGeneratedOnAdd() diff --git a/BackEnd/Timeline/Services/UserService.cs b/BackEnd/Timeline/Services/UserService.cs index 915c9460..f83d2928 100644 --- a/BackEnd/Timeline/Services/UserService.cs +++ b/BackEnd/Timeline/Services/UserService.cs @@ -242,7 +242,6 @@ namespace Timeline.Services { Username = username, Password = _passwordService.HashPassword(password), - Roles = "", Version = 1 }; _databaseContext.Users.Add(newEntity); -- cgit v1.2.3