public void Registration_RegisterNewUserToEmptyDataBase() { var(repoMock, controller, authOption) = GetDefalt(); ApplicationUser createdUser = null; string UsedPassword = null; repoMock .Setup(R => R.CreateUserAsync(It.IsAny <ApplicationUser>(), It.IsAny <string>())) .Callback <ApplicationUser, string>((U, P) => (createdUser, UsedPassword) = (U, P)) .Returns(Task.FromResult(IdentityResult.Success)); var registerModel = new RegisterModel.InputModel() { Email = "*****@*****.**", Password = "******", ConfirmPassword = "******", Sex = true, Name = "Тест", Surname = "Тестеров", PhoneNumber = "+78885553535", Birthday = "25/03/1995" }; var result = controller.Registration(registerModel).Result; Assert.AreEqual(StatusCode.OK, result.StatusCode); repoMock.Verify(R => R.CreateUserAsync(It.IsAny <ApplicationUser>(), It.IsAny <string>()), Times.Once); Assert.AreEqual(registerModel.Email, createdUser.Email); Assert.AreEqual(registerModel.Password, UsedPassword); Assert.AreNotEqual(registerModel.Password, createdUser.PasswordHash); Assert.AreEqual(registerModel.Sex, createdUser.Sex); Assert.AreEqual(registerModel.Name, createdUser.Name); Assert.AreEqual(registerModel.Surname, createdUser.Surname); Assert.AreEqual(registerModel.PhoneNumber, createdUser.PhoneNumber); Assert.AreEqual(registerModel.ParsedBirthday(), createdUser.Birthday); }
public async Task <IActionResult> Register([FromBody] RegisterModel.InputModel model) { if (model == null || String.IsNullOrEmpty(model.Password) || String.IsNullOrEmpty(model.ConfirmPassword) || String.IsNullOrEmpty(model.Email)) { return(BadRequest()); } if (model.Password != model.ConfirmPassword) { return(Json(new { IsError = true, Error = "Введённые пароли не совпадают" })); } var identityUser = new IdentityUser { UserName = model.Email }; var identityResults = await _signInManager.UserManager.CreateAsync(identityUser, model.Password); if (!identityResults.Succeeded) { return(Json(new { IsError = true, Error = "При создании нового пользователя произошла ошибка. Убедитесь, что выбранный вами пароль содержит не менее 6 символов" })); } return(Json(new { IsError = false })); }
protected override ValidationResult IsValid(object value, ValidationContext validationContext) { RegisterModel.InputModel model = (RegisterModel.InputModel)validationContext.ObjectInstance; if (model.AdminKey != AdminKey) { return(new ValidationResult("The admin key isn't correct.")); } return(ValidationResult.Success); }
public override void SetGegevensWerkgever(RegisterModel.InputModel input) { Achternaam = input.Achternaam; Voornaam = input.Voornaam; Geboortedatum = input.Geboortedatum; Gsm = input.GsmNummer; Geslacht = input.Geslacht; Nationaliteit = input.Nationaliteit; Gemeente = input.Gemeente; Postcode = input.Postcode; Straat = input.Straat; Huisnummer = input.Huisnummer; this.Email = input.Email; this.UserName = input.Email; OrganisatieNaam = input.OrganisatieNaam; BtwNummer = input.Btwnummer; }
public async Task <Doctor> RegisterDoctorAsync(RegisterModel.InputModel model, int userId) { try { Doctor doc = new Doctor(); doc.Birthday = model.Birthday; doc.Firstname = model.Firstname; doc.Lastname = model.Lastname; doc.Birthday = model.Birthday; doc.UserId = userId; doc.State = UserStates.Deactive; Address address = new Address(); address.Country = address.City = address.Line1 = address.Line2 = address.Neighborhood = string.Empty; using (var transaction = await _context.Database.BeginTransactionAsync()) { try { await _context.Addresses.AddAsync(address); await _context.SaveChangesAsync(); doc.Address = address; await _context.Doctors.AddAsync(doc); await _context.SaveChangesAsync(); await AssignRoleToUser(userId, PharmacyRoles.Doctor); transaction.Commit(); } catch (Exception innerEx) { transaction.Rollback(); throw innerEx; } } return(doc); } catch (Exception ex) { throw ex; } }
public async Task <Employee> RegisterEmployeeAsync(RegisterModel.InputModel model, int userId) { try { Employee emp = new Employee(); emp.Birthday = model.Birthday; emp.Firstname = model.Firstname; emp.Lastname = model.Lastname; emp.Birthday = model.Birthday; emp.UserId = userId; emp.State = UserStates.Deactive; Address address = new Address(); address.Country = address.City = address.Line1 = address.Line2 = address.Neighborhood = string.Empty; using (var transaction = await _context.Database.BeginTransactionAsync()) { try { await _context.Addresses.AddAsync(address); await _context.SaveChangesAsync(); emp.Address = address; await _context.Employees.AddAsync(emp); await _context.SaveChangesAsync(); await AssignRoleToUser(userId, PharmacyRoles.Employee); transaction.Commit(); } catch (Exception innerEx) { transaction.Rollback(); throw innerEx; } } return(emp); } catch (Exception ex) { throw ex; } }
public async Task <Patient> RegisterPatientAsync(RegisterModel.InputModel model, int userId) { try { Patient patient = new Patient(); patient.Birthday = model.Birthday; patient.Firstname = model.Firstname; patient.Lastname = model.Lastname; patient.Birthday = model.Birthday; patient.UserId = userId; Address address = new Address(); address.Country = address.City = address.Line1 = address.Line2 = address.Neighborhood = string.Empty; using (var transaction = await _context.Database.BeginTransactionAsync()) { try { await _context.Addresses.AddAsync(address); await _context.SaveChangesAsync(); patient.Address = address; await _context.Patients.AddAsync(patient); await _context.SaveChangesAsync(); await AssignRoleToUser(userId, PharmacyRoles.Patient); transaction.Commit(); } catch (Exception innerEx) { transaction.Rollback(); throw innerEx; } } return(patient); } catch (Exception ex) { throw ex; } }
public async Task <IActionResult> OnPostAsync([FromBody] RegisterModel.InputModel input) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = input.Email, Email = input.Email, StartDate = DateTime.Now, Cash = 1000000 }; var result = await _userManager.CreateAsync(user, input.Password); if (result.Succeeded) { return(Ok()); } else { return(BadRequest(new { status = 400, detail = "This email adress has been registered" })); } } return(BadRequest(new { status = 400, detail = "Input data is not valid" })); }
public async Task <ResponseBase> Registration([FromBody] RegisterModel.InputModel model) { if (ModelState.IsValid) { await CheckRegistrationsArgs(model); var user = new ApplicationUser { UserName = model.Email, Email = model.Email, Name = model.Name, Surname = model.Surname, PhoneNumber = model.PhoneNumber, Sex = model.Sex, Birthday = model.ParsedBirthday() }; var result = await repository.CreateUserAsync(user, model.Password); if (result.Succeeded) { // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713 // Send an email with this link //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); //var callbackUrl = Url.Action(nameof(ConfirmEmail), "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme); //await _emailSender.SendEmailAsync(model.Email, "Confirm your account", // $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>"); logger.LogInformation(3, "User created a new account with password."); return(ResponseBase.OKResponse); } logger.LogWarning(string.Join(" ", result.Errors.Select(E => $"{E.Code}---{E.Description}"))); logger.LogWarning("Model valid but error"); logger.LogWarning(JsonConvert.SerializeObject(ModelState, Formatting.Indented)); logger.LogWarning(JsonConvert.SerializeObject(model, Formatting.Indented)); } //ModelState. logger.LogWarning("Model not valid"); logger.LogWarning(JsonConvert.SerializeObject(ModelState, Formatting.Indented)); logger.LogWarning(JsonConvert.SerializeObject(model, Formatting.Indented)); throw new ArgumentException(); }
public async Task <IActionResult> OnPostAsync([FromBody] RegisterModel.InputModel input) { var user = new ApplicationUser { UserName = input.Email.ToLower(), Email = input.Email }; var result = await _userManager.CreateAsync(user, input.Password); var errorList = new List <string>(); if (result.Succeeded) { return(Ok(new { status = 200, title = "Registered successfully." })); } foreach (IdentityError error in result.Errors) { errorList.Add(error.Description); } return(BadRequest(new { status = 400, errors = errorList })); }
public async Task OnRegister_WhenPassInvalidUser_ModelStateThrowsanError() { var user = new PortFreightUser() { UserName = "******", Email = "*****@*****.**", PasswordHash = "TestTest1!" }; var inputModel = new RegisterModel.InputModel { Email = user.Email, Password = user.PasswordHash }; registerModel.Input = inputModel; registerModel.ModelState.AddModelError("Sender Id", "Sender Id is required."); var result = await registerModel.OnPostAsync(); Assert.IsNotNull(result); Assert.IsInstanceOfType(result, typeof(PageResult)); }
private async Task CheckRegistrationsArgs(RegisterModel.InputModel model) { var codes = new List <StatusCode>(); if (await repository.AnyUser(U => U.PhoneNumber == model.PhoneNumber)) { codes.Add(SituationCenter.Shared.Exceptions.StatusCode.PhoneBusy); } if (await repository.AnyUser(U => U.Email == model.Email)) { codes.Add(SituationCenter.Shared.Exceptions.StatusCode.EmailBusy); } switch (codes.Count) { case 0: return; case 1: throw new StatusCodeException(codes[0]); default: throw new MultiStatusCodeException(codes); } }
public void CreateUser(RegisterModel.InputModel viewModel, string userId) { var cloudinary = CloudinaryInitialization.Initialize(); if (viewModel.ProfileImage.Name == null) { throw new Exception("Image not found, Please add an image"); } var uploadParams = new ImageUploadParams() { File = new FileDescription(viewModel.ProfileImage.FileName, viewModel.ProfileImage.OpenReadStream()), }; var uploadResult = cloudinary.Upload(uploadParams); if (uploadResult.Error != null) { throw new Exception(uploadResult.Error.Message); } var applicationUser = _dbContext.Users.FirstOrDefault(identityUser => identityUser.Id == userId); var user = new User() { FirstName = viewModel.FirstName, LastName = viewModel.LastName, Age = viewModel.Age, ApplicationUserId = userId, ApplicationUser = applicationUser, Resume = null, ImageLocation = uploadResult.SecureUrl.AbsoluteUri }; _dbContext.ApplicationUsers.Add(user); _dbContext.SaveChanges(); }
public abstract void SetGegevensWerkgever(RegisterModel.InputModel input);