public async Task <IActionResult> CreateUser([FromBody] UserForCreationDto user) { try { if (user == null) { return(BadRequest("Owner object is null")); } if (!ModelState.IsValid) { return(BadRequest("Invalid model object")); } var userEntity = _mapper.Map <User>(user); _repository.User.CreateUser(userEntity); await _repository.SaveAsync(); var createdUser = _mapper.Map <UserDto>(userEntity); return(CreatedAtRoute("UserById", new { id = createdUser.UserId }, createdUser)); } catch (Exception ex) { return(StatusCode(500, "Internal server error")); } }
public async Task <IActionResult> CreateUser([FromBody] int officeId) { if (await _userRepository.EmailExistsAsync(User.Identity.Name)) { ModelState.AddModelError( "Email", "The provided email is already registered"); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var userName = User.Claims.Where(c => c.Type == "name").Select(c => c.Value).FirstOrDefault(); var user = new UserForCreationDto() { FullName = userName + " " + userName, Email = User.Identity.Name, OfficeId = officeId, RoleId = 1 }; var newUserEntity = _mapper.Map <User>(user); _userRepository.CreateUser(newUserEntity); await _userRepository.SaveAsync(); var createdUser = await _userRepository.GetUserAsync(User.Identity.Name); return(CreatedAtRoute( "GetUser", new { id = newUserEntity.Id }, _mapper.Map <UserDto>(createdUser))); }
public UserDto Create(UserForCreationDto userForCreation) { try { if (userForCreation.name == "" || userForCreation.password == "" || userForCreation.right_id == 0) { _logger.LogError("invalid user data"); return(null); } User userCheck = _repository.GetUserByLogin(userForCreation.username, ""); if (userCheck != null) { _logger.LogError("Username is already in use"); return(null); } Hasher hasher = new Hasher(); userForCreation.password = hasher.HashPassword(userForCreation.password); var DataEntity = _mapper.Map <User>(userForCreation); _repository.Create(DataEntity); _repository.Save(); return(GetById(DataEntity.id)); } catch (Exception ex) { _logger.LogError($"Something went wrong inside CreateUser action: {ex.Message}"); throw new Exception(); } }
public IActionResult CreateUser([FromBody] UserForCreationDto user) { try { if (user == null) { _logger.LogError("User object sent from client is null"); return(BadRequest("User object is null")); } if (!ModelState.IsValid) { _logger.LogError("Invalid user object sent from client"); return(BadRequest("Invalid model object")); } var userEntity = _mapper.Map <User>(user); _repository.User.CreateUser(userEntity); _repository.Save(); var createdUser = _mapper.Map <UserDto>(userEntity); return(CreatedAtRoute("UserById", new { id = createdUser.Id }, createdUser)); } catch (Exception ex) { _logger.LogError($"Something went wrong inside CreateUser action: {ex.Message}"); return(StatusCode(500, "Internal server error")); } }
public async Task <ActionResult <UserDto> > Register(UserForCreationDto user) { try { if (await _usersRepository.IsEmailTaken(user.Email)) { return(Conflict()); } var newUser = _mapper.Map <User>(user); newUser.Password = Hash.GetHash(user.Password); _dbRepository.Add(newUser); if (await _dbRepository.SaveChangesAsync()) { return(CreatedAtAction(nameof(GetUser), new { userId = newUser.Id }, _mapper.Map <UserDto>(newUser))); } } catch (Exception) { return(StatusCode(StatusCodes.Status500InternalServerError, "Database Failure")); } return(BadRequest()); }
public IActionResult AddUser( [FromBody] UserForCreationDto userForCreation) { try { logger.LogInformation("Add User " + userForCreation.ToString()); if (userForCreation == null || !ModelState.IsValid) { return(BadRequest("User not valid")); } if (userServices.UserExists(userForCreation.Email)) { return(BadRequest("User already exists in the system")); } var userEntity = Mapper.Map <User>(userForCreation); User user = userServices.AddUser(userEntity); if (!userServices.Save()) { return(StatusCode(500, "A problem happened with handling your request.")); } return(Ok(user)); } catch (Exception e) { logger.LogError(e.Message); return(StatusCode(500, "A problem happened with handling your request.")); } }
public async Task <Guid> CreateAsync(UserForCreationDto creationDto) { UserEntity newUser = Activator.CreateInstance <UserEntity>(); newUser.IsActive = true; foreach (PropertyInfo propertyInfo in creationDto.GetType().GetProperties()) { if (newUser.GetType().GetProperty(propertyInfo.Name) != null) { newUser.GetType().GetProperty(propertyInfo.Name).SetValue(newUser, propertyInfo.GetValue(creationDto, null)); } } newUser.UserName = creationDto.Email; await _userManager.CreateAsync(newUser, creationDto.Password); foreach (string roleName in creationDto.RoleNames) { await _userManager.AddToRoleAsync(newUser, roleName); } await _userManager.UpdateAsync(newUser); return(newUser.Id); }
public IActionResult Register([FromBody] UserForCreationDto userForCreationDto) { if (!ModelState.IsValid) { // return 422 return(new Helpers.UnprocessableEntityObjectResult(ModelState)); } // map dto to entity var user = _mapper.Map <User>(userForCreationDto); try { // save var userFromRepo = _userRepository.Create(user, userForCreationDto.Password); var userToReturn = _mapper.Map <UserDto>(userFromRepo); return(Ok(userToReturn)); } catch (AppException ex) { // return error message if there was an exception return(BadRequest(new { message = ex.Message })); } }
public async Task InsertDelete_SingleUser_ReturnsNoContent() { // arrange var userForCreationDto = new UserForCreationDto() { FirstName = "Markus", LastName = "Christen", Email = "*****@*****.**", Biography = "this is a test", DegreeProgram = "Testing", StartDate = "HS20" }; var postRequest = CreateHttpRequest(HttpMethod.Post, "/users/", userForCreationDto); // act var postResponse = await Client.SendAsync(postRequest); var userDto = await GetRequestData <UserDto>(postResponse); // assert Assert.Equal(HttpStatusCode.Created, postResponse.StatusCode); Assert.Equal(userForCreationDto.FirstName, userDto.FirstName); // arrange var query = postResponse.Headers.Location.PathAndQuery; var deleteRequest = CreateHttpRequest(HttpMethod.Delete, query); // act var deleteResponse = await Client.SendAsync(deleteRequest); deleteResponse.EnsureSuccessStatusCode(); // assert Assert.Equal(HttpStatusCode.OK, deleteResponse.StatusCode); }
//[RequestHeaderMatchesMediaType("Accept", new[] {"..."} )] public ActionResult CreateUser([FromBody] UserForCreationDto user) { if (user == null) { return(BadRequest()); } var userEntity = _mapper.Map <User>(user); _usersRepository.AddUser(userEntity); if (!_usersRepository.Save()) { throw new Exception("Creating a user failed on save."); } var userToReturn = _mapper.Map <UserDto>(userEntity); var links = CreateLinksForUser(userToReturn.Id, null); var linkedResourceToReturn = userToReturn.ShapeData(null) as IDictionary <string, object>; linkedResourceToReturn.Add("links", links); return(CreatedAtRoute("GetUser", new { id = linkedResourceToReturn["Id"] }, linkedResourceToReturn)); }
public User AddUser(UserForCreationDto userForCreation) { // copy to save photo string newName = GetImageName(); string desFile = GetFullPath(newName); try { File.Copy(userForCreation.Photo, desFile, true); } catch { System.Windows.MessageBox.Show("Đã xảy ra lỗi khi lưu file!"); return(null); } // save user var newUser = Mapper.Map <User>(userForCreation); newUser.Photo = newName; var role = _roleRepository.GetRoleByName(userForCreation.Role); newUser.RoleId = role.Id; return(_userRepository.Create(newUser)); }
public IActionResult CreateUser([FromBody] UserForCreationDto userDto) { if (userDto == null) { return(BadRequest()); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } try { var userEntity = Mapper.Map <User>(userDto); _registrationRepository.AddUser(userEntity); if (!_registrationRepository.Save()) { return(StatusCode(500, "A problem happened while handling your request.")); } var createdUserToReturn = Mapper.Map <UserWithRolesDto>(userEntity); return(CreatedAtRoute("GetUser", new { subscriberId = createdUserToReturn.SubscriberId }, createdUserToReturn)); } catch (DbUpdateException ex) { if (ex.InnerException is SqlException innerException && innerException.Number == 2601) { return(BadRequest("Subscriber ID already exists - Duplicate Subscriber ID")); }
public IActionResult AddUser([FromBody] UserForCreationDto newUser) { if (newUser == null) { return(BadRequest("unserializable")); } var validator = new UserForCreationDtoValidator(); ValidationResult results = validator.Validate(newUser); if (!results.IsValid) { return(BadRequest(results)); } if (_immersiveRepo.UsernameExists(newUser.Username)) { return(BadRequest("this username already exists")); } newUser.Salt = _passHasher.GenerateSalt(); newUser.PassHash = _passHasher.HashPassword(newUser.Password, newUser.Salt); User toWriteUser = Mapper.Map <User>(newUser); _immersiveRepo.AddUser(toWriteUser); return(NoContent()); }
public async Task <IActionResult> CreateUser( [FromBody] UserForCreationDto userForCreation) { if (userForCreation == null) { ModelState.AddModelError("Message", "Unable to locate payload for new request"); return(BadRequest(ModelState)); } var command = new AddUserCommand(userForCreation.FirstName, userForCreation.LastName, userForCreation.Email, userForCreation.UserName, userForCreation.Password, userForCreation.ConfirmPassword, userForCreation.Roles, userForCreation.Facilities); _logger.LogInformation( "----- Sending command: AddUserCommand - {userName}", command.UserName); var commandResult = await _mediator.Send(command); if (commandResult == null) { return(BadRequest("Command not created")); } return(CreatedAtAction("GetUserByIdentifier", new { id = commandResult.Id }, commandResult)); }
public IActionResult login([FromBody] UserForCreationDto user) { try { if (user == null) { _logger.LogError("User object sent from client is null."); return(BadRequest("User object is null")); } if (!ModelState.IsValid) { _logger.LogError("Invalid user object sent from client."); return(BadRequest("Invalid model object")); } var userEntity = _mapper.Map <User>(user); var result = connector.Login(userEntity); return(Ok(result)); } catch (Exception ex) { _logger.LogError($"Something went wrong inside CreateUser action: {ex.Message}"); return(StatusCode(500, "Internal server error")); } }
public IActionResult CreateUser([FromBody] UserForCreationDto user) { if (user == null) { return(BadRequest()); } if (!ModelState.IsValid) { return(BadRequest()); } var userToAdd = Mapper.Map <Entities.User>(user); //If AddUser method false, username exists if (!_messangerRepository.AddUser(userToAdd)) { return(BadRequest()); } //If false, there were problem with saving to database if (!_messangerRepository.Save()) { return(StatusCode(500, "Server error")); } return(Ok()); }
public async Task <IActionResult> CreateUser(UserForCreationDto userForCreationDto) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (!userForCreationDto.Password.Equals(userForCreationDto.ConfirmedPassword)) { return(BadRequest("Password is not equal to confirmedPassword")); } var user = _mapper.Map <User>(userForCreationDto); user.Id = Guid.NewGuid(); _repositoryWrapper.User.Create(user); if (!await _repositoryWrapper.User.SaveAsync()) { throw new Exception("Create User Failed."); } var userDto = _mapper.Map <UserDto>(user); return(CreatedAtRoute(nameof(GetUserAsync), new { userId = user.Id }, userDto)); }
public IActionResult CreateUser([FromBody] UserForCreationDto user) { try { if (user == null) { _logger.LogError("User object sent from client is null."); return(BadRequest("User object is null")); } if (!ModelState.IsValid) { _logger.LogError("Invalid User object sent from client."); return(BadRequest("Invalid model object")); } UserDto userDto = _userLogic.Create(user); if (userDto == null) { return(Problem("Username already exists")); } return(GetUserById(userDto.id)); } catch (Exception ex) { return(StatusCode(500, "Internal server error")); } }
public async Task <IActionResult> Register([FromBody] UserForCreationDto newUser) { var userToAdd = new TestUser { SubjectId = Guid.NewGuid().ToString(), Username = newUser.Username, Password = newUser.Password, Claims = new List <Claim> { new Claim(JwtClaimTypes.Email, newUser.Email), new Claim(JwtClaimTypes.Role, "user") } }; var newIdentityUser = new IdentityUser(newUser.Username) { Id = userToAdd.SubjectId }; foreach (var claim in userToAdd.Claims) { newIdentityUser.Claims.Add(new IdentityUserClaim <string> { UserId = newIdentityUser.Id, ClaimType = claim.Type, ClaimValue = claim.Value, }); } var a = await _userManager.CreateAsync(newIdentityUser, newUser.Password); if (!a.Succeeded) { return(BadRequest(a)); } return(NoContent()); }
public IActionResult CreateUserForOrganization(Guid orgId, [FromBody] UserForCreationDto user) { if (user == null) { _logger.LogError("UserForCreationDto object sent from client is null."); return(BadRequest("UserForCreationDto object is null")); } // var organization = _repository.Company.GetCompany(companyId, trackChanges: false); var organization = _repository.Organization.GetOrganization(orgId, trackChanges: false); if (organization == null) { _logger.LogInfo($"Organization with id: {orgId} doesn't exist in the database."); return(NotFound()); } var userEntity = _mapper.Map <User>(user); // _repository.Employee.CreateEmployeeForCompany(companyId, employeeEntity); _repository.User.CreateUserForOrganization(orgId, userEntity); _repository.Save(); var userToReturn = _mapper.Map <UserDto>(userEntity); return(CreatedAtRoute("GetUserForOrganization", new { orgId, id = userToReturn.Id }, userToReturn)); // return CreatedAtRoute( new { orgId, id = userToReturn.Id }, userToReturn); }
public async Task <IActionResult> Register([FromBody] UserForCreationDto request) { if (await _unitOfWork.userService.EmailExists(request.Email)) { return(BadRequest("Email has already been taken!")); } var userEntity = Mapper.Map <AppUser>(request); var user = _unitOfWork.userService.Register(userEntity); Console.WriteLine("user: "******"Something went wrong")); } }
public IActionResult CreateUser([FromBody] UserForCreationDto user) { try { if (user == null) { return(BadRequest("User object is null")); } if (!ModelState.IsValid) { return(BadRequest("Invalid model object")); } var userEntity = _mapper.Map <User>(user); userEntity.DateUpdatePassword = DateTime.Now; userEntity.DateValidityPassword = DateTime.Now.AddMonths(3); userEntity.State = true; _repository.User.CreateUser(userEntity); _repository.Save(); var createdUser = _mapper.Map <UserDto>(userEntity); return(CreatedAtRoute("UserById", new { userId = createdUser.UserId }, createdUser)); } catch (Exception ex) { return(StatusCode(500, $"Internal server error: {ex.Message}")); } }
public SignUpRequest CreateSignUpRequestFromUserDto(UserForCreationDto user) { var signUpRequest = new SignUpRequest { ClientId = _settings.Value.UserPoolClientId, Password = user.Password, Username = user.UserName, }; var emailAttribute = new AttributeType { Name = "email", Value = user.Email }; var firstNameAttr = new AttributeType { Name = "given_name", Value = user.FirstName }; var lastName = new AttributeType { Name = "family_name", Value = user.LastName }; signUpRequest.UserAttributes.Add(emailAttribute); signUpRequest.UserAttributes.Add(firstNameAttr); signUpRequest.UserAttributes.Add(lastName); return(signUpRequest); }
public IActionResult Register([FromBody] UserForCreationDto userDto) { if (userDto == null) { return(BadRequest()); } if (!ModelState.IsValid) { // return 422 return(new UnprocessableEntityObjectResult(ModelState)); } try { // map dto to entity var user = Mapper.Map <User>(userDto); // save _userService.Create(user, userDto.Password); var userToReturn = Mapper.Map <UserDto>(user); return(CreatedAtRoute("GetUserById", new { id = userToReturn.Id }, userToReturn)); } catch (AppException ex) { // return error message if there was an exception _logger.LogInformation(100, ex.ToString()); return(BadRequest()); } }
public async Task <IActionResult> Login([FromBody] UserForCreationDto user) { try { var existUser = await _userManager.FindByNameAsync(user.UserName); if (existUser != null && await _userManager.CheckPasswordAsync(existUser, user.Password)) { var tokenDescriptor = new SecurityTokenDescriptor() { Subject = new ClaimsIdentity(new Claim[] { new Claim("userId", existUser.Id), }), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.GetValue <string>("ApplicationSettings:JWT_Secret"))), SecurityAlgorithms.HmacSha256) }; var tokenHandler = new JwtSecurityTokenHandler(); var securityToken = tokenHandler.CreateToken(tokenDescriptor); var token = tokenHandler.WriteToken(securityToken); return(Ok(new { token })); } else { return(BadRequest(new { message = "Email or password is incorrect!" })); } } catch (Exception e) { return(StatusCode(500, e)); } }
public async Task InsertDelete_SingleStudyGroup_ReturnsNoContent() { // arrange var userForCreationDto = new UserForCreationDto() { FirstName = "Markus", LastName = "Christen", Email = "*****@*****.**", Biography = "this is a test", DegreeProgram = "Testing", StartDate = "HS20" }; var postRequestUser = CreateHttpRequest(HttpMethod.Post, "/users/", userForCreationDto); var postResponseUser = await Client.SendAsync(postRequestUser); try { var studyGroupForCreationDto = new StudyGroupForCreationDto() { Purpose = "Test study group", ModuleId = -1 }; var postRequestStudyGroup = CreateHttpRequest(HttpMethod.Post, "/studygroups/", studyGroupForCreationDto); // act var postResponseStudyGroup = await Client.SendAsync(postRequestStudyGroup); var fetchedStudyGroup = await GetRequestData <StudyGroupDto>(postResponseStudyGroup); // assert Assert.Equal(HttpStatusCode.Created, postResponseStudyGroup.StatusCode); Assert.Equal(studyGroupForCreationDto.Purpose, fetchedStudyGroup.Purpose); Assert.NotNull(fetchedStudyGroup.Module); Assert.NotNull(fetchedStudyGroup.User); // arrange var queryForStudyGroup = postResponseStudyGroup.Headers.Location.PathAndQuery; var deleteRequestStudyGroup = CreateHttpRequest(HttpMethod.Delete, queryForStudyGroup); // act var deleteResponseStudyGroup = await Client.SendAsync(deleteRequestStudyGroup); // assert Assert.Equal(HttpStatusCode.OK, deleteResponseStudyGroup.StatusCode); } finally { // clean up var queryForUser = postResponseUser.Headers.Location.PathAndQuery; var deleteRequestUser = CreateHttpRequest(HttpMethod.Delete, queryForUser); var deleteResponseUser = await Client.SendAsync(deleteRequestUser); deleteResponseUser.EnsureSuccessStatusCode(); } }
public async Task <Object> NewDeliveryMan([FromBody] UserForCreationDto newDeliveryMan) { var identityUser = new IdentityUser { Email = newDeliveryMan.Email, UserName = newDeliveryMan.Email }; if (await _userManager.FindByEmailAsync(newDeliveryMan.Email) != null) { return(BadRequest(new { code = "DuplicatedEmail", message = "Cette adresse email est déjà utilisée." })); } try { var result = await _userManager.CreateAsync(identityUser, newDeliveryMan.Password); if (result.Succeeded) { IdentityUser user = _userManager.Users.Where(u => u.Email == newDeliveryMan.Email).FirstOrDefault(); //Insert in the table location var location = locationService.AddLocation(newDeliveryMan.Location); //Transform the image base64 String ImageModel uploadedImage = FileUploader.Base64ToImage(newDeliveryMan.ImageBase64String, "DeliveryMenPictures"); //Create the client entity var entityDeliveryMan = new DeliveryMan { IdentityId = user.Id, Email = newDeliveryMan.Email, FirstName = newDeliveryMan.FirstName, LastName = newDeliveryMan.LastName, Phone = newDeliveryMan.Phone, DateOfBirth = newDeliveryMan.DateOfBirth, ImageBase64 = uploadedImage.ImageBytes, PicturePath = uploadedImage.Path, Location = location, HasValidatedEmail = false, IsValidated = false }; //Insert the new user in the DB var addedDeliveryMan = deliveryMenService.AddDeliveryMan(entityDeliveryMan); //Send the verification email var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); SendVerificationEmail(addedDeliveryMan, user.Id, code); } return(Ok(result)); } catch (Exception ex) { throw ex; } }
public async Task <ActionResult <UserDto> > PostUserAsync(UserForCreationDto newUser) { var user = await _userService.AddNewUserAsync(_mapper.Map <User>(newUser)); return(CreatedAtRoute("GetUser", new { user.Id }, _mapper.Map <UserDto>(user))); }
public IActionResult login([FromBody] UserForCreationDto user) { try { if (user == null) { _logger.LogError("User object sent from client is null."); return(BadRequest("User object is null")); } if (!ModelState.IsValid) { _logger.LogError("Invalid user object sent from client."); return(BadRequest("Invalid model object")); } var userEntity = _repository.User.GetUserWithDetails(user.username, user.password); if (userEntity == null) { _logger.LogError("Invalid user credentials sent from client."); return(BadRequest("Invalid user credentials")); } var valEntity = _repository.Validation.GetvalidationByUser(userEntity.id); if (valEntity == null) { Validation val = new Validation(); val.userId = userEntity.id; val.Creation_date = DateTime.Now; val.expiration_date = val.Creation_date.AddMinutes(30); _repository.Validation.CreateValidation(val); _repository.Save(); var createdVal = _mapper.Map <ValidationDto>(val); createdVal.user = new UserForTransfer(); createdVal.user.id = userEntity.id; createdVal.user.username = userEntity.username; return(Ok(createdVal)); } valEntity.user = new UserForTransfer(); valEntity.user.id = userEntity.id; valEntity.user.username = userEntity.username; return(Ok(valEntity)); } catch (Exception ex) { _logger.LogError($"Something went wrong inside login action: {ex.Message}"); return(StatusCode(500, "Internal server error")); } }
public IActionResult GreateNewUser(UserForCreationDto userDto) { var user = _mapper.Map <User>(userDto); _wrapper.User.Create(user); _wrapper.Save(); userDto = _mapper.Map <UserForCreationDto>(user); return(CreatedAtRoute(new { userDto }, userDto)); }