public RegisterPage(string userName = null) { UserRegisterViewModel = new UserRegisterViewModel { UserName = userName ?? string.Empty }; BindingContext = UserRegisterViewModel; InitializeComponent(); }
public async Task <ActionResult <UserToken> > CreateUser(UserRegisterViewModel model) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { return(BuildToken(new UserInfo { Email = model.Email, Password = model.Password })); } else { return(null);// result.Errors; } }
public static void AddUser(UserRegisterViewModel URV, string link, string code) // dodanie uzytkownika { using (sklepEntities db = new sklepEntities()) { Users user = new Users(); user.UserName = URV.Login; user.Email = URV.Email; string mySalt = BCrypt.Net.BCrypt.GenerateSalt(); string myHash = BCrypt.Net.BCrypt.HashPassword(URV.Password, mySalt); user.Password = myHash; user.IsActive = "N"; user.Role = "Uzytkownik"; user.Link = code; EmailService.sendConfirmAccount(user.UserName, user.Email, link); db.Users.Add(user); db.SaveChanges(); } }
public async Task <ActionResult> AddDriver(UserRegisterViewModel model) { if (ModelState.IsValid) { var operation = await _driverService.CreateDriver(model.ToUserDto("driver")); if (operation.Success) { Session["Create"] = new AlertViewModel(operation.Message, AlertType.Success); return(RedirectToAction("Index", "Home")); } return(new HttpOperationStatusResult(operation)); } return(View("AddUser", model)); }
public async Task <IActionResult> Register(UserRegisterViewModel userRegisterViewModel) { if (!ModelState.IsValid) { return(View(userRegisterViewModel)); } var response = await _authenticationService.Register(userRegisterViewModel); if (HasErrors(response.ResponseResult)) { return(View(userRegisterViewModel)); } await AddLoginInformationToCookie(response); return(RedirectToAction("Index", "")); }
public async Task <UserLoggedViewModel> Register(UserRegisterViewModel user) { var content = GetContent(user); var response = await _httpClient.PostAsync("/api/identidade/registrar", content); if (HasResponseErrors(response)) { var responseErrors = await DeserializeObjectResponse <ErrorResponseViewModel>(response); return(new UserLoggedViewModel { ErrorResponse = responseErrors }); } var userLogged = await DeserializeObjectResponse <UserLoggedViewModel>(response); return(userLogged); }
private string ProcessUploadedFile(UserRegisterViewModel model) { string uniqueFileName = null; if (model.Image != null) { string uploadsFolder = Path.Combine(env.WebRootPath, "images"); uniqueFileName = Guid.NewGuid().ToString() + "_" + model.Image.FileName; string filePath = Path.Combine(uploadsFolder, uniqueFileName); using (var fileStream = new FileStream(filePath, FileMode.Create)) { model.Image.CopyTo(fileStream); } } return(uniqueFileName); }
public async Task <IActionResult> RegisterUser(UserRegisterViewModel register) { try { var erroMsg = await _userService.AddAsync(register); if (erroMsg == string.Empty) { return(Created("", register.UserName)); } return(BadRequest(erroMsg)); } catch (Exception ex) { return(StatusCode(StatusCodes.Status500InternalServerError, ex)); } }
public ActionResult RegisterUsers(UserRegisterViewModel model) { if (!ModelState.IsValid || _repo.CheckExist(model.Login)) { ModelState.AddModelError("", "User with name already exists"); return(View(model)); } var user = new Users() { Login = model.Login, Password = model.Password.GetHashCode().ToString(), Email = model.Email, }; _repo.Create(user); Roles.AddUserToRole(user.Login, "fan"); return(RedirectToAction("Login")); }
public async Task <ActionResult> New(UserRegisterViewModel model) { if (ModelState.IsValid) { var user = new TicketDeskUser { UserName = model.UserName, Email = model.Email, DisplayName = model.DisplayName }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await UserManager.AddToRolesAsync(user.Id, DomainContext.TicketDeskSettings.SecuritySettings.DefaultNewUserRoles.ToArray()); HostingEnvironment.QueueBackgroundWorkItem(ct => { using (var notificationContext = new TdPushNotificationContext()) { notificationContext.SubscriberPushNotificationSettingsManager.AddSettingsForSubscriber( new SubscriberNotificationSetting { SubscriberId = user.Id, IsEnabled = true, PushNotificationDestinations = new[] { new PushNotificationDestination() { DestinationType = "email", DestinationAddress = user.Email, SubscriberName = user.DisplayName } } }); notificationContext.SaveChanges(); } }); return(RedirectToAction("Index")); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task <IActionResult> RegisterConfirm(UserRegisterViewModel model) { ApplicationUser applicationUser = new ApplicationUser(); applicationUser.Email = model.Email; applicationUser.UserName = model.Username; applicationUser.PhoneNumber = model.Tell; var status = await userManager.CreateAsync(applicationUser, model.Password); if (status.Succeeded) { string token = await userManager.GenerateEmailConfirmationTokenAsync(applicationUser); string href = Url.Action("AccountConfirm", "Register", new { id = applicationUser.Id, token = token }, "https"); string body = $@"Hello <b>{model.Username} {model.Email}</b><br/> Click <a href='{href}'>here</a> account Maked"; System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage("*****@*****.**", model.Email); mailMessage.Subject = "Reset Password "; mailMessage.Body = body; mailMessage.IsBodyHtml = true; SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587); smtpClient.EnableSsl = true; smtpClient.Credentials = new NetworkCredential("*****@*****.**", "reza_1234567890"); try { smtpClient.Send(mailMessage); } catch { TempData["msg"] = "ایمیل تغییر رمز به آدرس شما ارسال نگردید"; } TempData["msg"] = "ایمیل تغییر رمز به آدرس شما ارسال گردید"; return(RedirectToAction("Index", "Home")); } else { return(RedirectToAction("RegisterLogin")); } }
public IActionResult Register(UserRegisterViewModel model) { if (ModelState.IsValid) { User user = userService.Get(x => x.Email.Equals(model.Email) || x.UserName.Equals(model.UserName)); if (user != null) { ViewBag.RegisterAlertMassage = "Email adresi veya Kullanici adi daha önce kullanılmış."; return(View(model)); } bool valid = IsValidEmail(model.Email) && (int)GetPasswordStrength(model.Password) > 2; if (valid && model.ProfilePhoto != null) { model.Password = PasswordCryptographyCombine(model.Password); string uniqueFileName = null; string ex = Path.GetExtension(model.ProfilePhoto.FileName); string uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "UserImages"); uniqueFileName = Guid.NewGuid().ToString().Replace("-", "") + "_" + model.UserName + ex; string filePath = Path.Combine(uploadsFolder, uniqueFileName); model.ProfilePhoto.CopyTo(new FileStream(filePath, FileMode.Create)); user = new User() { FirstName = model.FirstName, LastName = model.LastName, ProfilePhoto = uniqueFileName, Email = model.Email, Password = model.Password, UserName = model.UserName }; userService.Add(user); userService.Save(); return(RedirectToAction("Index", "Login", new { area = "", username = user.UserName })); } } ViewBag.RegisterAlertMassage = "Tüm bilgileri eksiksiz ve doğru biçimde girdiğinizden emin olunuz."; return(View(model)); }
public async Task <ActionResult> Registrar(UserRegisterViewModel viewModel) { if (!ModelState.IsValid) { return(BadRequest(ModelState.Values.SelectMany(e => e.Errors))); } var result = await _userManagementService.Create(viewModel).ConfigureAwait(true); if (!result.Succeeded) { return(BadRequest(result.ToString())); } viewModel.Senha = string.Empty; viewModel.ConfirmaSenha = string.Empty; return(Ok(viewModel)); }
public async Task <IActionResult> UserRegister(UserRegisterViewModel model, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent : false); return(RedirectToAction("UserIndex", "Events")); } } return(View(model)); }
public IActionResult Register(UserRegisterViewModel user) { if (user == null) { return(BadRequest("Bad Input")); } string result = null; try { result = _auth.Register(user); } catch (Exception e) { Console.WriteLine(e.Message + e.StackTrace + e.Source); } return(Ok(result)); }
public IEnumerable <string> UserValidation(UserRegisterViewModel model) { if (model.Username == null) { this.errors.Add("Error"); } else if (model.Username.Length < 4 || model.Username.Length > 20) { this.errors.Add("error"); } else if (this.dB.Users.Any(u => u.Username == model.Username)) { this.errors.Add("errors"); } if (model.Password.Length > 20) { this.errors.Add("errors"); } else if (model.Password != model.ConfirmPassword) { this.errors.Add("Errors"); } else if (model.Password == null || model.ConfirmPassword == null) { this.errors.Add("Errors"); } if (model.Email == null) { this.errors.Add("error"); } string pattern = @"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"; Match match = Regex.Match(model.Email, pattern); if (!match.Success) { this.errors.Add("errors"); } return(this.errors); }
public IActionResult Register(UserRegisterViewModel vm) { if (ModelState.IsValid) { _context.Users.Add(vm.User); _context.SaveChanges(); return(RedirectToAction("Login")); } else { return(View( new UserRegisterViewModel() { User = vm.User, ProductTypes = _context.ProductTypes.ToList() } )); } }
public async Task <ActionResult> Register(UserRegisterViewModel model) { if (Request.IsAuthenticated) { return(GetDefaultRedirectRoute()); } if (ModelState.IsValid) { var user = new DotUser { Name = model.Name, Email = model.Email, Realm = Entities.Realm.BG, UserName = model.Name, //Entities.User.GenerateUserName(model.Name), CurrentCultureId = Globalization.RegionCulture.Name, CurrentUICultureId = Globalization.LanguageCulture.Name, TimeZoneId = Globalization.TimeZoneInfo.Id }; if (ModelState.IsValid) { var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent : true, rememberBrowser : false); // Get user data. var entity = await _userManager.FindByNameAsync(user.Email); // Register account creation. _timelineService.RegisterActivity(Entities.Realm.BG, Entities.ActivityType.CreatedItsOwnAccount, entity.Id); return(RedirectToLocal()); } AddErrors(result); } } return(View(model)); }
public async Task <ActionResult> Register(UserRegisterViewModel userRegisterViewModel) { if (!ModelState.IsValid) { return(GenerateResponse(ModelState)); } var user = new IdentityUser() { UserName = userRegisterViewModel.Email, Email = userRegisterViewModel.Email, EmailConfirmed = true }; var request = await _userManager.CreateAsync(user, userRegisterViewModel.Password); foreach (var error in request.Errors) { AddErrorToList(error.Description); } if (!request.Succeeded) { return(GenerateResponse()); } var registerCustomerResult = await RegisterCustomerBus(userRegisterViewModel); if (!registerCustomerResult.Validation.IsValid) { await _userManager.DeleteAsync(user); return(GenerateResponse(registerCustomerResult.Validation)); } var login = new UserLoginViewModel() { Email = userRegisterViewModel.Email, Password = userRegisterViewModel.Password }; return(await Login(login)); }
public async Task <IActionResult> Register(UserRegisterViewModel model) { if (ModelState.IsValid) { //var user = new IdentityUser { UserName = model.Email, Email = model.Email }; //Part: 77.2.1, 77.4.3 var user = new ApplicationUser { UserName = model.Email, Email = model.Email, City = model.City }; var result = await userManager.CreateAsync(user, model.Password); if (result.Succeeded) { //Part: 113.2.1 var token = await userManager.GenerateEmailConfirmationTokenAsync(user); //generate Email Confirmation Token var confirmationLink = Url.Action("ConfirmAccountByEmail", "Account", new { userId = user.Id, token = token }, Request.Scheme); //generate Email Confirmation Link logger.Log(LogLevel.Warning, confirmationLink); //61-64 // //Part:84.4 //for Staying signedIn User on signIn after create a New User if (signInManager.IsSignedIn(User) && User.IsInRole("Admin")) { return(RedirectToAction("ListUsers", "Administration")); } //113.2.2 //await signInManager.SignInAsync(user, isPersistent: false); //isPersistent: false for Session Cooce(Sign in Lost after browser close) & isPersistent: true for Permanent Cooce(Sign in also stay after browser close) //return RedirectToAction("index", "Home"); ViewBag.ErrorTitle = "Your Registration successful"; ViewBag.ErrorMessage = "Befor you can Login, please confirm your email," + "by clicking on the confirmation link we have emailed you"; return(View("Error")); // } foreach (IdentityError error in result.Errors) { ModelState.AddModelError("", error.Description); } } return(View(model)); }
public async Task <IActionResult> UserRegister(UserRegisterViewModel model) { if (ModelState.IsValid) { User user = new User { Email = model.Email, UserName = model.Email, Role = "user" }; UserModel us = new UserModel() { ModelCar = model.Car, Name = model.Email, PhoneNumber = model.PhoneNumber, Id = user.Id }; _context.User.Add(us); _context.SaveChanges(); // добавляем пользователя var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { await _userManager.AddToRoleAsync(user, "user"); } if (result.Succeeded) { // установка куки await _signInManager.SignInAsync(user, false); return(RedirectToAction("Index", "Home")); } else { foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } } return(View(model)); }
public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { string actionName = context.RouteData.Values["action"] as string; string token = string.Empty; bool verificationSuccess; if (actionName == "PassChange") { PassResetEmailViewModel model = context.ActionArguments["model"] as PassResetEmailViewModel; token = model.CaptchaToken; } else if (actionName == "AddNewUser") { UserRegisterViewModel model = context.ActionArguments["model"] as UserRegisterViewModel; token = model.CaptchaToken; } else { context.Result = new ObjectResult("Bad request.") { StatusCode = 400 }; return; } string ip = _userService.GetIpAddress(context.HttpContext); verificationSuccess = await _http.VerifyCaptchaAsync(token, ip); if (!verificationSuccess) { context.Result = new ObjectResult("Oops! Something went wrong.") { StatusCode = 429 }; return; } await next(); }
public async Task <IActionResult> Register(UserRegisterViewModel model) { if (ModelState.IsValid) { var user = await _context.Users.FirstOrDefaultAsync(u => u.Login == model.Login); if (user == null) { Console.WriteLine(model.SelectedBuilding); var repo = new AddressRepository(_context, model.SelectedRegion); var hashed = HashPassword(model.Password); var(address, index) = await repo.MakeAddress(model); _context.Users.Add(new Users { Login = model.Login, Password = hashed, Role = Role.User, LastName = model.LastName, FirstName = model.FirstName, MiddleName = model.MiddleName, TerritoryCode = model.SelectedCity, StreetCode = model.SelectedStreet, Address = address, Index = index, Building = model.BuildingName, BuildingCode = model.SelectedBuilding, Flat = model.Flat }); await _context.SaveChangesAsync(); await Authenticate(model.Login); return(RedirectToAction(nameof(Index))); } Console.WriteLine(user); ModelState.AddModelError("", "Пользователь уже существует"); } return(View(model)); }
public async Task <ActionResult <BaseResponse> > Register([FromBody] UserRegisterViewModel req) { BaseResponse br = new BaseResponse(); if (req.Password != req.PasswordAgain) { br.Success = false; br.Message = "两次输入的密码不一致,请确认"; return(br); } bool bGroup = await _gs.IsExist(a => a.Id == req.GroupId); if (!bGroup) { #region 添加modelstate /* * var err = new Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary(); * err.AddModelError("Message", "输入的组织编号不存在,请确认"); * return BadRequest(err); */ #endregion //return BadRequest("输入的组织编号不存在,请确认"); br.Success = false; br.Message = "输入的组织编号不正确"; return(br); } //验证是否重名(所有用户名都不能重复,不同组织也不允许重复) bool bUser = await _us.IsExist(a => a.Account == req.Account); if (bUser) { br.Success = false; br.Message = "此用户名已存在,请选择其他的用户名"; //return br; } else { br = await _us.UserRegisterAsync(req); } return(br); }
public async Task <IActionResult> Registration(UserRegisterViewModel userviewmodel, CancellationToken token) { if (ModelState.IsValid) { UserBE userExistence = await _userBL.GetUserByUserNameAndEmailBL(userviewmodel.UserName, userviewmodel.Email, token); UserBE userToAdd = new UserBE(); if (userExistence == null) { userToAdd.UserName = userviewmodel.UserName; userToAdd.Email = userviewmodel.Email; userToAdd.NormalizedUserName = userviewmodel.UserName.ToUpper(); userToAdd.NormalizedEmail = userviewmodel.Email.ToUpper(); var resultRegistration = await _userManager.CreateAsync(userToAdd, userviewmodel.Password); if (resultRegistration.Succeeded) { var userAfterAdd = await _userManager.FindByEmailAsync(userviewmodel.Email); await _signManager.SignInAsync(userAfterAdd, false); return(RedirectToAction("UserFlights", "Flight")); } else { foreach (var error in resultRegistration.Errors) { ModelState.AddModelError("", error.Description); } } } ModelState.AddModelError("Login", "Vous avez deja un compte"); ModelState.AddModelError("Email", "Vous avez deja un compte"); return(View(userviewmodel)); } return(View(userviewmodel)); }
public IActionResult Register(UserRegisterViewModel model, IFormFile ProfilePic) //Register User Route //pass the file from the form { if (ModelState.IsValid) { if (ProfilePic != null) //aka if a picture was uploaded { var filename = Path.Combine(HE.WebRootPath + "/images", Path.GetFileName(ProfilePic.FileName)); //stores a string of where the new file root should be String filestring = GetRandString(); //returns a string of numbers to randomize the file names String[] newfile = filename.Split("."); //creates an array of the file string before the period and after so we can add the randomized string String newFileString = newfile[0] + filestring + "." + newfile[1]; //puts the string back together including the random string String[] splitrootfile = newFileString.Split("wwwroot"); //creates a string with the path necessary to store and retrieve the image from the images folder ProfilePic.CopyTo(new FileStream(newFileString, FileMode.Create)); //stores the new file into our full path which is what we made prior to splitting by wwwroot User newUser = new User { FirstName = model.FirstName, LastName = model.LastName, Email = model.Email, UserName = model.UserName, Password = model.Password, ProfilePic = splitrootfile[1], //store only the second half of the split path into database. We only need this part of the path to access the images Token = 1, Score = 0, UserLevel = 0 }; PasswordHasher <User> Hasher = new PasswordHasher <User>(); newUser.Password = Hasher.HashPassword(newUser, newUser.Password); //Hash password _context.Add(newUser); _context.SaveChanges(); User activeUser = _context.users.Single(u => (string)u.Email == (string)model.Email); //re-obtain newly created User for Id information if (activeUser.UserId == 1) { activeUser.UserLevel = 9;//First user to admin _context.SaveChanges(); } HttpContext.Session.SetString("userName", activeUser.UserName); HttpContext.Session.SetInt32("activeUser", activeUser.UserId); TempData["pic"] = splitrootfile[1]; //for testing only to display the image path return(RedirectToAction("Dashboard", "Cleanup")); //Go to actual site } } return(View("RegistrationPartial")); //Failed registration attempt goes here }
public async Task <HttpResponseMessage> PostUser(UserRegisterViewModel viewModel) { UserCreateModel user = new UserCreateModel(viewModel); using (HttpClient client = new HttpClient()) { var token = await _identityServerTools.IssueClientJwtAsync( clientId : "identity_server", lifetime : 3600, audiences : new[] { "trackerApi" }); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); var json = JsonConvert.SerializeObject(user); var data = new StringContent(json, Encoding.UTF8, "application/json"); var result = await client.PostAsync(apiAddress + "Users", data); return(result); } }
public async Task <IActionResult> RegisterUserAsync([FromBody] UserRegisterViewModel userRegisterViewModel) { try { var user = mapper.Map <User>(userRegisterViewModel); user.Role = UserRoles.UserRole; await userService.CreateAsync(user); logger.LogInformation($"User register. Id: {user.Id}"); return(Ok(mapper.Map <UserDetailedViewModel>(user))); } catch (DbUpdateException exc) { logger.LogError(exc, exc.Message); return(BadRequest("User with specified email already exists.")); } }
public void Register(UserRegisterViewModel userRegisterViewModel) { var user = _userRepository.GetSingle(x => x.Email.Equals(userRegisterViewModel.Email.ToLowerInvariant())); if (user != null) { throw new GameScopeException("user_already_exists", "This email already registered"); } var salt = _encrypter.GetSalt(); var password = _encrypter.GetHash(userRegisterViewModel.Password, salt); var createUserCommand = new CreateUserCommand( userRegisterViewModel.Email.ToLowerInvariant(), password, salt ); _bus.SendCommand(createUserCommand); }
public IActionResult Register([Bind("Name,Email,Password,PasswordConfirm,Role")] UserRegisterViewModel m) { if (!ModelState.IsValid) { return(View(m)); } // add user via service var user = _svc.AddUser(m.Name, m.Email, m.Password, m.Role); // check if error adding user and display warning if (user == null) { Alert("There was a problem Registering. Please try again", AlertType.warning); return(View(m)); } Alert("Successfully Registered. Now login", AlertType.info); return(RedirectToAction(nameof(Login))); }
public async Task <string> AddAsync(UserRegisterViewModel userRegister) { if (await EmailAlreadyExists(userRegister.UserEmail)) { return("Esse email ja está cadastrado"); } userRegister.UserPassword = _cryptographyService.CreateEncryption(userRegister.UserPassword); var user = _mapper.Map <UserRegisterViewModel, User>(userRegister); var affectedRows = await _userRepository.AddAsync(user); if (affectedRows <= 0) { return("Erro ao cadastrar"); } return(string.Empty); }
public async Task<ActionResult> Register(UserRegisterViewModel model) { if (ModelState.IsValid) { var defaultAvatar = Image.FromFile(Server.MapPath("~/Content/images/photo.png")); var user = new UserProfile() { Email = model.Email, Password = Crypto.HashPassword(model.Password), UserName = model.Name, Avatar = defaultAvatar.ImageToByteArray() }; var result = await UserProfileManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SignInAsync(user, isPersistent: false); return RedirectToAction("wunderlist", "Wunderlist"); } ModelState.AddModelError("", result.Errors.ToString()); } return View(model); }
public virtual ActionResult Signup(UserRegisterViewModel user) { if (ModelState.IsValid) { var newUser = _mappingService.Map<UserRegisterViewModel, User>(user); var confirmation = _userService.AddUser(newUser, AccountType.Smoothie); if (confirmation.WasSuccessful) return RedirectToAction(MVC.Home.Index()); ModelState.AddModelError("Email", confirmation.Message); } return View(user); }
public ActionResult Register() { var model = new UserRegisterViewModel { User = new User() }; try { SinglePageService singlePageService = new SinglePageService(); model.RegNotice = singlePageService.GetSingPageById("94"); } catch (Exception) { } return View(model); }
public ActionResult Register() { var model = new UserRegisterViewModel { User = new User() }; try { SinglePageService singlePageService = new SinglePageService(); model.RegNotice = singlePageService.GetSingPageById("94"); if (CurrentWeChatUser.UserId.HasValue && CurrentUser != null) { model.ErrorMsg = "UserLoggedIn"; } } catch (Exception ex) { LogService.LogWexin("微信会员注册页面访问异常", ex.ToString()); } return View(model); }
internal RegisterEventArgs(UserRegisterViewModel userRegisterViewModel) { UserRegisterViewModel = userRegisterViewModel; }
public ActionResult Register() { var model = new UserRegisterViewModel { User = new User() }; try { SinglePageService singlePageService = new SinglePageService(); model.RegNotice = singlePageService.GetSingPageById("94"); } catch (Exception ex) { LogService.LogWexin("会员注册", ex.ToString()); } return View(model); }
// // GET: /User/Edit/5 public ActionResult Edit(int id = 0) { UserProfile userprofile = db.Users.Find(id); if (userprofile == null) { return HttpNotFound(); } var model = new UserRegisterViewModel(); var companyUserManger = ApplicationUserManager.Create(User.Identity.GetDatabaseName()); model.UserId = userprofile.Id; model.FirstName = userprofile.FirstName; model.LastName = userprofile.LastName; model.EmailAddress = userprofile.UserName; model.InitialEmail = userprofile.UserName; model.PhotoPath = userprofile.PhotoPath; var userrole = companyUserManger.IsInRoleAsync(userprofile.Id, "Admin"); //var roles = companyUserManger.(userprofile.Id); //model.IsAdmin = (roles.Length > 0 && roles[0] == "Admin") ? true : false; model.IsAdmin = userrole.Result; model.Availability = userprofile.Availability ?? false; model.DesignationId = userprofile.DesignationId; model.UserCode = userprofile.UserCode; model.EnablePIN = userprofile.EnablePIN; ViewBag.PhoneType = db.tabPhoneTypes.ToList(); ViewBag.PhoneNumbers = db.tabUserPhones.Where(p => p.UserId == id).ToList(); ViewBag.Designation = new SelectList(db.tabDesignations.ToList(), "DesignationId", "Desgination", userprofile.DesignationId); return View(model); }
public ActionResult Register(SHTS.Model.User user) { var userRegisterViewModel = new UserRegisterViewModel(); try { userRegisterViewModel.User = user; var errorMsg = string.Empty; bool result = false; bool vcodeVail = false; //取消手机验证逻辑 //if (Session["vcode"] == null) //{ // errorMsg = "请先输入手机验证码!"; //} //else if (!string.Equals(Session["vcode"].ToString(), // Request.Form["code"], StringComparison.InvariantCultureIgnoreCase)) //{ // errorMsg = "手机验证码输入错误!"; //} //else { vcodeVail = true; } if (vcodeVail) { user.LoginIdentiy = user.UserName; user.Photo = ConfigurationManager.AppSettings["DefaultPhoto"]; result = userService.UserRegister(user, out errorMsg); if (result) { //return Redirect("/mobile/account/login"); errorMsg = "SUCCESS"; CurrentUser = user; } } userRegisterViewModel.ErrorMsg = errorMsg; if (!result) { SinglePageService singlePageService = new SinglePageService(); userRegisterViewModel.RegNotice = singlePageService.GetSingPageById("94"); } } catch (Exception ex) { LogService.Log("注册用户", ex.ToString()); } return View(userRegisterViewModel); }
public async Task<ActionResult> Create(UserRegisterViewModel model) { try { if (ModelState.IsValid) { using (var companyUserManger = ApplicationUserManager.Create(User.Identity.GetDatabaseName())) { var result = await companyUserManger.CreateAsync(new UserProfile { Email = model.EmailAddress, FirstName = model.FirstName, LastName = model.LastName, UserName = model.EmailAddress, UserCode = model.UserCode, PhotoPath = model.PhotoPath, Availability = model.Availability, DesignationId = model.DesignationId, RestaurantName = User.Identity.GetDatabaseName(), TermAndCondition = true, EmailConfirmed = true, Approved = false }, model.Password); var getUseradd = await companyUserManger.FindByNameAsync(model.EmailAddress); if (model.IsAdmin) { companyUserManger.AddToRole(getUseradd.Id, "Admin"); } model.PhoneNumbers = model.PhoneNumbers.Replace("/", "\\/"); List<UserPhones> phnNumbers = (new JavaScriptSerializer()).Deserialize<List<UserPhones>>(model.PhoneNumbers); foreach (var phone in phnNumbers) { phone.UserId = getUseradd.Id; db.tabUserPhones.Add(phone); } var Mondoresult = await UserManager.CreateAsync(new UserProfile { Email = model.EmailAddress, FirstName = model.FirstName, LastName = model.LastName, UserName = model.EmailAddress, UserCode = model.UserCode, PhotoPath = model.PhotoPath, Availability = model.Availability, DesignationId = model.DesignationId, RestaurantName = User.Identity.GetDatabaseName(), TermAndCondition = true, }, model.Password); var Useradd = await UserManager.FindByNameAsync(model.EmailAddress); UserManager.AddToRole(Useradd.Id, "user"); return RedirectToAction("Index", new { id = getUseradd.Id }); } //return RedirectToAction("Index", new { id = user.Id }); } } catch (Exception) { string[] allRoles = Roles.GetRolesForUser(model.EmailAddress); if (allRoles.Count() > 0) { Roles.RemoveUserFromRoles(model.EmailAddress, allRoles); } //((SimpleMembershipProvider)Membership.Provider).DeleteAccount(model.EmailAddress); //Membership.Provider.DeleteUser(model.EmailAddress, true); //Membership.DeleteUser(model.EmailAddress, true); } finally { ClearStaffCache(); } ViewBag.PhoneType = new SelectList(db.tabPhoneTypes.ToList(), "PhoneTypeId", "PhoneType"); ViewBag.Designation = new SelectList(db.tabDesignations.ToList(), "DesignationId", "Desgination"); return View(model); }
public void Signup_Action_When_The_User_Model_Is_Valid_Returns_RedirectToRouteResult() { // Arrange const string expectedActionName = "Login"; const string expectedControllerName = "Account"; var registeredUser = new UserRegisterViewModel { Email = "*****@*****.**", Password = "******".Hash() }; var confirmation = new ActionConfirmation<User> { WasSuccessful = true, Message = "", Value = new User() }; _userService.Setup(r => r.AddUser(It.IsAny<User>(), It.IsAny<AccountType>())).Returns(confirmation); _accountController = new AccountController(_userService.Object, _mappingService.Object, _authenticationService.Object); // Act var result = _accountController.Signup(registeredUser) as RedirectToRouteResult; // Assert Assert.IsNotNull(result, "Should have returned a RedirectToRouteResult"); Assert.AreEqual(expectedActionName, result.RouteValues["Action"], "Action name should be {0}", expectedActionName); Assert.AreEqual(expectedControllerName, result.RouteValues["Controller"], "Controller name should be {0}", expectedControllerName); }
public ActionResult Edit(UserRegisterViewModel model) { var user = db.Users.Find(model.UserId); var companyUserManger = ApplicationUserManager.Create(User.Identity.GetDatabaseName()); try { model.PhoneNumbers = model.PhoneNumbers.Replace("/", "\\/"); List<UserPhones> phnNumbers = (new JavaScriptSerializer()).Deserialize<List<UserPhones>>(model.PhoneNumbers); var token = companyUserManger.GeneratePasswordResetToken(user.Id); if (model.IsPasswordChanged && !this.ResetPasswordWithToken(token, model.Password)) { throw new Exception("Failed to update password."); } var DBPhones = user.PhoneNumbers.ToList(); foreach (var phone in phnNumbers) { if (DBPhones.Any(p => p.PhoneNumber == phone.PhoneNumber)) { var dbphone = DBPhones.Where(p => p.PhoneNumber == phone.PhoneNumber).Single(); dbphone.PhoneTypeId = phone.PhoneTypeId; db.Entry(dbphone).State = System.Data.Entity.EntityState.Modified; } else { phone.UserId = user.Id; user.PhoneNumbers.Add(phone); } } foreach (var dbphone in DBPhones) { if (!phnNumbers.Any(p => p.PhoneNumber == dbphone.PhoneNumber)) { user.PhoneNumbers.Remove(dbphone); } } if (model.IsAdmin) { //var roles = Roles.GetRolesForUser(model.EmailAddress); //if (!roles.Contains("Admin")) //{ // Roles.AddUserToRole(model.EmailAddress, "Admin"); //} companyUserManger.AddToRole(model.UserId.Value, "Admin"); } else { var roles = companyUserManger.GetRoles(model.UserId.Value); if (roles.Contains("Admin")) { companyUserManger.RemoveFromRole(model.UserId.Value, "Admin"); } } user.FirstName = model.FirstName; user.LastName = model.LastName; user.PhotoPath = model.PhotoPath; user.Availability = model.Availability; user.DesignationId = model.DesignationId; user.UserCode = model.UserCode; user.EnablePIN = model.EnablePIN; db.Entry(user).State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index", new { id = user.Id }); } catch (Exception) { ViewBag.PhoneType = db.tabPhoneTypes.ToList(); ViewBag.PhoneNumbers = db.tabUserPhones.Where(p => p.UserId == user.Id).ToList(); ViewBag.Designation = new SelectList(db.tabDesignations.ToList(), "DesignationId", "Desgination"); return View(model); } finally { ClearStaffCache(); } }