public async Task <IActionResult> CreateAccount([FromBody] CreateAccountModel user) { bool isValid = true; if (string.IsNullOrWhiteSpace(user.FirstName) || string.IsNullOrWhiteSpace(user.LastName) || string.IsNullOrWhiteSpace(user.EmailAddress) || string.IsNullOrWhiteSpace(user.Password) || string.IsNullOrWhiteSpace(user.ConfirmPassword)) { ErrorMessage = "Please fill all required fields."; return(BadRequest(ErrorMessage)); } if (!_emailValidator.CheckRule(user.EmailAddress)) { ErrorMessage += "Email invalid format."; isValid = false; } if (!_passwordValidator.CheckRule(user.Password)) { ErrorMessage += "*Password invalid format." + " It must contains 8 characters, at least one letter and one digit."; isValid = false; } if (!user.Password.Equals(user.ConfirmPassword)) { ErrorMessage += "*Password mismatch."; isValid = false; } if (!isValid) { return(BadRequest(ErrorMessage)); } var(passwordHash256, salt) = _securePassword.EncryptPassword(user.Password); try { var newUser = new User() { FirstName = user.FirstName, LastName = user.LastName, EmailAddress = user.EmailAddress, PasswordHash = Convert.ToBase64String(passwordHash256), PasswordSalt = Convert.ToBase64String(salt) }; await _userService.CreateAccountAsync(newUser); } catch (Exception ex) { ErrorMessage = ex.Message; return(BadRequest(ErrorMessage)); } return(Ok("Account created.")); }
public ActionResult Authorize(CreateAccountModel model) { if (ModelState.IsValid) { if (_accountService.ExistsAccount(model.LoginName)) { ModelState.AddModelError("LoginName", string.Format("登录账号 {0} 已经存在", model.LoginName)); return View("AuthorizeRegisterAccount", model); } var account = _accountService.GetRegisterAccountById((int)model.Id); account.AccountName = model.LoginName; account.Password = model.ConfirmPassword; account.Name = model.Name; account.Age = model.Age; account.Birthday = model.Birthday; account.Gender = model.Gender; account.Telephone = model.Telephone; account.Mobile = model.Mobile; account.Email = model.Email; account.JobNumber = model.JobNumber; _accountService.AuditAccount(account); return RedirectToAction("Edit","Account", new { id = account.Id}); } return View("AuthorizeRegisterAccount",model); }
public async Task <ActionResult> UserCreate(CreateAccountModel model) { if (ModelState.IsValid) { //page.310 AppUser user = new AppUser { UserName = model.Name, Email = model.Email, PhoneNumber = model.Phone, CityID = model.CityID, CountryID = model.CountryID, ShippingAddress = model.ShippingAddress }; IdentityResult result = await myUserManager.CreateAsync(user, model.Password); if (result.Succeeded) { return(RedirectToAction("UserIndex")); } else { AddErrorsFromResult(result); } } CityAndCountryPorvider.SetSelectListToViewBag(this, repository, model.CityID, model.CountryID); ViewBag.IsAdminAccess = true; if (!CityAndCountryPorvider.CheckIfSelectListOfViewBagCorrect(this)) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } return(View("~/Views/Home/CreateUser.cshtml", model)); }
public void Cannot_Create_User_When_ModelState_Invalid() { var myMock = new MyMock(); //不確認CreateAsync功能 myMock.UserManager.Setup(u => u.CreateAsync(It.IsAny <AppUser>(), It.IsAny <string>())).ReturnsAsync(IdentityResult.Success); CreateAccountModel userInfo = new CreateAccountModel { Name = "UserName", Email = "*****@*****.**", Password = "******", PasswordConfirm = "12sd45er78", Phone = "0123456789", CityID = 2, CountryID = 3, ShippingAddress = "999" }; var controller = new HomeController(myMock.ProductRepository.Object, myMock.UserManager.Object); controller.ModelState.AddModelError("error", "error"); controller.Url = GetUrlHelper(); var result = controller.CreateUser(userInfo) as Task <ActionResult>; var viewresult = result.Result; Assert.AreEqual(userInfo, (viewresult as ViewResult).Model); }
public async Task <Result <UserInfoModel> > Activate([FromBody] CreateAccountModel model) { if (!Validate(model)) { return(null); } var user = await _userService.GetAsync(model.PublicId); if (user == null) { throw new AppValidationException(ErrorMessagesLibrary.Data[ErrorMessagesLibrary.Keys.CantFindUser]); } user.FirstName = model.FirstName; user.LastName = model.LastName; user.IsConfirmed = true; user.Status = UserStatus.Active; user.ConfirmationToken = Guid.Empty; await _userService.UpdateAsync(user, null, model.Password); await _userService.SignInAsync(user); return(await PopulateUserInfoModel(user)); }
public async Task <IHttpActionResult> CreateAccount(CreateAccountModel model) { if (model == null) { return(BadRequest()); } var userStore = new ApplicationUserStore(); var usermanager = new ApplicationUserManager(userStore); var user = new ApplicationUser { UserName = model.Email }; var result = await usermanager.CreateAsync(user, model.Password); if (!result.Succeeded) { foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error); } return(BadRequest(ModelState)); } return(Ok()); }
public void Can_Create_User() { var myMock = new MyMock(); //不確認CreateAsync功能 myMock.UserManager.Setup(u => u.CreateAsync(It.IsAny <AppUser>(), It.IsAny <string>())).ReturnsAsync(IdentityResult.Success); CreateAccountModel userInfo = new CreateAccountModel { Name = "UserName", Email = "*****@*****.**", Password = "******", PasswordConfirm = "12sd45er78", Phone = "0123456789", CityID = 2, CountryID = 3, ShippingAddress = "999" }; var controller = new HomeController(myMock.ProductRepository.Object, myMock.UserManager.Object); controller.Url = GetUrlHelper(); var result = controller.CreateUser(userInfo) as Task <ActionResult>; var viewresult = result.Result; Assert.AreEqual("Account", (viewresult as RedirectToRouteResult).RouteValues["controller"]); Assert.AreEqual("Login", (viewresult as RedirectToRouteResult).RouteValues["action"]); //還搞不定Url.Action的問題 //Assert.AreEqual("Login", (viewresult as RedirectToRouteResult).RouteValues["returnUrl"]); }
public async Task CreateAccount_ValidAccount_ReturnsAccount() { const string email = "*****@*****.**"; const string password = "******"; var salt = new byte[] { 0x20, 0x20, 0x20, 0x20 }; var hashedPassword = new byte[] { 0x20, 0x20, 0x20, 0x20 }; const string token = "testjwttoken"; var account = new Account { Id = Guid.NewGuid(), Email = email, Password = hashedPassword, isDelegate = false, isDAppOwner = false, Salt = salt, Token = token }; var createAccountModel = new CreateAccountModel() { Email = email, Password = password }; _accountService.Setup(x => x.CreateAccount(createAccountModel)).ReturnsAsync(account); var result = await _accountController.CreateAccount(createAccountModel) as ObjectResult; Assert.IsType <OkObjectResult>(result); Assert.Equal(account.Id, ((Account)result.Value).Id); }
public ActionResult Account(string id) { using (var db = new Entities()) { var model = new CreateAccountModel(); model.groups = db.asp_Group.Select(x => new GroupData { id = x.id, name = x.name, description = x.description }).ToList(); var data = db.asp_User.FirstOrDefault(x => x.account == id); if (data != null) { model.account = data.account; model.name = data.userName; //model.password model.email = data.email; model.edit = true; foreach (var item in model.groups) { if (data.asp_Group.Any(x => x.id == item.id)) { item.check = true; } } } return(PartialView(model)); } }
public async Task <ActionResult> CreateUser(CreateAccountModel model) { if (ModelState.IsValid) { //page.310 AppUser user = new AppUser { UserName = model.Name, Email = model.Email, PhoneNumber = model.Phone, CityID = model.CityID, CountryID = model.CountryID, ShippingAddress = model.ShippingAddress }; IdentityResult result = await myUserManager.CreateAsync(user, model.Password); if (result.Succeeded) { //await UserManager.AddToRoleAsync(user.Id, "Users"); //新帳號預設Users權限 TempData["message"] = "創建帳號成功,請登入!"; return(RedirectToAction("Login", "Account", new { returnUrl = Url.Action("Index", "Home") })); } else { AddErrorsFromResult(result); } } CityAndCountryPorvider.SetSelectListToViewBag(this, repository, model.CityID, model.CountryID); if (!CityAndCountryPorvider.CheckIfSelectListOfViewBagCorrect(this)) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } return(View(model)); }
public ActionResult Register(CreateAccountModel model) { Customer customer = new Customer(); customer.NameSurname = model.NameSurname; customer.UserName = model.UserName; customer.Salary = Convert.ToDecimal(model.Salary); customer.Email = model.Email; customer.Age = model.Age; customer.Password = model.Password; customer.City = model.City; customer.Occupation = model.Occupation; if (model.Condition == "1") { customer.Condition = true; } else { customer.Condition = false; } customer.Gender = Convert.ToByte(model.Gender); _userService.AddCustomer(customer); return(RedirectToAction("Register", new { message = "success" })); }
public async Task <IActionResult> CreateAccount([FromBody] CreateAccountModel newAccount) { var result = await this.validateCreateAccount.ValidateAsync(newAccount); if (!result.IsValid) { var errorResponse = new List <ResponseError>(); foreach (var error in result.Errors) { errorResponse.Add( new ResponseError() { Field = error.PropertyName, ErrorMessage = error.ErrorMessage, InputData = error.AttemptedValue, }); } return(this.BadRequest(errorResponse)); } if (await this.auth.CreateAccount(newAccount) != 0) { return(this.Ok(new { message = "User Account has been created successfully." })); } return(this.BadRequest(new { message = "Account Could not be created, please try again later." })); }
public void CreateAccount() { Database.SetInitializer(new ManahostManagerInitializer()); using (ManahostManagerDAL prectx = new ManahostManagerDAL()) { prectx.Database.Delete(); } var AccountModel = new CreateAccountModel() { Civility = "Mr", Country = "France", Email = "*****@*****.**", FirstName = "Fabrice", LastName = "Didierjean", Password = "******", PasswordConfirmation = "TOTOTITi88$$" }; HttpResponseMessage result; using (var server = TestServer.Create <WebApiApplication>()) { result = server.CreateRequest("/api/Account").And(x => { x.Content = new ObjectContent(typeof(CreateAccountModel), AccountModel, new JilFormatter()); x.Content.Headers.ContentType = new MediaTypeHeaderValue(GenericNames.APP_JSON); }).PostAsync().Result; string msg = result.Content.ReadAsStringAsync().Result; Assert.AreEqual(HttpStatusCode.OK, result.StatusCode, "Status Create Account" + msg); } }
private static void CreateCustomerAndAccounts(AccountModel accountModel) { var stringTask = AsyncHelpers.RunSync(() => client.PostAsync("http://localhost:61255/api/customers", new StringContent(JsonConvert.SerializeObject(accountModel), Encoding.UTF8, "application/json"))); var customerId = JsonConvert.DeserializeObject <int>(AsyncHelpers.RunSync(() => stringTask.Content.ReadAsStringAsync())); Console.WriteLine($"Custumer with id {customerId} created"); for (int i = 0; i < 30; i++) { var accountRequest = new CreateAccountModel { Id = customerId, Name = "Account" }; var accountReponse = AsyncHelpers.RunSync(() => client.PostAsync("http://localhost:61255/api/accounts", new StringContent(JsonConvert.SerializeObject(accountRequest), Encoding.UTF8, "application/json"))); var accountResponseBody = JsonConvert.DeserializeObject <OpenAccountResponse>(AsyncHelpers.RunSync(() => accountReponse.Content.ReadAsStringAsync())); Console.WriteLine($"Account with id {accountResponseBody.AccountId} created"); } }
public static string DoUserCreation(CreateAccountModel model) { var Password = model.Password; var TrainerName = model.Username; var Email = model.Email; if (UserNameAlreadyTaken(TrainerName)) { return("username already taken"); } try { Controllers.PokemonController.CreateNewTrainer(model.Username); Password = EncryptPassword(Password); InsertDBcredentials(TrainerName, Password, Email); return("account created"); } catch (Exception ex) { Console.WriteLine(ex.Message); return("error"); } }
public Account post_accounts_create(CreateAccountModel model) { var account = Session.Query <Account>().FirstOrDefault(t => t.Name == model.Name); if (account != null) { throw new InvalidOperationException("A Account with that name already exists"); } account = new Account { Id = model.AccountId, Name = model.Name }; Session.Store(account); Bus.Publish <AccountCreated>(m => { m.AccountId = account.Id; }); return(account); }
public async Task CreateAccount_ValidAccount_ReturnsAccountWithoutSensitiveData() { const string email = "*****@*****.**"; const string password = "******"; var salt = new byte[] {0x20, 0x20, 0x20, 0x20}; var hashedPassword = new byte[] {0x20, 0x20, 0x20, 0x20}; var account = new Account { Email = email, Password = hashedPassword, Salt = salt, }; var createModel = new CreateAccountModel { Email = "*****@*****.**", Password = "******" }; _repository.Setup(x => x.Get(createModel.Email)).ReturnsAsync((Account) null); _hasher.Setup(x => x.CreateSalt()).Returns(salt); _hasher.Setup(x => x.HashPassword(password, salt)).ReturnsAsync(hashedPassword); _repository.Setup(x => x.Create(It.IsAny<Account>())).ReturnsAsync(account); _regexHelper.Setup(x => x.IsValidEmail(createModel.Email)).Returns(true); _regexHelper.Setup(x => x.IsValidPassword(createModel.Password)).Returns(true); _messageQueuePublisher.Setup(x => x.PublishMessageAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), new {Email = email})).Returns(Task.CompletedTask); var result = await _accountService.CreateAccount(createModel); Assert.Equal(account.Email, result.Email); Assert.Null(result.Password); Assert.Null(result.Salt); }
/// <summary> /// New Account API Post /// </summary> /// <param name="acct"> /// AccountInfoModel for API post /// </param> /// <returns> /// Post location /// </returns> private async Task <Uri> PostNewAcct(CreateAccountModel acct) { HttpResponseMessage response = await ApiHelper.ApiClient.PostAsJsonAsync("/v1/user", acct); response.EnsureSuccessStatusCode(); return(response.Headers.Location); }
public async Task <IActionResult> CreateAccount(CreateAccountModel model) { if (ModelState.IsValid) { UserModel user = new UserModel() { UserName = model.UserName, Email = model.Email, PhoneNumber = model.PhoneNumber, EmailConfirmed = false, EmailVerificationKey = RandomKeyGenerator.RandomString(25), }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { var send = await _messageService.SendNewVerificationCode(user.Email, user.EmailVerificationKey, user.UserName); if (send) { return(RedirectToAction("NeedVerification", new { userName = user.UserName, email = user.Email })); } return(View(model)); } else { foreach (var error in result.Errors) { ModelState.AddModelError("", error.Description); } } } return(View(model)); }
public CreateAccountViewModel(CreateAccount view) { _View = view; _Model = new CreateAccountModel(); _Model.ShowText = false; UseCreateAccountCommand = new CreateAccountCommand(this); UseReturnToLoginCACommand = new ReturnToLoginFromACCommand(this); }
public void TestCreateAccountModel1() { CreateAccountModel model = new CreateAccountModel(); Assert.IsNull(model.username); Assert.IsNull(model.password); Assert.IsNull(model.phone_number); }
public async Task <int> CreateAccount([FromBody] CreateAccountModel model) { var result = 0; result = await Server.CreateAccount(model.Name, model.Description); return(result); }
private async Task UpdateAccountNameToLegalEntityName(CreateAccountModel model) { await _mediator.SendAsync(new RenameEmployerAccountCommand { HashedAccountId = model.HashedAccountId.Value, ExternalUserId = model.UserId, NewName = model.OrganisationName }); }
public async Task <ActionResult> CreateAccount() { var enteredData = _employerAccountOrchestrator.GetCookieData(); if (enteredData == null) { // N.B CHANGED THIS FROM SelectEmployer which went nowhere. _employerAccountOrchestrator.DeleteCookieData(); return(RedirectToAction(ControllerConstants.SearchForOrganisationActionName, ControllerConstants.SearchOrganisationControllerName)); } var request = new CreateAccountModel { UserId = GetUserId(), OrganisationType = enteredData.EmployerAccountOrganisationData.OrganisationType, OrganisationReferenceNumber = enteredData.EmployerAccountOrganisationData.OrganisationReferenceNumber, OrganisationName = enteredData.EmployerAccountOrganisationData.OrganisationName, OrganisationAddress = enteredData.EmployerAccountOrganisationData.OrganisationRegisteredAddress, OrganisationDateOfInception = enteredData.EmployerAccountOrganisationData.OrganisationDateOfInception, PayeReference = enteredData.EmployerAccountPayeRefData.PayeReference, AccessToken = enteredData.EmployerAccountPayeRefData.AccessToken, RefreshToken = enteredData.EmployerAccountPayeRefData.RefreshToken, OrganisationStatus = string.IsNullOrWhiteSpace(enteredData.EmployerAccountOrganisationData.OrganisationStatus) ? null : enteredData.EmployerAccountOrganisationData.OrganisationStatus, EmployerRefName = enteredData.EmployerAccountPayeRefData.EmployerRefName, PublicSectorDataSource = enteredData.EmployerAccountOrganisationData.PublicSectorDataSource, Sector = enteredData.EmployerAccountOrganisationData.Sector, HashedAccountId = _accountCookieStorage.Get(_hashedAccountIdCookieName), Aorn = enteredData.EmployerAccountPayeRefData.AORN }; var response = await _employerAccountOrchestrator.CreateOrUpdateAccount(request, HttpContext); if (response.Status == HttpStatusCode.BadRequest) { response.Status = HttpStatusCode.OK; response.FlashMessage = new FlashMessageViewModel { Headline = "There was a problem creating your account" }; return(RedirectToAction(ControllerConstants.SummaryActionName)); } _employerAccountOrchestrator.DeleteCookieData(); var returnUrlCookie = _returnUrlCookieStorageService.Get(ReturnUrlCookieName); _accountCookieStorage.Delete(_hashedAccountIdCookieName); _returnUrlCookieStorageService.Delete(ReturnUrlCookieName); if (returnUrlCookie != null && !returnUrlCookie.Value.IsNullOrWhiteSpace()) { return(Redirect(returnUrlCookie.Value)); } return(RedirectToAction(ControllerConstants.WhenDoYouWantToView, ControllerConstants.EmployerAgreementControllerName, new { hashedAccountId = response.Data.EmployerAgreement.HashedAccountId, agreementId = response.Data.EmployerAgreement.HashedAgreementId })); }
public IActionResult Employers() { var viewModel = new CreateAccountModel { BaseEmployerAccountUrl = _configuration.EmployerAccountBaseUrl }; return(View(viewModel)); }
public JsonResult Create(CreateAccountModel model) { try { if (!ModelState.IsValid) { return(Json(new { ok = false, Message = ModelState.Values.SelectMany(v => v.Errors).FirstOrDefault().ErrorMessage }, JsonRequestBehavior.AllowGet)); } var user = new User() { UserName = model.UserName, Email = model.Email, Password = model.Password, ConfirmPassword = model.ConfirmPassword }; var result = accountService.CreateAccount(user); if (result) { return(Json(new { ok = result, Message = "Account created succesfully." }, JsonRequestBehavior.AllowGet)); } else { return(Json(new { ok = result, Message = "Can not create the Account." }, JsonRequestBehavior.AllowGet)); } } catch (ServiceException se) { return(Json(new { ok = false, Message = se.Message }, JsonRequestBehavior.AllowGet)); } catch (Exception se) { return(Json(new { ok = false, Message = "Error" }, JsonRequestBehavior.AllowGet)); } }
public RequestHandlerResult CreateAccount(CreateAccountModel model) { return(Pipeline .Start() .AddNext <ISearchAccountStep>() .When(b => b.Id == "bla") .AddNext <ISearchAccountStep>() .AddNext <ICreateAccountStep>() .Execute(model)); }
public AccountEntityModel Account(CreateAccountModel model) { using (var repo = new AccountRepository(_systemDataContext)) { var account = model.Map(); // commit new account to db return(repo.Create(account)); } }
public ActionResult Post([FromBody] CreateAccountModel createAccountModel) { if (!_customerService.CheckIfCustomerExists(createAccountModel.CustomerId)) { return(BadRequest("Customer could not be found.")); } var result = _accountService.AddAccount(createAccountModel.CustomerId, createAccountModel.InitialCredit); return(Ok(result)); }
public string Get([FromQuery] string name, [FromQuery] string pass, [FromQuery] string email) { var cam = new CreateAccountModel() { Username = name, Password = pass, Email = email }; return(NewUser.DoUserCreation(cam)); }
public async Task <IActionResult> CreateAccount([FromBody] CreateAccountModel accountModel) { try { return(Ok(await _accountService.CreateAccount(accountModel))); } catch (Exception e) { return(BadRequest(e.Message)); } }
public ActionResult AuthorizeRegisterAccount(int id) { var account = _accountService.GetRegisterAccountById(id); var model = new CreateAccountModel(account); return View(model); }
// Use this for initialization public override void Start() { base.Start(); m_createAccountModel = new CreateAccountModel(this); createAccountView.createAccountController = this; // Fade in the background m_readyForInput = false; Fader.AttachFaderTo(this.gameObject, Color.black, Fader.eFadeType.fadeIn, 1.0f, () => { m_readyForInput = true; }); }
public ActionResult CreateSsoAccount(CreateAccountModel model) { var re =new JsonData<int>(); try { if (_accountService.ExistsAccount(model.LoginName)) { re.s = false; re.m ="帐户名称已存在!"; Response.StatusCode = 500; return Json("帐户名称已存在!"); } var newAccount = new Account() { AccountName = model.LoginName, Password = model.Password, Name = string.IsNullOrEmpty(model.Name) ? " " : model.Name, Age = model.Age, Birthday = model.Birthday, Gender = model.Gender, Telephone = model.Telephone, Mobile = model.Mobile, Email = model.Email, JobNumber = model.JobNumber, }; _accountService.AddAccount(newAccount); re.d = newAccount.Id; if (model.Clients != null) { _accountService.AuthorizeClients(newAccount.Id, model.Clients); } return Json(newAccount.Id); } catch (Exception ex) { re.s = false; Response.StatusCode = 500; return Json(ex.Message); } return Json(re); }