public ActionResult <UserOutDto> Register([FromBody] UserCreateDto userInDto) { //Check if given email is already used. if (_userRepository.Where(u => u.Email == userInDto.Email).Any()) { return(BadRequest(new Message("Email: " + userInDto.Email + " already exists."))); } //Check if given username is already used. if (_userRepository.Where(u => u.UserName == userInDto.UserName).Any()) { return(BadRequest(new Message("Username: "******" already exists."))); } //Check if password is valid. if (string.IsNullOrWhiteSpace(userInDto.Email)) { return(BadRequest(new Message("Email is invalid."))); } //Check if password is valid. if (string.IsNullOrWhiteSpace(userInDto.UserName)) { return(BadRequest(new Message("Username is invalid."))); } //Check if password is valid. if (string.IsNullOrWhiteSpace(userInDto.Password)) { return(BadRequest(new Message("Password is invalid."))); } UserHelpers.CreatePasswordHash(userInDto.Password, out var passwordHash, out var passwordSalt); var userIn = _mapper.Map <User>(userInDto); //Save user's password userIn.PasswordHash = passwordHash; userIn.PasswordSalt = passwordSalt; //Set user's role "User" by default. userIn.Role = Role.User; //Save user to the table if (_userRepository.Add(userIn)) { var userOutDto = _mapper.Map <UserOutDto>(userIn); return(userOutDto); } return(BadRequest(new Message("Error when creating user"))); }
public ActionResult <UserOutDto> Update(string id, [FromBody] UserUpdateDto userDto) { var userOld = _userRepository.GetById(id); if (userOld == null) { return(NotFound(new Message("No such user with this id: " + id))); } //Check if token is given by admin or authorized user var tokenUser = HttpContext.User; if (!AuthorizationHelpers.IsAdmin(tokenUser) && !AuthorizationHelpers.IsAuthorizedUser(tokenUser, id)) { return(Unauthorized(new Message("Unauthorized user."))); } if (!string.IsNullOrWhiteSpace(userDto.BirthDate)) { userOld.BirthDate = userDto.BirthDate; } if (!string.IsNullOrWhiteSpace(userDto.Description)) { userOld.Description = userDto.Description; } if (!string.IsNullOrWhiteSpace(userDto.FacebookLink)) { userOld.FacebookLink = userDto.FacebookLink; } if (!string.IsNullOrWhiteSpace(userDto.InstagramLink)) { userOld.InstagramLink = userDto.InstagramLink; } if (!string.IsNullOrWhiteSpace(userDto.LinkedinLink)) { userOld.LinkedinLink = userDto.LinkedinLink; } if (!string.IsNullOrWhiteSpace(userDto.Theme)) { userOld.Theme = userDto.Theme; } if (!string.IsNullOrWhiteSpace(userDto.TwitterLink)) { userOld.TwitterLink = userDto.TwitterLink; } if (!string.IsNullOrWhiteSpace(userDto.Password)) { UserHelpers.CreatePasswordHash(userDto.Password, out var passwordHash, out var passwordSalt); userOld.PasswordHash = passwordHash; userOld.PasswordSalt = passwordSalt; } if (_userRepository.Update(userOld)) { var userOutDto = _mapper.Map <UserOutDto>(userOld); return(userOutDto); } return(BadRequest(new Message("Error when updating user."))); }