public async Task <ActionResult> SignUp(AccountSignUpViewModel model, string returnUrl) { if (ModelState.IsValid) { var adminUser = new AppUserEntity { FullName = model.Name, Email = model.Email, CultureId = User.Culture.Name, UICultureId = User.UICulture.Name, TimeZoneId = User.TimeZone.Id }; // adminUser.SetDefaultUserName(); // adminUser.Realms.Add(Realm.AdminWebsite); // adminUser.Roles.Add(Role.Basic); // var result = await _appUserManager.CreateAsync(adminUser, model.Password); if (result.Succeeded) { var isPersistent = false; _signInManager.InitialPersistenceState = isPersistent; await _signInManager.SignInAsync( adminUser, isPersistent, rememberBrowser : false ); return(RedirectToLocal(returnUrl)); } ModelState.AddModelError(string.Empty, GetLocalizedString <AreaResources>("DefaultErrorMessage")); } ViewBag.ReturnUrl = returnUrl; return(View(model)); }
public async Task <IActionResult> SignUp(AccountSignUpViewModel model) { string returnUrl = Url.Content("~/"); if (!ModelState.IsValid) { return(View(model)); } var user = new User { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { Logger.LogInformation("User created a new account with password."); var code = await UserManager.GenerateEmailConfirmationTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); var callbackUrl = Url.Action( "ConfirmEmail", "Account", values: new { area = "Identity", userId = user.Id, code = code }, protocol: Request.Scheme); await EmailSender.SendEmailAsync(model.Email, "Confirm your email", $"Please confirm your account by <a href='{ HtmlEncoder.Default.Encode(callbackUrl) }'>clicking here</a>."); if (UserManager.Options.SignIn.RequireConfirmedAccount) { return(RedirectToAction("SignUpConfirmation", new { email = model.Email })); } else { await SignInManager.SignInAsync(user, isPersistent : false); return(Redirect(returnUrl)); } } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } return(View(model)); }
public IActionResult SignUp(AccountSignUpViewModel accountSignUpViewModel) { if (!ModelState.IsValid) { return(Redirect("/site/vertical/pages-register.html")); } var json = JsonConvert.SerializeObject(accountSignUpViewModel); var data = new StringContent(json, Encoding.UTF8, "application/json"); var result = _client.PostAsync("api/accounts", data).Result; if (result.StatusCode == System.Net.HttpStatusCode.OK) { return(Redirect("/site/vertical/pages-login.html")); } return(Redirect("/site/vertical/pages-register.html")); }
/// <summary> /// Authenticates a user account returned from the Web Account Manager service. /// </summary> /// <param name="wi">Web account info object instance representing an authenticated WAM user.</param> /// <param name="ct">Cancellation token.</param> /// <returns>Response object from the server.</returns> public async Task <UserResponse> AuthenticateAsync(Services.WebAccountManager.WebAccountInfo wi, CancellationToken ct) { // This logic below should be server side. Token should be used to retrieve MSA and then check to see if MediaAppSample account exists else register new account. switch (wi.Type) { case Services.WebAccountManager.WebAccountTypes.Microsoft: { // Retrieve MSA profile data MicrosoftAccountDetails msa = null; using (var api = new MicrosoftApi()) { msa = await api.GetUserProfile(wi.Token, ct); } if (msa == null) { throw new Exception("Could not retrieve Microsoft account profile data!"); } var response = await this.IsMicrosoftAccountRegistered(msa.id, ct); if (response != null) { // User account exists, return response return(response); } else { // No account exists, use MSA profile to register user AccountSignUpViewModel vm = new AccountSignUpViewModel(); // Set all the MSA data to the ViewModel vm.Populate(msa); // Call the registration API to create a new account and return return(await this.RegisterAsync(vm, ct)); } } default: throw new NotImplementedException(wi.Type.ToString()); } }
//[Route("~/[controller]/[action]")] public async Task <IActionResult> SignUp(string returnUrl) { if (this._signInManager.IsSignedIn(User)) { return(RedirectToAction("Index", "Home")); } var model = new AccountSignUpViewModel() { DateOfBirth = DateTime.Now, ExternalLogins = new ExternalLoginsViewModel() { ReturnUrl = returnUrl, ExternalLogins = (await this._signInManager.GetExternalAuthenticationSchemesAsync()).ToList() } }; return(View(model)); }
public ActionResult SignUp(bool?isdialog, SocialType social = SocialType.None, string returnUrl = null) { var model = new AccountSignUpViewModel { SocialType = social, ConnectSocial = true, ReturnUrl = returnUrl }; if (isdialog.HasValue) { if (isdialog.Value) { return(View("SignUp", "_LightLayout", model)); } } return(View(model)); }
/// <summary> /// Performs account creation for the application. /// </summary> /// <param name="vm">Sign up view model instance containing all the user's registration information.</param> /// <returns>Login response and authorization information if the account creation process was successful.</returns> public async Task <UserResponse> RegisterAsync(AccountSignUpViewModel vm, CancellationToken ct) { var response = new UserResponse() { AccessToken = "0987654321", RefreshToken = "qrstuvwxwyz", ID = vm.Username, Email = vm.Username, FirstName = vm.FirstName, LastName = vm.LastName }; await Task.Delay(2000, ct); return(response); //var dic = new Dictionary<string, string>(); //dic.Add("grant_type", "password"); //dic.Add("username", vm.Username); //dic.Add("password", vm.Password1); //dic.Add("scope", "streaming"); //var contents = new HttpFormUrlEncodedContent(dic); //HttpStringContent content = new HttpStringContent(message.Stringify(), UnicodeEncoding.Utf8, "application/json"); //return await this.PostAsync<UserResponse, HttpFormUrlEncodedContent>(URL_ACCOUNT_SIGNUP, contents); }
public async Task <ActionResult> SignUp(AccountSignUpViewModel viewModel) { if (ModelState.IsValid) { var existingUser = await _userManager.FindByEmailAsync(viewModel.Email); if (existingUser != null) { ModelState.AddModelError("Email", "The provided email address has already been used."); } else { var user = new User { UserName = viewModel.Email, Email = viewModel.Email }; var result = await _userManager.CreateAsync(user, viewModel.Password); if (result.Succeeded) { var userProfile = new UserProfile { FullName = viewModel.FullName, JoinDate = DateTime.Today, UserId = user.Id }; _userProfileRepository.Add(userProfile); await _signInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); return(RedirectToAction("Index", "Member")); } foreach (var error in result.Errors) { ModelState.AddModelError("", error); } } } return(View(viewModel)); }
public async Task <IActionResult> SignUp(AccountSignUpViewModel model) { model.DateOfBirth = (model.DateOfBirth.Year == 1 ? DateTime.Now : model.DateOfBirth); model.ExternalLogins .ExternalLogins = (await this._signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); if (ModelState.IsValid) { var user = new AppUser { UserName = model.Email, FirstName = model.FirstName, LastName = model.LastName, Gendre = model.Gendre, DateOfBirth = model.DateOfBirth, Email = model.Email }; var result = await this._userManager.CreateAsync(user, model.Password); if (result.Succeeded) { // isPersistent if true keeps us signed in even when close the browser await this._signInManager.SignInAsync(user, isPersistent : false); return(RedirectToAction("Index", "Home")); } foreach (var error in result.Errors) { ModelState.AddModelError("", error.Description); } } return(View(model)); }
public async Task <IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null) { returnUrl = returnUrl ?? Url.Content("~/"); var login = new AccountSignUpViewModel() { ExternalLogins = new ExternalLoginsViewModel() { ReturnUrl = returnUrl, ExternalLogins = (await this._signInManager.GetExternalAuthenticationSchemesAsync()).ToList() } }; if (remoteError != null) { ModelState.AddModelError(string.Empty, $"Error from External Provider: {remoteError}"); return(View(nameof(SignIn), login)); } var info = await this._signInManager.GetExternalLoginInfoAsync(); if (info == null) { ModelState.AddModelError(string.Empty, "Error Loading External Login Information."); return(View(nameof(SignIn), login)); } var email = info.Principal.FindFirstValue(ClaimTypes.Email); AppUser user = null; if (email != null) { user = await this._userManager.FindByEmailAsync(email); } var signInResult = await this._signInManager.ExternalLoginSignInAsync ( info.LoginProvider, info.ProviderKey, isPersistent : false, bypassTwoFactor : true ); if (signInResult.Succeeded) { return(LocalRedirect(returnUrl)); } else { if (email != null) { if (user == null) { var firstName = info.Principal.FindFirstValue(ClaimTypes.GivenName); var lastName = info.Principal.FindFirstValue(ClaimTypes.Surname); var name = info.Principal.FindFirstValue(ClaimTypes.Name); var gendre = info.Principal.FindFirstValue(ClaimTypes.Gender); user = new AppUser { UserName = email, Email = email, FirstName = firstName == null ? "User" : firstName, LastName = lastName == null ? "User" : lastName, Gendre = gendre == null ? "unset" : gendre }; var generatedUserPassword = GenerateRandomPassword(); var result = await this._userManager.CreateAsync(user, generatedUserPassword); if (!result.Succeeded) { return(RedirectToAction(nameof(SignUp), login)); } var token = await this._userManager.GenerateEmailConfirmationTokenAsync(user); var confirmationLink = Url.Action( "ConfirmEmail", "Account", new { userId = user.Id, token = token }, Request.Scheme ); this._logger.LogWarning ( $"\n\n\n" + $"\nUser: {email}" + $"\nGenerated Password: \"{generatedUserPassword}\"" + $"\nGenerated Email Confirmation: \"{confirmationLink}\"" + $"\n\n\n" ); } await this._userManager.AddLoginAsync(user, info); await this._signInManager.SignInAsync(user, isPersistent : true); return(LocalRedirect(returnUrl)); } var modl = new StatusResultViewModel(); modl.Title = $"Email claim not received from: {info.LoginProvider}"; modl.Message = "Please contact support on [email protected]"; return(View("../Error/NotFound", modl)); } }
public ActionResult SignUp(AccountSignUpViewModel model, bool?isdialog) { if (ModelState.IsValid) { var phone = UserService.NormalizePhoneNumber(model.PhoneNumber); var encryptedPhoneNumber = CryptographyService.EncryptPhone(phone); var usersWithSamePhone = DataService.PerThread.BaseUserSet.OfType <User>().Count(u => u.EncryptedPhoneNumber == encryptedPhoneNumber); if (usersWithSamePhone != 0) { throw new ValidationException("Пользователь с таким номером телефона уже зарегистрирован"); } var encryptedEmail = CryptographyService.EncryptEmail(model.Email); var usersWithSameEmail = DataService.PerThread.BaseUserSet.OfType <User>().Count(u => u.EncryptedEmail == encryptedEmail); if (usersWithSameEmail != 0) { throw new ValidationException("Пользователь с такой электропочтой уже зарегистрирован"); } var user = (User)AccountService.SignUp(model.Email, model.Email, model.Password, false); user.FirstName = model.Name; user.SurName = model.SurName; user.Patronymic = model.Patronymic; user.PhoneNumber = phone; user.Sex = ValueAnalizer.GetGenderFromString(model.Gender); user.IsPhoneVerified = false; user.IsEmailVerified = false; user.IsOutdated = true; UserService.NormalizePhoneNumber(user); if (model.ConnectSocial && HttpContext.Session["social_type"] != null && HttpContext.Session["social_id"] != null && HttpContext.Session["social_link"] != null) { var socialType = (SocialType)HttpContext.Session["social_type"]; var socialLink = HttpContext.Session["social_link"].ToString(); var socialKey = HttpContext.Session["social_id"].ToString(); var usersWithSameSocial = DataService.PerThread.SocialAccountSet.Count(u => u.SocialId == socialKey && u.SocialType == (byte)socialType); if (usersWithSameSocial != 0) { throw new ValidationException("Пользователь с таким аккаунтом " + model.SocialType.ToString() + " уже зарегистрирован"); } AccountService.ConnectSocialAccount(user, socialType, socialLink, socialKey); HttpContext.Session.Remove("social_id"); HttpContext.Session.Remove("social_type"); HttpContext.Session.Remove("social_link"); } DataService.PerThread.SaveChanges(); //var code = AccountService.GenerateSecretCode(user.Id); //var sms = "Ваш секретный код для верификации на Демократии2: " + code; //SmsService.SendMessage("+7" + telephone, sms); //var smtp = new SmtpClient(); //var link = ConstHelper.AppUrl + Url.Action("codeVerification", new { id = user.Id }); //var message = new MailMessage //{ // Subject = "Ввод кода подтверждения на Демократии2", // Body = "<p>Если вы еще не ввели код подтверждения, пришедший вам по смс, перейдите по ссылке: <a href='" + link + "'>" + link + "</a>.</p>" + // "<p>Если вам не пришло смс, напишите на <a href='mailto:[email protected]'>[email protected]</a></p>", // IsBodyHtml = true //}; //message.To.Add(user.Email); //smtp.Send(message); //smtp.Dispose(); AccountService.SendEmailVerification(user.Id); AccountService.TrySignIn(model.Email, model.Password, true, HttpContext.Request.UserHostAddress); MonitoringService.AsynchLogUserRegistration(user.Id, HttpContext.Request.UserHostAddress); if (string.IsNullOrWhiteSpace(model.ReturnUrl)) { return(RedirectToAction("index", "user")); } return(Redirect(model.ReturnUrl)); } if (isdialog.HasValue) { if (isdialog.Value) { return(View("SignUp", "_LightLayout", model)); } } return(View(model)); }