Beispiel #1
0
        public async Task <IActionResult> Edit(int id, UserForEditDto userDto)
        {
            var user = await _dbContext.Users.FirstOrDefaultAsync(u => u.Id == id);

            if (user == null)
            {
                return(NotFound());
            }
            ViewData["userModel"] = user;
            if (ModelState.IsValid)
            {
                _mapper.Map(userDto, user);

                // Password change
                if (userDto.Password != null && await ValidatePassword(user, userDto.Password))
                {
                    await ChangeUserPassword(user, userDto.Password);
                }

                // Claims
                user.Claims.Clear();

                foreach (var claimDto in userDto.UserClaims.Where(c => c.Enabled))
                {
                    user.Claims.Add(new UserClaim(user, claimDto.Type, claimDto.Name));
                }
                await _dbContext.SaveChangesAsync();

                _flashMessage.Success($"Registo atualizado com sucesso.");

                userDto.SetEnabledClaims(user.Claims);
                return(RedirectToAction(nameof(Edit), new { user.Id }));
            }
            return(View(userDto));
        }
        public async Task <IActionResult> Update(UserForEditDto userForEdit)
        {
            if (!int.TryParse(User.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? string.Empty, out var loggedUserId))
            {
                return(Unauthorized());
            }

            var privilages = new List <int>()
            {
                (int)UserPrivileges.Administrator, (int)UserPrivileges.Employee
            };

            int.TryParse(User.FindFirst(ClaimTypes.Role)?.Value, out var privilagesId);

            if (loggedUserId != userForEdit.Id)
            {
                if (!privilages.Contains(privilagesId))
                {
                    return(StatusCode((int)HttpStatusCode.Unauthorized));
                }
            }

            var result = await _userRepository.Edit(userForEdit);

            return(result ? Ok() : StatusCode((int)HttpStatusCode.InternalServerError));
        }
Beispiel #3
0
        public async Task <User> UpdateProfile(UserForEditDto userForEditDto)
        {
            var currentUser = await Get(userForEditDto.UserId);

            if (currentUser != null)
            {
                _mapper.Map <UserForEditDto, User>(userForEditDto, currentUser);
                await _context.SaveChangesAsync();
            }

            return(currentUser);
        }
Beispiel #4
0
        public async Task <bool> SaveUser(string username, UserForEditDto user)
        {
            User existingUser = await this.GetUser(username);

            if (existingUser == null)
            {
                return(false);
            }

            _mapper.Map(user, existingUser);
            int saved = await this.Save();

            return(saved > 0);
        }
        public async Task <bool> Edit(UserForEditDto userForEdit)
        {
            var user = await GetUserById(userForEdit.Id);

            try
            {
                _mapper.Map(userForEdit, user);
                return(await Update(user));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(false);
            }
        }
Beispiel #6
0
        public async Task <IActionResult> Add(UserForEditDto model)
        {
            return(await _DbContextFactory.UseTransaction(async() =>
            {
                if (string.IsNullOrEmpty(model.Username))
                {
                    return Error(propertyKey: "username", errorMessage: "用户名不能为空");
                }

                if ((await _userService.GetUserByUsername(model.Username)) != null)
                {
                    return Error(propertyKey: "user", errorMessage: "用户名已经被其它合作伙伴注册");
                }

                var user = new User
                {
                    PartnerId = 0,
                    ParentUserId = 0,
                    UserGuid = Guid.NewGuid(),
                    Username = model.Username,
                    Password = model.Password,
                    DisplayName = model.DisplayName,
                    RealName = model.RealName,
                    Email = model.Email,
                    Mobile = model.Mobile,
                    Approved = model.Approved,
                    Deleted = false,
                    CreateTime = DateTime.Now,
                    UpdateTime = DateTime.Now,
                    LastLoginDate = null,
                };
                await _userService.InsertUser(user);

                //密码
                if (!string.IsNullOrWhiteSpace(model.Password))
                {
                    //var result = await _userService.ChangePassword(model.Username, model.Password);
                    //if (!result.success)
                    //{
                    //    return Error(propertyKey: "password", errorMessage: "用户创建成功但密码设置失败" + result.errorMessage);
                    //}
                }

                await _userService.UpdateUser(user);

                return Success(PreUserModel(user));
            }));
        }
Beispiel #7
0
        public async Task <User> UpdateUser(UserForEditDto updatedUserDto)
        {
            var user = await _authRepo.GetFirstOrDefault(u => u.Id == updatedUserDto.Id);

            if (user == null)
            {
                throw new System.ArgumentException("Unable to update user", string.Empty);
            }

            updatedUserDto.UserName = updatedUserDto.UserName.ToUpper();

            _mapper.Map(updatedUserDto, user);
            await _authRepo.SaveAsync();

            return(user);
        }
        public async Task <IActionResult> editUser(UserForEditDto userForEditDto)
        {
            var user = await _userManager.Users.FirstOrDefaultAsync(u => u.Id == userForEditDto.Id);

            _mapper.Map(userForEditDto, user);

            var roles = await _userManager.GetRolesAsync(user);

            await _userManager.RemoveFromRolesAsync(user, roles.ToArray());

            await _userManager.AddToRoleAsync(user, user.Status);

            await _repo.Save();

            return(Ok("Modified Successfully !"));
        }
        public async Task <IActionResult> EditUser(int id, UserForEditDto userForEdit)
        {
            if (id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            var userfromRepo = await this._repo.GetUser(id);

            _mapper.Map(userForEdit, userfromRepo);
            if (await _repo.SaveAll())
            {
                return(NoContent());
            }
            throw new Exception($"Updating new user {id} failed on save");
        }
Beispiel #10
0
        public async Task <IActionResult> UpdateUser(int id, UserForEditDto dto)
        {
            if (id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }
            var user = await _userRepo.GetUserById(id);

            _mapper.Map(dto, user);
            if (await _userRepo.SaveAll())
            {
                return(NoContent());
            }
            // throw new System.Exception($"Updating user {id} failed on save");
            return(BadRequest());
        }
Beispiel #11
0
        public async Task <IActionResult> EditUser(string username, UserForEditDto user)
        {
            string currentUser = User.FindFirstValue(ClaimTypes.Name);

            if (username != currentUser)
            {
                return(Unauthorized());
            }

            if (await _userRepository.SaveUser(username, user))
            {
                return(NoContent());
            }
            else
            {
                throw new System.Exception($"Could not update user {username}!");
            };
        }
Beispiel #12
0
        public async Task <IActionResult> UpdateUser(int id, UserForEditDto userForEditDto)
        {
            if (id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            var user = await _datingRepository.GetUser(id);

            _mapper.Map(userForEditDto, user);

            if (await _datingRepository.SaveAll())
            {
                return(NoContent());
            }

            throw new Exception($"Updating user {id} failed on save");
        }
Beispiel #13
0
        public async Task <IActionResult> Update(int id, UserForEditDto userEditObj)
        {
            if (id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            var userFromRepo = await _repo.GetUser(id);

            _mapper.Map(userEditObj, userFromRepo);

            if (await _repo.SaveAll())
            {
                return(NoContent());
            }

            throw new Exception("Failed to update user");
        }
Beispiel #14
0
        public async Task <IActionResult> Upload(string userId, [FromForm] UserForEditDto userForEditDto)
        {
            try
            {
                var imageUrl = _azureBlobStorageService.UploadFileToBlob(userForEditDto.File);
                var result   = await _userService.SetProfileImageUrl(userId, imageUrl);

                if (result == false)
                {
                    return(BadRequest("Failed save the image"));
                }
                Console.WriteLine($"path message: {imageUrl}");
                return(Ok());
            }
            catch (Exception ex)
            {
                return(StatusCode(500, $"Internal server error: {ex}"));
            }
        }
Beispiel #15
0
        public async Task <IActionResult> UpdateUser(int id, UserForEditDto userForEdit)
        {
            //try to edit the not logged in user
            if (id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }
            else
            {
                var user = await _repo.GetUser(id);

                var mappedUser = _mapper.Map(userForEdit, user);
                if (await _repo.SaveAll())
                {
                    return(NoContent());
                }
                throw new Exception($"updating user {id} failed on save");
            }
        }
Beispiel #16
0
        public async Task <IActionResult> UpdateUser([FromBody] UserForEditDto updatedUserDto)
        {
            var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

            //TODO add account type verification for tasks
            if (currentUserId == 0)
            {
                return(Unauthorized());
            }

            try {
                await _userService.UpdateUser(updatedUserDto);
            } catch (ArgumentException e) {
                ModelState.AddModelError("Exception", e.Message);
                return(BadRequest(ModelState));
            }

            return(Ok());
        }
Beispiel #17
0
        public async Task <IActionResult> UpdateUser(int id, UserForEditDto userForEditDto)
        {
            var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);

            if (id != int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)))
            {
                return(Unauthorized());
            }
            var userFromRepo = await datingService.GetUser(id);

            mapper.Map(userForEditDto, userFromRepo);

            if (await datingService.SaveAll())
            {
                return(NoContent());
            }

            throw new Exception($"Updating user {id} failed on save");
        }
Beispiel #18
0
        public async Task <IActionResult> EditUser(int id, UserForEditDto userForEdit)
        {
            //Checks the user id that we can from auth token
            if (id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            var userFromRepo = await _repo.GetUser(id);

            //Updates the values in user model
            _mapper.Map(userForEdit, userFromRepo);

            if (await _repo.SaveAll())
            {
                return(NoContent());
            }
            // $ in front is used for string interpolation
            throw new System.Exception($"Updating user {id} failed on save");
        }
Beispiel #19
0
        public async Task <IActionResult> Update(UserForEditDto model)
        {
            return(await _DbContextFactory.UseTransaction(async() =>
            {
                var user = await _userService.GetUserById(model.Id);
                if (user == null || user.Deleted)
                {
                    return Error(propertyKey: "user", errorMessage: "用户不能存在");
                }


                user.DisplayName = model.DisplayName;
                user.Approved = model.Approved;
                user.Email = model.Email;
                user.UpdateTime = DateTime.Now;
                user.Mobile = model.Mobile;
                user.RealName = model.RealName;
                await _userService.UpdateUser(user);

                return Success(PreUserModel(user));
            }));
        }
        public async Task <IActionResult> ChangePassword(int userId, UserForEditDto userForEditDto)
        {
            int loggedUserId;

            Int32.TryParse(User.FindFirst(ClaimTypes.NameIdentifier)?.Value, out loggedUserId);

            if (userId != loggedUserId)
            {
                return(BadRequest("You cannot modify another user's profile."));
            }

            var user = await userRepository.GetUser(userId);

            user = await authRepository.ChangePassword(user, userForEditDto.Password);

            if (await dataContext.Commit())
            {
                return(NoContent());
            }

            throw new Exception($"Changing password failed on save.");
        }
        public async Task <IActionResult> EditUser([FromBody] UserForEditDto userForEditDto)
        {
            var user = await _userManager.FindByNameAsync(userForEditDto.Email);

            if (user == null || !await _userManager.CheckPasswordAsync(user, userForEditDto.Password))
            {
                return(Unauthorized(new AuthResponseDto {
                    ErrorMessage = "Invalid Authentication"
                }));
            }
            var phoneNumber = await _userManager.GetPhoneNumberAsync(user);

            if (userForEditDto.PhoneNumber != phoneNumber)
            {
                var setPhoneResult = await _userManager.SetPhoneNumberAsync(user, userForEditDto.PhoneNumber);

                if (!setPhoneResult.Succeeded)
                {
                    return(BadRequest());
                }
            }
            if (userForEditDto.UserName != user.UserName)
            {
                user.UserName = userForEditDto.UserName;
            }
            if (userForEditDto.NewEmail != user.Email)
            {
                user.Email = userForEditDto.NewEmail;
            }

            await _userManager.UpdateAsync(user);

            await _context.SaveChangesAsync();

            return(StatusCode(200));
        }
Beispiel #22
0
        public async Task <IActionResult> UpdateUser(string uid, UserForEditDto userForEdit)
        {
            if (uid == "")
            {
                return(Unauthorized());
            }

            //Is the editor's role id greater than the userForEdit role id? Disallow - editors can only edit roles at and beneath their role
            var editorRoleId = await isValidEditor();

            if (editorRoleId == null)
            {
                return(Unauthorized());
            }

            var fromDb = await _repo.Find(x => x.UserId == uid);

            if (fromDb == null)
            {
                throw new Exception($"Failed to find user: {uid}");
            }
            var resetDate = fromDb.LockedOutEnd;

            // now get the role
            var fromDbRole = await _userRole.Find(x => x.UserId == fromDb.UserId);

            if (fromDbRole == null)
            {
                throw new Exception($"Failed to find data for user: {uid}");
            }

            var fromDbRoleId = await _role.Find(x => x.RoleId == fromDbRole.RoleId);

            if (fromDbRoleId == null)
            {
                throw new Exception("Missing data");
            }

            if (editorRoleId.Id > fromDbRoleId.Id)
            {
                return(Unauthorized());
            }

            //map to supplied
            _mapper.Map(userForEdit, fromDb);

            // if account being unlocked then reset accessFailedCount to 0
            if (resetDate != fromDb.LockedOutEnd && fromDb.LockedOutEnd.Year == 1900)
            {
                fromDb.AccessFailedCount = 0;
            }

            var success = await _repo.SaveAll();

            // change the role also if not the same
            if (fromDbRole != null && userForEdit.RoleCode != fromDbRole.RoleId)
            {
                fromDbRole.RoleId = userForEdit.RoleCode;
                if (!await _userRole.SaveAll())
                {
                    return(BadRequest($"Failed to update user role for user {uid} from '{userForEdit.RoleCode}' to '{fromDbRole.RoleId}'"));
                    // throw new Exception($"Failed to update user role for user {uid} from '{userForEdit.RoleCode}' to '{fromDbRole.RoleId}'");
                }
                success = true;
            }

            if (!success)
            {
                return(BadRequest($"Failed to complete update on user {uid}"));
                // throw new Exception($"Failed to complete update on user {uid}");
            }
            return(NoContent());
        }
        public IActionResult Update([FromBody] UserForEditDto userForEditDto)
        {
            /*var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);
             * if (currentUserId == userForEditDto.Id)
             * {
             *
             * }*/


            User user = _userDal.GetUserById(userForEditDto.Id);

            if (userForEditDto.NameSurname != "" && userForEditDto.PhoneNumber != "" && userForEditDto.Email != "")
            {
                user.Email       = userForEditDto.Email;
                user.NameSurname = userForEditDto.NameSurname;
                user.PhoneNumber = userForEditDto.PhoneNumber;


                _userDal.Update(user);
                return(new StatusCodeResult(201));

                /*
                 * byte[] passwordHash, passwordSalt;
                 * authRepository.CreatePasswordHash(userForEditDto.Password, out passwordHash, out passwordSalt);
                 * user.PasswordHash = passwordHash;
                 * user.PasswordSalt = passwordSalt;*/
            }
            else
            {
                return(Ok("Empty properties!!!"));
            }

            //_userDal.Update(user);

            /*try
             * {
             *  var currentUserId= int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);
             * if(currentUserId== userForEditDto.Id)
             *  {
             *      User user = new User();
             *      UsersContext usersContext = new UsersContext();
             *      AuthRepository authRepository = new AuthRepository(usersContext);
             *      byte[] passwordHash, passwordSalt;
             *      user.Email = userForEditDto.Email;
             *      user.NameSurname = userForEditDto.NameSurname;
             *      user.PhoneNumber = userForEditDto.PhoneNumber;
             *
             *
             *      authRepository.CreatePasswordHash(userForEditDto.password, out passwordHash, out passwordSalt);
             *      user.PasswordHash = passwordHash;
             *      user.PasswordSalt = passwordSalt;
             *      _userDal.Update(user);
             *      return new StatusCodeResult(201);
             *  }
             *  else
             *  {
             *      return NotFound(404);
             *  }
             *
             * }
             * catch
             * { }
             * return BadRequest();*/
        }