From 5a8c7d92216bb7fafc649056a00c11682b82a279 Mon Sep 17 00:00:00 2001 From: transtrike Date: Sun, 31 Jan 2021 13:38:15 +0200 Subject: Fixed NullReference in cloud, CommentEditingWebModel, PromotionToAdmin, Posts violate key in db --- src/DevHive.Services/Services/UserService.cs | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) (limited to 'src/DevHive.Services/Services') diff --git a/src/DevHive.Services/Services/UserService.cs b/src/DevHive.Services/Services/UserService.cs index c2c42e0..c8624ee 100644 --- a/src/DevHive.Services/Services/UserService.cs +++ b/src/DevHive.Services/Services/UserService.cs @@ -241,7 +241,7 @@ namespace DevHive.Services.Services User newUser = await this._userRepository.GetByIdAsync(userId); - return new TokenModel(WriteJWTSecurityToken(newUser.Id, newUser.UserName, newUser.Roles); + return new TokenModel(WriteJWTSecurityToken(newUser.Id, newUser.UserName, newUser.Roles)); } private async Task PopulateModel(UpdateUserServiceModel updateUserServiceModel) @@ -249,16 +249,25 @@ namespace DevHive.Services.Services User user = this._userMapper.Map(updateUserServiceModel); /* Fetch Roles and replace model's*/ - HashSet roles = new(); - int rolesCount = updateUserServiceModel.Roles.Count; - for (int i = 0; i < rolesCount; i++) + //Do NOT allow a user to change his roles, unless he is an Admin + bool isAdmin = (await this._userRepository.GetByIdAsync(updateUserServiceModel.Id)) + .Roles.Any(r => r.Name == Role.AdminRole); + + if (isAdmin) { - Role role = await this._roleRepository.GetByNameAsync(updateUserServiceModel.Roles.ElementAt(i).Name) ?? - throw new ArgumentException("Invalid role name!"); + HashSet roles = new(); + foreach (var role in updateUserServiceModel.Roles) + { + Role returnedRole = await this._roleRepository.GetByNameAsync(role.Name) ?? + throw new ArgumentException($"Role {role.Name} does not exist!"); - roles.Add(role); + roles.Add(returnedRole); + } + user.Roles = roles; } - user.Roles = roles; + //Preserve original user roles + else + user.Roles = (await this._userRepository.GetByIdAsync(updateUserServiceModel.Id)).Roles; /* Fetch Friends and replace model's*/ HashSet friends = new(); -- cgit v1.2.3