[ValidateAntiForgeryToken] //CSRF public async Task <IActionResult> Registration(AccountRegistration userInput) { // post request logic if (!ModelState.IsValid) { return(View(userInput)); } // for now we will just take the username and email as they are. var user = new User { UserName = userInput.UserName, Email = userInput.Email }; var result = await _userManager.CreateAsync(user, userInput.Password); if (result.Succeeded) { await _userManager.AddToRoleAsync(user, "Visitor"); await _signInManager.SignInAsync(user, isPersistent : false); return(RedirectToAction(nameof(HomeController.Index), "Home")); } foreach (var error in result.Errors) { ModelState.TryAddModelError(error.Code, error.Description); } return(View(userInput)); }
public bool RegisterAccount(AccountRegistration newAccount) { try { UserDetail user = new UserDetail() { UserId = newAccount.UserId, Name = newAccount.Name, Email = newAccount.Email, Address = newAccount.Address, Mobile = newAccount.Mobile, MasterAreaId = newAccount.MasterAreaId, MasterCityId = newAccount.MasterCityId, Remarks = " ", UserStatusId = newAccount.UserStatusId }; db.UserDetails.Add(user); db.SaveChanges(); return(true); } catch (Exception) { //throw ex; return(false); } }
public async Task <Account> CreateUserAccount(string email, string password, string nickName = "") { AccountRegistration accountRegistration = new AccountRegistration(email, password, nickName); Account registredAccount = await accountRepository.CreateAsync(accountRegistration.Account); return(registredAccount); }
public ActionResult NewAccount() { //var identity = User.Identity as ClaimsIdentity; //var userToken = GetAuthenticatedUserToken(identity); var accountRegistration = new AccountRegistration(); //AccountsRepositoryFactory.GetAccountsRepository().CreateAccount(userToken); //return RedirectToAction("Index"); return(View("Register", accountRegistration)); }
/// <summary> /// Use this is to register new yousers /// </summary> /// <param name="request"></param> /// <param name="cancellationToken"></param> /// <exception cref="ArgumentNullException">If request is null</exception> /// <exception cref="ArgumentException">If email not exist</exception> /// <returns></returns> public async override Task <TokenReply> HandleRequest(RequestObject <RegistrationRequest, TokenReply> request, CancellationToken cancellationToken = default) { if (request == null) { throw new ArgumentNullException(nameof(request)); } if (request == null) { request = new RequestObject <RegistrationRequest, TokenReply>(new RegistrationRequest()) { StatusCode = StatusCode.NotFound }; request.Detail = $"{nameof(request)} is null"; return(new TokenReply()); } RegistrationRequest requestData = request.Value; if (IsAccountExist(requestData.Email)) { request.StatusCode = StatusCode.AlreadyExists; request.Detail = "Email already exist"; return(new TokenReply()); } // this code work in only in valid satate string nickname = NicknameGenerator.FromEmail(requestData.Email); AccountRegistration accountRegistration = new AccountRegistration(requestData.Email, requestData.Password, nickname); Context.Accounts.Add(accountRegistration.Account); await Context.SaveChangesAsync(); if (!requestData.IsAnonymous) { // send verifier email await emailVerifierService .InstatiateVerifierMessage(accountRegistration.Account.User, accountRegistration.Account.Email) .ConfigureAwait(false); } // generate token TokenResponse tokenResponse = new TokenResponse(accountRegistration.Account.AccountId, accountRegistration.Account.Role, jwtProvider); TokenReply registrationReply = new TokenReply { UserId = tokenResponse.UserId, Token = tokenResponse.Token }; return(registrationReply); }
public ActionResult NewAccount(AccountRegistration registration) { //ValidateModel(registration); if (!ModelState.IsValid) { return(View("Register", registration)); } var identity = User.Identity as ClaimsIdentity; var userToken = GetAuthenticatedUserToken(identity); AccountsRepositoryFactory.GetAccountsRepository().CreateAccount(userToken, registration.EmailAddress); return(RedirectToAction("Index")); }
public async Task <IWebUser> Register([FromBody] AccountRegistration creds) { if (ModelState.IsValid) { IWebUser user = _manager.Register(creds); if (user != null) { await SetUserSession(user); return(user); } } throw new Exception("Invalid Credentials"); }
public ActionResult Register(AccountRegistration registration) { try { if (ModelState.IsValid && checkRegistrationFields(registration)) { if (checkEmail(registration.Username)) { if (checkPassword(registration.Password, registration.Password2)) { var accMgr = storeFactory.AccMgr; //create user var userId = accMgr.CreateUser(registration.Username, registration.Password); if (userId != "Error") { //assign user role if (SetUserRoles(int.Parse(userId), SHOPPER)) { //register account registration.UserId = userId; if (accMgr.RegisterAccount(registration)) { // proceed to login return(RedirectToAction("Login")); } else { ModelState.AddModelError("", "Unable to register a new shopper account."); } } } } } } } catch (Exception) { }; ViewBag.UserStatusId = new SelectList(edb.UserStatus, "Id", "Name", registration.UserStatusId); ViewBag.MasterCityId = new SelectList(edb.MasterCities, "Id", "Name", registration.MasterCityId); ViewBag.MasterAreaId = new SelectList(edb.MasterAreas, "Id", "Name", registration.MasterAreaId); return(View()); }
public string Register(AccountRegistration data) { var emailCheck = CheckEmail(data.Email); if (emailCheck != RegistrationEmailStatus.Ready) { throw new InvalidOperationException("Email verification returned: " + emailCheck.ToString()); } if (CheckUsername(data.Username) != "Available") { throw new InvalidOperationException("Username not available"); } Guid memberId = Guid.Empty; var result = AddNewMember(data, () => { var member = db.PersonContact.Where(f => f.Type == "email" && f.Value == data.Email).Select(f => f.Person).Single(); memberId = member.Id; var now = DateTime.Now; // For all units where the member is active and they have accounts turned on... foreach (var unit in member.Memberships.Where(f => f.Activated < now && (f.EndTime == null || f.EndTime > now) && f.Status.GetsAccount).Select(f => f.Unit)) { string roleName = string.Format("sec.{0}.members", unit.DisplayName.Replace(" ", "").ToLowerInvariant()); // Give them rights as a member of the unit. if (System.Web.Security.Roles.RoleExists(roleName)) { System.Web.Security.Roles.AddUserToRole(data.Username, roleName); } } return(member); }, "register-account.html"); if (result == "OK" && memberId != Guid.Empty) { var member = db.Members.Single(f => f.Id == memberId); member.Username = data.Username; db.SaveChanges(); } return(result); }
public bool checkRegistrationFields(AccountRegistration registration) { bool isValid = true; if (registration.Password.IsNullOrWhiteSpace() || registration.Password2.IsNullOrWhiteSpace()) { ModelState.AddModelError("Password", "Password field is empty."); isValid = false; } if (registration.Username.IsNullOrWhiteSpace()) { ModelState.AddModelError("Username", "Username field is empty."); isValid = false; } if (registration.Name.IsNullOrWhiteSpace()) { ModelState.AddModelError("Name", "Name field is empty."); isValid = false; } if (registration.Address.IsNullOrWhiteSpace()) { ModelState.AddModelError("Address", "Address field is empty."); isValid = false; } if (registration.Email.IsNullOrWhiteSpace()) { ModelState.AddModelError("Email", "Email field is empty."); isValid = false; } if (registration.Mobile.IsNullOrWhiteSpace()) { ModelState.AddModelError("Mobile", "Mobile field is empty."); isValid = false; } if (registration.Email.IsNullOrWhiteSpace()) { ModelState.AddModelError("Email", "Email field is empty."); isValid = false; } return(isValid); }
protected void btnRegister_Click(object sender, EventArgs e) { try { if (Convert.ToString(Session["Admin_OTP"]) != txtOTP.Text) { General.DisplaySweetAlertPopup(this, "Error", "Invalid OTP", MessageType.error); } string adminDetails = ""; Member objMember = new Member(); AccountRegistration adminRegistration = new AccountRegistration { FirstName = txtFirstName.Text.Trim(), MiddleName = txtMiddleName.Text.Trim(), LastName = txtLastName.Text.Trim(), MobileNo = txtMobileNo.Text.Trim(), EmailID = txtEmailID.Text.Trim(), IsAdmin = true, Password = txtPassword.Text.Trim() }; XmlSerializer xmlserializer = new XmlSerializer(adminRegistration.GetType()); var stringWriter = new StringWriter(); using (var writer = XmlWriter.Create(stringWriter)) { xmlserializer.Serialize(writer, adminRegistration); adminDetails = stringWriter.ToString(); } string tStatus = objMember.beSaveRegistrationDetails(adminDetails); General.DisplaySweetAlertPopup(this, "Success", "Admin Created Successfully", MessageType.success); Clear(); } catch (Exception ex) { General.DisplaySweetAlertPopup(this, "Error", "Server Error!, please try again", MessageType.error); } }
private void btnNewAccount_Click(object sender, EventArgs e) { AccountRegistration accr = new AccountRegistration(this); accr.ShowDialog(); }
static void Main(string[] args) { User temporaryUser = new User(); bool isActive = true; string key; do { Console.Clear(); Console.WriteLine("1. Зарегистрировать пользователя \n2. Войти в личный кабинет \n3. Поиск \n4. Просмотреть весь каталог товаров \n5. Выход"); key = Console.ReadLine(); switch (key) { case "1": { Console.Clear(); User user = new User(); AccountRegistration registration = new AccountRegistration(); registration.Registration(user); } break; case "2": { Console.Clear(); LogIn login = new LogIn(); login.LogInChecker(temporaryUser); if (temporaryUser.IsLogged == true) { Console.Clear(); Console.WriteLine("1. Корзина \n2. История покупок \n3. Выйти из аккаунта \n4. Назад в главное меню"); string action; bool basketIsExit = false; action = Console.ReadLine(); switch (action) { case "1": { Console.WriteLine("Реализовано только в подкюченном режиме"); } break; case "2": { Console.WriteLine("Реализовано только в подкюченном режиме"); } break; case "3": { login.LogOut(temporaryUser); } break; case "4": { break; } break; } Console.ReadKey(); } else { Console.WriteLine("Для доступа в личный кабинет нужно авторизоваться в системе"); Console.ReadKey(); } } break; case "3": { int pageSize = 3; int pageNumber = 0; bool exit = false; FindItem find = new FindItem(); Console.WriteLine("Введите название товара"); string itemName = Console.ReadLine(); while (!exit) { Console.Clear(); try { var result = find.FindItems(itemName, pageSize, pageNumber); foreach (var item in result) { Console.WriteLine(item.Name); Console.WriteLine(item.Price); Console.WriteLine(item.Description); Console.WriteLine("--------------------------------------------------"); } } catch (ArgumentOutOfRangeException exception) { Console.WriteLine("Ошибка! Чтобы продолжить просмотр листайте вперед"); } Console.WriteLine("1. Следующая страница \n2. Предыдущая страница \n3. Выход"); string action = Console.ReadLine(); if (action == "1") { pageNumber++; } else if (action == "2") { pageNumber--; } else if (action == "3") { exit = true; } } } break; case "4": { int pageSize = 3; int pageNumber = 0; bool exit = false; int i = 1; ShowItem show = new ShowItem(); while (!exit) { Console.Clear(); try { var result = show.ShowItems(pageSize, pageNumber); foreach (var item in result) { Console.WriteLine("Наименование товара: " + item.Name); Console.WriteLine("Цена: " + item.Price); Console.WriteLine("Описание товара: " + item.Description); Console.WriteLine("--------------------------------------------------"); i++; } } catch (ArgumentOutOfRangeException exception) { Console.WriteLine("Ошибка! Чтобы продолжить просмотр листайте вперед"); } Console.WriteLine("1. Следующая страница \n2. Предыдущая страница \n3. Выход"); string action = Console.ReadLine(); if (action == "1") { pageNumber++; } else if (action == "2") { pageNumber--; } else if (action == "3") { exit = true; } } } break; case "5": { isActive = false; } break; } } while (isActive != false); }
private string AddNewMember(AccountRegistration data, Func <Member> memberCallback, string noticeTemplate) { if (string.IsNullOrWhiteSpace(data.Email)) { return("Email is required"); } if (!Regex.IsMatch(data.Email, @"^\S+@\S+\.\S+$")) { return("Unrecognized email address"); } if (string.IsNullOrWhiteSpace(data.Username)) { return("Username is required"); } if (data.Username.Length < 3) { return("Username must be 3 or more characters"); } if (data.Username.Length > 200) { return("Username must be less than 200 characters"); } if (!Regex.IsMatch(data.Username, @"^[a-zA-Z0-9\.\-_]+$")) { return("Username can only contain numbers, letters, and the characters '.', '-', and '_'"); } if (membership.GetUser(data.Username, false) != null) { return("Username is already taken"); } if (string.IsNullOrWhiteSpace(data.Password)) { return("Password is required"); } if (data.Password.Length < 6) { return("Password must be at least 6 characters"); } if (data.Password.Length > 64) { return("Password must be less than 64 characters"); } MembershipCreateStatus status; var user = membership.CreateUser(data.Username, data.Password, data.Email, null, null, false, null, out status); if (status != MembershipCreateStatus.Success) { return("Could not create user"); } try { System.Web.Security.FormsAuthenticationTicket ticket = new System.Web.Security.FormsAuthenticationTicket(data.Username, false, 5); Thread.CurrentPrincipal = new System.Web.Security.RolePrincipal(new System.Web.Security.FormsIdentity(ticket)); var member = memberCallback(); SarMembership.KcsarUserProfile profile = ProfileBase.Create(data.Username) as SarMembership.KcsarUserProfile; if (profile != null) { profile.FirstName = member.FirstName; profile.LastName = member.LastName; profile.LinkKey = member.Id.ToString(); profile.Save(); } string mailSubject = string.Format("{0} account verification", ConfigurationManager.AppSettings["dbNameShort"] ?? "KCSARA"); string mailTemplate = File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Templates", "Email", noticeTemplate)); string mailBody = mailTemplate .Replace("%Username%", data.Username) .Replace("%VerifyLink%", new Uri(this.Request.RequestUri, Url.Route("Default", new { httproute = "", controller = "Account", action = "Verify", id = data.Username })).AbsoluteUri + "?key=" + user.ProviderUserKey.ToString()) .Replace("%WebsiteContact%", ConfigurationManager.AppSettings["MailFrom"] ?? "*****@*****.**"); db.SaveChanges(); EmailService.SendMail(data.Email, mailSubject, mailBody); } catch (Exception ex) { log.Error(ex.ToString()); membership.DeleteUser(data.Username, true); return("An error occured while creating your user account"); } return("OK"); }