public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return(RedirectToAction("Index", "Manage")); } if (ModelState.IsValid) { // Obtener datos del usuario del proveedor de inicio de sesión externo var info = await AuthenticationManager.GetExternalLoginInfoAsync(); if (info == null) { return(View("ExternalLoginFailure")); } var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user); if (result.Succeeded) { result = await UserManager.AddLoginAsync(user.Id, info.Login); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); return(RedirectToLocal(returnUrl)); } } AddErrors(result); } ViewBag.ReturnUrl = returnUrl; return(View(model)); }
public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return(RedirectToAction("Index", "Manage")); } if (ModelState.IsValid) { // Получение сведений о пользователе от внешнего поставщика входа var info = await AuthenticationManager.GetExternalLoginInfoAsync(); if (info == null) { return(View("ExternalLoginFailure")); } var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user); if (result.Succeeded) { result = await UserManager.AddLoginAsync(user.Id, info.Login); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); return(RedirectToLocal(returnUrl)); } } AddErrors(result); } ViewBag.ReturnUrl = returnUrl; return(View(model)); }
public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return(RedirectToAction("Index", "Manage")); } if (ModelState.IsValid) { // Uzyskaj informacje o użytkowniku od dostawcy logowania zewnętrznego var info = await AuthenticationManager.GetExternalLoginInfoAsync(); if (info == null) { return(View("ExternalLoginFailure")); } var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user); if (result.Succeeded) { result = await UserManager.AddLoginAsync(user.Id, info.Login); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); return(RedirectToLocal(returnUrl)); } } AddErrors(result); } ViewBag.ReturnUrl = returnUrl; return(View(model)); }
public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return(RedirectToAction("Index", "Manage")); } if (ModelState.IsValid) { // Get the information about the user from the external login provider ExternalLoginInfo info = await AuthenticationManager.GetExternalLoginInfoAsync(); if (info == null) { return(View("ExternalLoginFailure")); } ApplicationUser user = new ApplicationUser { UserName = model.Email, Email = model.Email }; IdentityResult result = await UserManager.CreateAsync(user); if (result.Succeeded) { result = await UserManager.AddLoginAsync(user.Id, info.Login); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); return(RedirectToLocal(returnUrl)); } } AddErrors(result); } ViewBag.ReturnUrl = returnUrl; return(View(model)); }
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return RedirectToAction("Index", "Manage"); } if (ModelState.IsValid) { // Obtenez des informations sur l’utilisateur auprès du fournisseur de connexions externe var info = await AuthenticationManager.GetExternalLoginInfoAsync(); if (info == null) { return View("ExternalLoginFailure"); } var user = new ApplicationUser { UserName = model.Email, Email = model.Email, DrivingLicense = model.DrivingLicense, Phone = model.Phone }; var result = await UserManager.CreateAsync(user); if (result.Succeeded) { result = await UserManager.AddLoginAsync(user.Id, info.Login); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); return RedirectToLocal(returnUrl); } } AddErrors(result); } ViewBag.ReturnUrl = returnUrl; return View(model); }
public async Task <IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null) { if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await this.signInManager.GetExternalLoginInfoAsync(); if (info == null) { return(View("ExternalLoginFailure")); } var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await this.userManager.CreateAsync(user); if (result.Succeeded) { result = await this.userManager.AddLoginAsync(user, info); if (result.Succeeded) { await this.signInManager.SignInAsync(user, isPersistent : false); this.logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider); return(RedirectToLocal(returnUrl)); } } AddErrors(result); } ViewData["ReturnUrl"] = returnUrl; return(View(model)); }
public async Task <ActionResult> EditBasicInfo(ExternalLoginConfirmationViewModel model)// ApplicationUser user) { if (ModelState.IsValid) { //var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())); //var user = manager.FindById(User.Identity.GetUserId()); //user.Birthday = model.Birthday; //user.HomeTown = model.HomeTown; var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); user.Email = model.Email; user.HomeTown = model.HomeTown; user.Birthday = model.Birthday; user.PhoneNumber = model.PhoneNumber; //user.UserIdCode = model.UserIdCode; await UserManager.UpdateAsync(user);// manager.UpdateAsync(user); return(View(model)); } else { return(View(model)); } }
public async Task <IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, bool isClientLogin = false, string returnUrl = null) { if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { return(View("ExternalLoginFailure")); } var user = new ApplicationUser { UserName = model.UserName }; var result = await _userManager.CreateAsync(user); if (result.Succeeded) { result = await _userManager.AddLoginAsync(user, info); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent : false); _logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider); return(RedirectOrCallback(returnUrl, isClientLogin, user.UserName, user.AccessToken)); } } AddErrors(result); } ViewData["ReturnUrl"] = returnUrl; ViewData["IsClientLogin"] = isClientLogin; return(View(model)); }
private static ExternalLoginConfirmationViewModel CreateExternalLoginConfirmationViewModel(string email = "*****@*****.**", string firstName = "FirstName", string lastName = "LastName", string phoneNumber = "(111)111-11-11") { var result = new ExternalLoginConfirmationViewModel { Email = email, FirstName = firstName, LastName = lastName, PhoneNumber = phoneNumber }; return result; }
public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return(RedirectToAction("Index", "Manage")); } if (ModelState.IsValid) { var loginInfo = Session["UserLoginInfo"] as UserLoginInfo; if (loginInfo == null) { return(RedirectToAction("Login", "Account")); } List <Claim> claims = new List <Claim>() { new Claim(WellKnown.ConfirmEmailViewModelClaim, JsonConvert.SerializeObject(new ConfirmEmailViewModel() { ConfirmEmailPurpose = ConfirmEmailPurpose.ConfirmEmailPurpose_CreateExternalAccount, Email = model.Email })), new Claim(WellKnown.UserLoginInfoClaim, JsonConvert.SerializeObject(loginInfo)), }; var now = DateTime.UtcNow; var lifetime = new Lifetime(now, now.AddMinutes(30)); var jwt = IdentityTokenHelper.BuildJWT(claims, WellKnown.ValidIssuer, WellKnown.EmailConfirmationAudience, lifetime); var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = "na", code = jwt }, protocol: Request.Url.Scheme); await UserManager.EmailService.SendAsync(new IdentityMessage() { Destination = model.Email, Subject = "Confirm your account!", Body = "You have 30 minutes to confirm your account by clicking here: " + callbackUrl }); return(RedirectToAction("EmailConfirmationSent", "Account", new { email = model.Email })); // await UserManager.SendEmailAsync(userId, "Confirm your account", "You have 30 minutes to confirm your account by clicking here: " + callbackUrl); /* * * // Get the information about the user from the external login provider * var info = await AuthenticationManager.GetExternalLoginInfoAsync(); * if (info == null) * { * return View("ExternalLoginFailure"); * } * var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; * var result = await UserManager.CreateAsync(user); * if (result.Succeeded) * { * result = await UserManager.AddLoginAsync(user.Id, info.Login); * if (result.Succeeded) * { * await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); * return RedirectToLocal(returnUrl); * } * } * AddErrors(result); */ } ViewBag.ReturnUrl = returnUrl; return(View(model)); }
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return RedirectToAction("Manage"); } if (ModelState.IsValid) { // Get the information about the user from the external login provider ClaimsIdentity id = await HttpContext.GetExternalIdentity(); if (id == null) { return View("ExternalLoginFailure"); } try { // Create a local user and sign in var user = new User(model.UserName); if (await Users.Create(user) && await Logins.Add(new UserLogin(user.Id, model.LoginProvider, id.FindFirstValue(ClaimTypes.NameIdentifier)))) { await SignIn(user.Id, id.Claims, isPersistent: false); return RedirectToLocal(returnUrl); } else { return View("ExternalLoginFailure"); } } catch (DbEntityValidationException e) { ModelState.AddModelError("", e.EntityValidationErrors.First().ValidationErrors.First().ErrorMessage); } } ViewBag.ReturnUrl = returnUrl; return View(model); }
public async Task <IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { log.LogDebug("ExternalLoginConfirmation called with returnurl " + returnUrl); //if (signInManager.IsSignedIn(User)) //{ // return RedirectToAction("Index", "Manage"); //} if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await signInManager.GetExternalLoginInfoAsync(); if (info == null) { return(View("ExternalLoginFailure")); } var userName = model.Email.Replace("@", string.Empty).Replace(".", string.Empty); var userNameAvailable = await userManager.LoginIsAvailable(Guid.Empty, userName); if (!userNameAvailable) { userName = model.Email; } var user = new SiteUser { SiteId = Site.Id, UserName = userName, Email = model.Email, AccountApproved = Site.RequireApprovalBeforeLogin ? false : true }; var result = await userManager.CreateAsync(user); if (result.Succeeded) { log.LogDebug("ExternalLoginConfirmation user created "); await ipAddressTracker.TackUserIpAddress(Site.Id, user.Id); result = await userManager.AddLoginAsync(user, info); if (result.Succeeded) { log.LogDebug("ExternalLoginConfirmation AddLoginAsync succeeded "); if (Site.RequireConfirmedEmail) // require email confirmation { var code = await userManager.GenerateEmailConfirmationTokenAsync(user); var callbackUrl = Url.Action(new UrlActionContext { Action = "ConfirmEmail", Controller = "Account", Values = new { userId = user.Id.ToString(), code = code }, Protocol = HttpContext.Request.Scheme }); emailSender.SendAccountConfirmationEmailAsync( Site, model.Email, sr["Confirm your account"], callbackUrl).Forget(); // this is needed to clear the external cookie - wasn't needed in rc2 await signInManager.SignOutAsync(); if (this.SessionIsAvailable()) { this.AlertSuccess(sr["Please check your email inbox, we just sent you a link that you need to click to confirm your account"], true); return(Redirect("/")); } else { return(RedirectToAction("EmailConfirmationRequired", new { userId = user.Id, didSend = true })); } } else { if (Site.RequireApprovalBeforeLogin) { emailSender.AccountPendingApprovalAdminNotification(Site, user).Forget(); // this is needed to clear the external cookie - wasn't needed in rc2 await signInManager.SignOutAsync(); return(RedirectToAction("PendingApproval", new { userId = user.Id, didSend = true })); } else { await signInManager.SignInAsync(user, isPersistent : false); if (!string.IsNullOrEmpty(returnUrl)) { return(LocalRedirect(returnUrl)); } return(this.RedirectToSiteRoot(Site)); } } } else { log.LogDebug("ExternalLoginConfirmation AddLoginAsync failed "); } } else { log.LogDebug("ExternalLoginConfirmation failed to user created "); } AddErrors(result); } else { log.LogDebug("ExternalLoginConfirmation called with ModelStateInvalid "); model.RegistrationPreamble = Site.RegistrationPreamble; model.RegistrationAgreement = Site.RegistrationAgreement; model.AgreementRequired = Site.RegistrationAgreement.Length > 0; } ViewData["ReturnUrl"] = returnUrl; return(View(model)); }
public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null) { if (User.IsSignedIn()) { return RedirectToAction("Index", "Manage"); } if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await SignInManager.GetExternalLoginInfoAsync(); if (info == null) { return View("ExternalLoginFailure"); } var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user); if (result.Succeeded) { result = await UserManager.AddLoginAsync(user, info); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent: false); return RedirectToLocal(returnUrl); } } AddErrors(result); } ViewBag.ReturnUrl = returnUrl; return View(model); }
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return RedirectToAction("Manage"); } if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await AuthenticationManager.GetExternalLoginInfoAsync(); if (info == null) { return View("ExternalLoginFailure"); } var user = new TasklyUser() { UserName = model.Email, Email = model.Email }; IdentityResult result = await UserManager.CreateAsync(user); if (result.Succeeded) { result = await UserManager.AddLoginAsync(user.Id, info.Login); if (result.Succeeded) { await SignInAsync(user, isPersistent: false); // // create the organisation at sign-up // var organisation = new Organisation { Name = model.Organisation, AccountType = OrgAccountType.free }; var db = new TasklyDbContext(); db.Organisations.Add(organisation); db.SaveChanges(); db.Dispose(); user.UserDisplayName = model.UserDisplayName; user.OrganisationID = organisation.ID; UserManager.Update(user); DemoSurvey.CreateDemo(organisation.ID); // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // SendEmail(user.Email, callbackUrl, "Confirm your account", "Please confirm your account by clicking this link"); return RedirectToLocal(returnUrl); } } AddErrors(result); } ViewBag.ReturnUrl = returnUrl; return View(model); }
public async Task<ActionResult> ExternalLoginConfirmation( ExternalLoginConfirmationViewModel model, string returnUrl) { if (this.User.Identity.IsAuthenticated) { return this.RedirectToAction("Index", "Manage"); } if (this.ModelState.IsValid) { // Get the information about the user from the external login provider var info = await this.AuthenticationManager.GetExternalLoginInfoAsync(); if (info == null) { return this.View("ExternalLoginFailure"); } var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await this.UserManager.CreateAsync(user); if (result.Succeeded) { result = await this.UserManager.AddLoginAsync(user.Id, info.Login); if (result.Succeeded) { await this.SignInManager.SignInAsync(user, false, false); return this.RedirectToLocal(returnUrl); } } this.AddErrors(result); } this.ViewBag.ReturnUrl = returnUrl; return this.View(model); }
public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return(RedirectToAction("Index", "Manage")); } if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await AuthenticationManager.GetExternalLoginInfoAsync(); if (info == null) { return(View("ExternalLoginFailure")); } var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user); if (result.Succeeded) { //Create the iMentorUser entry using (iMAST_dbEntities db = new iMAST_dbEntities()) { bool userExists = false; foreach (iMentorUser u in db.iMentorUsers.ToList()) { if (u.Email.Equals(user.Email)) { userExists = true; } } //Create the user if (!userExists) { var imUser = new iMentorUser(); imUser.UserName = user.UserName; imUser.Email = user.Email; imUser.UrlId = GetNewUrlId(); db.iMentorUsers.Add(imUser); db.SaveChanges(); //Create the Role var imUserRole = new iMentorUserRole(); imUserRole.UserId = imUser.Id; imUserRole.RoleId = db.iMentorRoles.Where(x => x.RoleName.Equals("Read Only")).FirstOrDefault().Id; //Default role is "Read Only" db.iMentorUserRoles.Add(imUserRole); db.SaveChanges(); } } result = await UserManager.AddLoginAsync(user.Id, info.Login); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); return(RedirectToAction("Index", "Home")); } } AddErrors(result); } //ViewBag.ReturnUrl = returnUrl; //return View(model); return(RedirectToAction("Index", "Home")); }
public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return(RedirectToAction("Manage")); } if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await AuthenticationManager.GetExternalLoginInfoAsync(); if (info == null) { return(View("ExternalLoginFailure")); } crm_Users crm_user = new crm_Users(); crm_user.Username = model.UserName; crm_user.FullName = model.UserName; var provider = info.Login.LoginProvider; var url = info.Login.ProviderKey; switch (provider.ToLower()) { case "google": { crm_user.GoogleplusURL = url; break; } case "facebook": { crm_user.FacebookURL = url; break; } case "twitter": { crm_user.TwitterURL = url; break; } case "linkedin": { crm_user.LinkedURL = url; break; } } _userService.Insert(crm_user); int InResult = _unitOfWork.SaveChanges(); if (InResult == 1) { Session["LogOn"] = model.UserName; return(RedirectToRoute( "Admin_Default", new { controller = "Dashboard", action = "Index" })); } } ViewBag.ReturnUrl = returnUrl; return(RedirectToRoute( "Admin_Default", new { controller = "Dashboard", action = "Index" })); }
public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel viewModel) { if (ModelState.IsValid) { // If the user aleady has an account with any other provider, log them in. if (await LoginIfExternalProviderAlreadyAssignedAsync() && User.Identity.IsAuthenticated) { return(RedirectToAction("Index", "Start")); } // Get the information about the user from the external login provider var socialLoginDetails = await UserService.GetExternalLoginInfoAsync(); if (socialLoginDetails == null) { return(View("ExternalLoginFailure")); } string firstName = null; string lastName = null; var nameClaim = socialLoginDetails.ExternalIdentity.Claims.FirstOrDefault(x => x.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"); if (nameClaim != null) { string[] names = nameClaim.Value.Split(' '); firstName = names[0]; lastName = names.Length > 1 ? names[1] : string.Empty; } string eMail = socialLoginDetails.Email; var customerAddress = CustomerAddress.CreateInstance(); customerAddress.Line1 = viewModel.Address; customerAddress.PostalCode = viewModel.PostalCode; customerAddress.City = viewModel.City; customerAddress.CountryName = viewModel.Country; var user = new SiteUser { UserName = eMail, Email = eMail, FirstName = firstName, LastName = lastName, RegistrationSource = "Social login", NewsLetter = viewModel.Newsletter, IsApproved = true }; var result = await UserManager.CreateAsync(user); if (result.Succeeded) { user.Addresses = new List <CustomerAddress>(new[] { customerAddress }); UserService.CreateCustomerContact(user); result = await UserManager.AddLoginAsync(user.Id, socialLoginDetails.Login); if (result.Succeeded) { return(RedirectToLocal(viewModel.ReturnUrl)); } } AddErrors(result.Errors); } return(View(viewModel)); }
public async Task <IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null) { if (_signInManager.IsSignedIn(User)) { return(RedirectToAction(nameof(ManageController.Index), "Manage")); } if (ModelState.IsValid) { var externalLoginInfo = await _signInManager.GetExternalLoginInfoAsync(); if (externalLoginInfo == null) { return(View("ExternalLoginFailure")); } var user = new ApplicationUser { UserName = model.Email, Email = model.Email, TimeZoneId = _generalSettings.Value.DefaultTimeZone, FirstName = model.FirstName, LastName = model.LastName, PhoneNumber = model.PhoneNumber }; var result = await _userManager.CreateAsync(user); if (result.Succeeded) { result = await _userManager.AddLoginAsync(user, externalLoginInfo); if (result.Succeeded) { var emailConfirmationToken = await _userManager.GenerateEmailConfirmationTokenAsync(user); if (model.EmailIsVerifiedByExternalLoginProvider) { await _userManager.ConfirmEmailAsync(user, emailConfirmationToken); } else { var callbackUrl = Url.Action(new UrlActionContext { Action = nameof(ConfirmEmail), Controller = "Account", Values = new { userId = user.Id, token = emailConfirmationToken }, Protocol = HttpContext.Request.Scheme }); await _mediator.SendAsync(new SendConfirmAccountEmail { Email = user.Email, CallbackUrl = callbackUrl }); } var changePhoneNumberToken = await _userManager.GenerateChangePhoneNumberTokenAsync(user, model.PhoneNumber); await _mediator.SendAsync(new SendAccountSecurityTokenSms { PhoneNumber = model.PhoneNumber, Token = changePhoneNumberToken }); await _userManager.AddClaimAsync(user, new Claim(Security.ClaimTypes.ProfileIncomplete, "NewUser")); await _signInManager.SignInAsync(user, isPersistent : false); return(_redirectAccountControllerRequests.RedirectToLocal(returnUrl, user)); } } AddErrorsToModelState(result); } ViewData["ReturnUrl"] = returnUrl; return(View(model)); }
public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return(RedirectToAction("Index", "Manage")); } if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await AuthenticationManager.GetExternalLoginInfoAsync(); if (info == null) { return(View("ExternalLoginFailure")); } var user = new ApplicationUser { UserName = model.Email, Email = model.Email, Firstname = model.Firstname, Lastname = model.Lastname, Fathername = model.Fathername, Mothername = model.Mothername, DateOfBirth = model.DateOfBirth, Address1 = model.Address1, Address2 = model.Address2, City = model.City, Country = model.Country, Institution = model.Institution, Program = model.Program, YearOfJoining = model.YearOfJoining, PhoneNumber = model.Mobile }; var result = await UserManager.CreateAsync(user); if (result.Succeeded) { result = await UserManager.AddLoginAsync(user.Id, info.Login); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); return(RedirectToLocal(returnUrl)); } } AddErrors(result); } ViewBag.ReturnUrl = returnUrl; List <SelectListItem> list = new List <SelectListItem>(); foreach (var rolee in RoleManager.Roles) { list.Add(new SelectListItem() { Value = rolee.Name, Text = rolee.Name }); } ViewBag.Roles = list; return(View(model)); }
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return RedirectToAction("Manage"); } if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await AuthenticationManager.GetExternalLoginInfoAsync(); if (info == null) { return View("ExternalLoginFailure"); } var externalIdentity = HttpContext.GetOwinContext().Authentication.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie); var emailClaim = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email); var email = emailClaim != null ? emailClaim.Value : null; var user = new ApplicationUser() { UserName = model.UserName, Email = email }; var result = await UserManager.CreateAsync(user); if (result.Succeeded) { result = await UserManager.AddLoginAsync(user.Id, info.Login); if (result.Succeeded) { _logger.Info("Created user {0} ({1}).", user.UserName, user.Email); await SignInAsync(user, isPersistent: false); return RedirectToLocal(returnUrl); } } AddErrors(result); } ViewBag.ReturnUrl = returnUrl; return View(model); }
public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { log.LogDebug("ExternalLoginConfirmation called with returnurl " + returnUrl); if (signInManager.IsSignedIn(User)) { return RedirectToAction("Index", "Manage"); } if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await signInManager.GetExternalLoginInfoAsync(); if (info == null) { return View("ExternalLoginFailure"); } var user = new SiteUser { SiteId = Site.Id, UserName = model.Email, Email = model.Email }; var result = await userManager.CreateAsync(user); if (result.Succeeded) { log.LogDebug("ExternalLoginConfirmation user created "); await ipAddressTracker.TackUserIpAddress(Site.Id, user.Id); result = await userManager.AddLoginAsync(user, info); if (result.Succeeded) { log.LogDebug("ExternalLoginConfirmation AddLoginAsync succeeded "); await signInManager.SignInAsync(user, isPersistent: false); if (!string.IsNullOrEmpty(returnUrl)) { return LocalRedirect(returnUrl); } return this.RedirectToSiteRoot(Site); } else { log.LogDebug("ExternalLoginConfirmation AddLoginAsync failed "); } } else { log.LogDebug("ExternalLoginConfirmation failed to user created "); } AddErrors(result); } else { log.LogDebug("ExternalLoginConfirmation called with ModelStateInvalid "); } ViewData["ReturnUrl"] = returnUrl; return View(model); }
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return RedirectToAction("Manage"); } if (ModelState.IsValid) { // Obtener datos del usuario del proveedor de inicio de sesión externo var info = await AuthenticationManager.GetExternalLoginInfoAsync(); if (info == null) { return View("ExternalLoginFailure"); } var user = new ApplicationUser() { UserName = model.UserName }; var result = await UserManager.CreateAsync(user); if (result.Succeeded) { result = await UserManager.AddLoginAsync(user.Id, info.Login); if (result.Succeeded) { await SignInAsync(user, isPersistent: false); return RedirectToLocal(returnUrl); } } AddErrors(result); } ViewBag.ReturnUrl = returnUrl; return View(model); }
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return RedirectToAction("Manage"); } if (ModelState.IsValid) { // Informationen zum Benutzer aus dem externen Anmeldeanbieter abrufen var info = await AuthenticationManager.GetExternalLoginInfoAsync(); if (info == null) { return View("ExternalLoginFailure"); } var user = new ApplicationUser() { UserName = model.UserName }; var result = await UserManager.CreateAsync(user); if (result.Succeeded) { result = await UserManager.AddLoginAsync(user.Id, info.Login); if (result.Succeeded) { await SignInAsync(user, isPersistent: false); return RedirectToLocal(returnUrl); } } AddErrors(result); } ViewBag.ReturnUrl = returnUrl; return View(model); }
public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return(RedirectToAction("Index", "Manage")); } if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await AuthenticationManager.GetExternalLoginInfoAsync(); if (info == null) { return(View("ExternalLoginFailure")); } var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user); if (result.Succeeded) { result = await UserManager.AddLoginAsync(user.Id, info.Login); if (result.Succeeded) { //Assign Role to user Here await this.UserManager.AddToRoleAsync(user.Id, model.UserRole); //Ends Here // // Add user to user table // User newUser = new User(); newUser.Active = 1; newUser.EmailAddress = model.Email; newUser.Id = user.Id; newUser.Role = model.UserRole; UserBusinessLayer ubl = new UserBusinessLayer(); ubl.Add(newUser); switch (model.UserRole) { case "Amateur Artist": Artist newArtist = new Artist(); newArtist.UserID = newUser.UserID; ArtistBusinessLayer abl = new ArtistBusinessLayer(); abl.Add(newArtist); break; case "Business Owner": Business newBusiness = new Business(); newBusiness.UserID = newUser.UserID; BusinessBusinessLayer bbl = new BusinessBusinessLayer(); bbl.Add(newBusiness); break; default: // Admin Role?? break; } await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); return(RedirectToLocal(returnUrl)); } } AddErrors(result); } ViewBag.ReturnUrl = returnUrl; return(View(model)); }
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return RedirectToAction("Manage"); } if (ModelState.IsValid) { // 从外部登录提供程序获取有关用户的信息 var info = await AuthenticationManager.GetExternalLoginInfoAsync(); if (info == null) { return View("ExternalLoginFailure"); } var user = new WXStudio.EFModel.Entities.Core.CoreAccount() { UserName = model.Email, Email = model.Email }; // new ApplicationUser() { UserName = model.Email, Email = model.Email }; IdentityResult result = await UserManager.CreateAsync(user); if (result.Succeeded) { result = await UserManager.AddLoginAsync(user.Id, info.Login); if (result.Succeeded) { await SignInAsync(user, isPersistent: false); // 有关如何启用帐户确认和密码重置的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkID=320771 // 发送包含此链接的电子邮件 // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // SendEmail(user.Email, callbackUrl, "确认你的帐户", "请单击此链接确认你的帐户"); return RedirectToLocal(returnUrl); } } AddErrors(result); } ViewBag.ReturnUrl = returnUrl; return View(model); }
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return RedirectToAction("Index", "Manage"); } if (ModelState.IsValid) { // 从外部登录提供程序获取有关用户的信息 var info = await AuthenticationManager.GetExternalLoginInfoAsync(); if (info == null) { return View("ExternalLoginFailure"); } var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user); if (result.Succeeded) { result = await UserManager.AddLoginAsync(user.Id, info.Login); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); return RedirectToLocal(returnUrl); } } AddErrors(result); } ViewBag.ReturnUrl = returnUrl; return View(model); }
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return RedirectToAction("Manage"); } if (ModelState.IsValid) { // Get the information about the user from the external login provider IdentityResult result = await IdentityManager.Authentication.CreateAndSignInExternalUserAsync(AuthenticationManager, new ApplicationUser { UserName = model.UserName }); if (result.Success) { return RedirectToLocal(returnUrl); } else { AddErrors(result); } } ViewBag.ReturnUrl = returnUrl; return View(model); }
public async Task <IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null) { log.LogDebug("ExternalLoginCallback called with returnurl " + returnUrl); if (remoteError != null) { ModelState.AddModelError(string.Empty, $"Error from external provider: {remoteError}"); return(View(nameof(Login))); } // this is actually signing the user in var info = await signInManager.GetExternalLoginInfoAsync(); if (info == null) { log.LogDebug("ExternalLoginCallback redirecting to login because GetExternalLoginInfoAsync returned null "); return(RedirectToAction(nameof(Login))); } // Sign in the user with this external login provider if the user already has a login. var result = await signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent : false); if (result.Succeeded) { //TODO: how to get the user here? //await ipAddressTracker.TackUserIpAddress(Site.SiteGuid, user.UserGuid); log.LogDebug("ExternalLoginCallback ExternalLoginSignInAsync succeeded "); if (!string.IsNullOrEmpty(returnUrl)) { return(LocalRedirect(returnUrl)); } return(this.RedirectToSiteRoot(Site)); } if (result.RequiresTwoFactor) { log.LogDebug("ExternalLoginCallback ExternalLoginSignInAsync RequiresTwoFactor "); return(RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl })); } if (result.IsNotAllowed) { return(RedirectToAction("PendingApproval")); } if (result.IsLockedOut) { log.LogDebug("ExternalLoginCallback ExternalLoginSignInAsync IsLockedOut "); return(View("Lockout")); } else { log.LogDebug("ExternalLoginCallback needs new account "); // If the user does not have an account, then ask the user to create an account. ViewData["ReturnUrl"] = returnUrl; ViewData["LoginProvider"] = info.LoginProvider; var email = info.Principal.FindFirstValue(ClaimTypes.Email); var model = new ExternalLoginConfirmationViewModel(); model.Email = email; model.RegistrationPreamble = Site.RegistrationPreamble; model.RegistrationAgreement = Site.RegistrationAgreement; model.AgreementRequired = Site.RegistrationAgreement.Length > 0; return(View("ExternalLoginConfirmation", model)); } }
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return RedirectToAction("Manage"); } if (ModelState.IsValid) { // Получение сведений о пользователе от внешнего поставщика входа var info = await AuthenticationManager.GetExternalLoginInfoAsync(); if (info == null) { return View("ExternalLoginFailure"); } var user = new User() { UserName = model.UserName }; var result = await UserManager.CreateAsync(user); if (result.Succeeded) { result = await UserManager.AddLoginAsync(user.Id, info.Login); if (result.Succeeded) { await SignInAsync(user, isPersistent: false); return RedirectToLocal(returnUrl); } } AddErrors(result); } ViewBag.ReturnUrl = returnUrl; return View(model); }
public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null) { if (_signInManager.IsSignedIn(User)) { return RedirectToAction(nameof(ManageController.Index), "Manage"); } if (ModelState.IsValid) { // Get the information about the user from the external login provider var externalLoginInfo = await _signInManager.GetExternalLoginInfoAsync(); if (externalLoginInfo == null) { return View("ExternalLoginFailure"); } var user = new ApplicationUser { UserName = model.Email, Email = model.Email, TimeZoneId = _generalSettings.Value.DefaultTimeZone, FirstName = model.FirstName, LastName = model.LastName, PhoneNumber = model.PhoneNumber }; var result = await _userManager.CreateAsync(user); if (result.Succeeded) { result = await _userManager.AddLoginAsync(user, externalLoginInfo); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); return RedirectToLocal(returnUrl, user); } } AddErrorsToModelState(result); } ViewData["ReturnUrl"] = returnUrl; return View(model); }
public async Task ExternalLoginConfirmationPutsCorrectDataInViewDataWithCorrectKey_WhenModelStateIsInvalid() { const string returnUrlKey = "ReturnUrl"; const string returnUrlValue = "http:\\test.url.com"; var model = new ExternalLoginConfirmationViewModel(); var controller = AccountController(); controller.AddModelStateError(); controller.SetFakeUser("test"); var result = await controller.ExternalLoginConfirmation(model, returnUrlValue) as ViewResult; var viewDataKey = result.ViewData.Keys.FirstOrDefault(k => k == returnUrlKey); var viewDataValue = result.ViewData[returnUrlKey] as string; Assert.Equal<string>(viewDataValue, returnUrlValue); Assert.NotNull(viewDataKey); }
public virtual async Task <IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null) { Log.LogDebug("ExternalLoginCallback called with returnurl " + returnUrl); if (remoteError != null) { var errormessage = string.Format(StringLocalizer["Error from external provider: {0}"], remoteError); Analytics.HandleLoginFail("Social", errormessage).Forget(); ModelState.AddModelError("providererror", errormessage); return(RedirectToAction("Login")); } var result = await AccountService.TryExternalLogin(); if (result.SignInResult.Succeeded) { if (result.User != null) { if (result.MustAcceptTerms) { await Analytics.HandleLoginSuccess(result); return(RedirectToAction("TermsOfUse")); } } return(await HandleLoginSuccess(result, returnUrl)); } foreach (var reason in result.RejectReasons) { // these reasons are not meant to be shown in the ui // but we can log them so admin will see failed attempts in the log along with reasons Log.LogWarning(reason); } if (result.SignInResult.IsNotAllowed) { return(await HandleLoginNotAllowed(result, returnUrl)); } if (result.ExternalLoginInfo == null) { Log.LogDebug("ExternalLoginCallback redirecting to login because GetExternalLoginInfoAsync returned null "); return(RedirectToAction(nameof(Login))); } if (result.SignInResult.RequiresTwoFactor) { return(await HandleRequiresTwoFactor(result, returnUrl, false)); } if (result.SignInResult.IsLockedOut) { return(await HandleLockout(result)); } // result.Failed // If the user does not have an account, then ask the user to create an account. // check the claims from the provider to see if we have what we need // only need to show this form if there is no email or if there is a required registration agreement ViewData["ReturnUrl"] = returnUrl; ViewData["LoginProvider"] = result.ExternalLoginInfo.LoginProvider; var email = result.ExternalLoginInfo.Principal.FindFirstValue(ClaimTypes.Email); var model = new ExternalLoginConfirmationViewModel { Email = email, RegistrationPreamble = CurrentSite.RegistrationPreamble, RegistrationAgreement = CurrentSite.RegistrationAgreement, AgreementRequired = !string.IsNullOrWhiteSpace(CurrentSite.RegistrationAgreement) }; return(View("ExternalLoginConfirmation", model)); }
public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie); } if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await AuthenticationManager.GetExternalLoginInfoAsync(); if (info == null) { return(View("ExternalLoginFailure")); } var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user); if (result.Succeeded) { var u = new Web_user() { Name = info.ExternalIdentity.Name, Birthday = new DateTime(1970, 1, 1), UserID = user.Id, UserImage = @"/Content/Images/default.jpg" }; if (model.AsTeacher) { using (var db = new ApplicationDbContext()) { var t = new Teacher() { User = u }; db.Web_Users.Add(u); db.Teachers.Add(t); db.SaveChanges(); } UserManager.AddToRole(user.Id, "Teacher"); } else { using (var db = new ApplicationDbContext()) { var s = new Student() { web_User = u }; db.Web_Users.Add(u); db.Students.Add(s); db.SaveChanges(); } UserManager.AddToRole(user.Id, "Student"); } result = await UserManager.AddLoginAsync(user.Id, info.Login); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); return(await SignInAsync(user, returnUrl)); } } AddErrors(result); } ViewBag.ReturnUrl = returnUrl; return(View(model)); }
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return RedirectToAction("Manage"); } if (ModelState.IsValid) { // Obtener datos del usuario del proveedor de inicio de sesión externo var info = await AuthenticationManager.GetExternalLoginInfoAsync(); if (info == null) { return View("ExternalLoginFailure"); } var user = new ApplicationUser() { UserName = model.Email, Email = model.Email }; IdentityResult result = await UserManager.CreateAsync(user); if (result.Succeeded) { result = await UserManager.AddLoginAsync(user.Id, info.Login); if (result.Succeeded) { await SignInAsync(user, isPersistent: false); // Para obtener más información sobre cómo habilitar la confirmación de la cuenta y el restablecimiento de la contraseña, visite http://go.microsoft.com/fwlink/?LinkID=320771 // Enviar un correo electrónico con este vínculo // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // SendEmail(user.Email, callbackUrl, "Confirmar cuenta", "Haga clic en este vínculo para confirmar la cuenta"); return RedirectToLocal(returnUrl); } } AddErrors(result); } ViewBag.ReturnUrl = returnUrl; return View(model); }
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return RedirectToAction("Manage"); } if (ModelState.IsValid) { // Obter as informações sobre o usuário do provedor de logon externo var info = await AuthenticationManager.GetExternalLoginInfoAsync(); if (info == null) { return View("ExternalLoginFailure"); } var user = new ApplicationUser() { UserName = model.Email, Email = model.Email }; IdentityResult result = await UserManager.CreateAsync(user); if (result.Succeeded) { result = await UserManager.AddLoginAsync(user.Id, info.Login); if (result.Succeeded) { await SignInAsync(user, isPersistent: false); // Para obter mais informações sobre como habilitar a confirmação de conta e a redefinição de senha, visite http://go.microsoft.com/fwlink/?LinkID=320771 // Enviar um email com este link // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // SendEmail(user.Email, callbackUrl, "Confirmar sua conta", "Confirme sua conta clicando neste link"); return RedirectToLocal(returnUrl); } } AddErrors(result); } ViewBag.ReturnUrl = returnUrl; return View(model); }
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return RedirectToAction("Manage"); } if (ModelState.IsValid) { // Get the information about the user from the external login provider try { if (await AuthenticationManager.CreateAndSignInExternalUser(HttpContext, model.LoginProvider, new User(model.UserName))) { return RedirectToLocal(returnUrl); } else { return View("ExternalLoginFailure"); } } catch (IdentityException e) { ModelState.AddModelError("", e.Message); } } ViewBag.ReturnUrl = returnUrl; return View(model); }
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return RedirectToAction("Index", "Manage"); } if (ModelState.IsValid) { // Получение сведений о пользователе от внешнего поставщика входа var info = await AuthenticationManager.GetExternalLoginInfoAsync(); if (info == null) { return View("ExternalLoginFailure"); } var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; //var user = new ApplicationUser //{ // UserName = model.Email, // Name = model.Name, // Password = model.Password, // Email = model.Email, // LastVisition = curDate, // RegistrationDate = curDate, // UserInfo = "user", // DateOfBlocking = curDate, // BlockForDate = curDate, // IsBlocked = false, // BlockReason = "", // Balance = 0 //}; var result = await UserManager.CreateAsync(user); if (result.Succeeded) { result = await UserManager.AddLoginAsync(user.Id, info.Login); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); return RedirectToLocal(returnUrl); } } AddErrors(result); } ViewBag.ReturnUrl = returnUrl; return View(model); }
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return RedirectToAction("Manage"); } if (ModelState.IsValid) { // Informationen zum Benutzer aus dem externen Anmeldeanbieter abrufen var info = await AuthenticationManager.GetExternalLoginInfoAsync(); if (info == null) { return View("ExternalLoginFailure"); } var user = new ApplicationUser() { UserName = model.Email, Email = model.Email }; IdentityResult result = await UserManager.CreateAsync(user); if (result.Succeeded) { result = await UserManager.AddLoginAsync(user.Id, info.Login); if (result.Succeeded) { await SignInAsync(user, isPersistent: false); // Weitere Informationen zum Aktivieren der Kontobestätigung und Kennwortzurücksetzung finden Sie unter "http://go.microsoft.com/fwlink/?LinkID=320771". // E-Mail-Nachricht mit diesem Link senden // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // SendEmail(user.Email, callbackUrl, "Konto bestätigen", "Bitte bestätigen Sie Ihr Konto. Klicken Sie dazu"); return RedirectToLocal(returnUrl); } } AddErrors(result); } ViewBag.ReturnUrl = returnUrl; return View(model); }
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return RedirectToAction("Manage"); } if (ModelState.IsValid) { // Informationen zum Benutzer aus dem externen Anmeldeanbieter abrufen IdentityResult result = await IdentityManager.Authentication.CreateAndSignInExternalUserAsync(AuthenticationManager, new User(model.UserName)); if (result.Success) { return RedirectToLocal(returnUrl); } else { AddErrors(result); } } ViewBag.ReturnUrl = returnUrl; return View(model); }
public async Task ExternalLoginConfirmationReturnsCorrectViewModel_WhenModelStateIsInvalid() { var model = new ExternalLoginConfirmationViewModel(); var controller = AccountController(); controller.AddModelStateError(); controller.SetFakeUser("test"); var result = await controller.ExternalLoginConfirmation(model) as ViewResult; var modelResult = result.ViewData.Model as ExternalLoginConfirmationViewModel; Assert.IsType<ViewResult>(result); Assert.IsType<ExternalLoginConfirmationViewModel>(modelResult); Assert.Same(modelResult, model); }
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return RedirectToAction("Manage"); } if (ModelState.IsValid) { ExternalLoginInfo asyncVariable0 = await AuthenticationManager.GetExternalLoginInfoAsync(); if (asyncVariable0 == null) { return View("ExternalLoginFailure"); } ApplicationUser user = new ApplicationUser { UserName = model.UserName }; IdentityResult result = await UserManager.CreateAsync(user); if (result.Succeeded) { result = await UserManager.AddLoginAsync(user.Id, asyncVariable0.Login); if (result.Succeeded) { await SignInAsync(user, false); return RedirectToLocal(returnUrl); } } AddErrors(result); } ((dynamic)ViewBag).ReturnUrl = returnUrl; return View(model); }
public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null) { if (User.IsSignedIn()) { return RedirectToAction(nameof(ManageController.Index), "Manage"); } if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { return View("ExternalLoginFailure"); } var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await _userManager.CreateAsync(user); if (result.Succeeded) { result = await _userManager.AddLoginAsync(user, info); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider); return RedirectToLocal(returnUrl); } } AddErrors(result); } ViewData["ReturnUrl"] = returnUrl; return View(model); }
public async Task<ActionResult> ExternalLoginCallback(string returnUrl) { ExternalLoginInfo loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(); if (loginInfo == null) { return RedirectToAction("Login"); } ApplicationUser user = await UserManager.FindAsync(loginInfo.Login); if (user != null) { await SignInAsync(user, false); return RedirectToLocal(returnUrl); } ((dynamic)ViewBag).ReturnUrl = returnUrl; ((dynamic)ViewBag).LoginProvider = loginInfo.Login.LoginProvider; ExternalLoginConfirmationViewModel model = new ExternalLoginConfirmationViewModel { UserName = loginInfo.DefaultUserName }; return View("ExternalLoginConfirmation", model); }
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return RedirectToAction("Manage"); } if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await AuthenticationManager.GetExternalLoginInfoAsync(); if (info == null) { return View("ExternalLoginFailure"); } var user = new ApplicationUser() { UserName = model.UserName, Email = model.Email, IsActive = true, EmailConfirmed = true }; var result = await UserManager.CreateAsync(user); UserManager.AddToRole(user.Id, "User"); if (result.Succeeded) { result = await UserManager.AddLoginAsync(user.Id, info.Login); if (result.Succeeded) { await SignInAsync(user, isPersistent: false); return RedirectToLocal(returnUrl); } } AddErrors(result); } ViewBag.ReturnUrl = returnUrl; return View(model); }
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { var errors = ModelState.Values.SelectMany(v => v.Errors); if (User.Identity.IsAuthenticated) { return RedirectToAction("Manage"); } if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await AuthenticationManager_GetExternalLoginInfoAsync_Workaround(); ApplicationUser user; if (info == null) { return View("ExternalLoginFailure"); } string loginProviderLowerCase = info.Login.LoginProvider.ToLower(); if (loginProviderLowerCase == "facebook") { user = createUserFromFacebookInfo(model); } else { user = new ApplicationUser() { UserName = GenerateUserName(model.Email), FirstName = model.FirstName, LastName = model.LastName, Email = model.Email, Gender = model.Gender }; } var result = await UserManager.CreateAsync(user); if (result.Succeeded) { result = await UserManager.AddLoginAsync(user.Id, info.Login); if (result.Succeeded) { await SignInAsync(user, isPersistent: false); return RedirectToLocal(returnUrl); } } AddErrors(result); } ViewBag.ReturnUrl = returnUrl; return View(model); }
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return RedirectToAction("Manage"); } if (ModelState.IsValid) { // Get the information about the user from the external login provider if ((await AuthenticationManager.CreateAndSignInExternalUserAsync(OwinAuthManager, new User(model.UserName))).Success) { return RedirectToLocal(returnUrl); } else { return View("ExternalLoginFailure"); } } ViewBag.ReturnUrl = returnUrl; return View(model); }
private ApplicationUser createUserFromFacebookInfo(ExternalLoginConfirmationViewModel i_Model) { ApplicationUser userToReturn; var externalIdentity = getExternalIdentity(); var email = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email).Value; var firstName = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == "urn:facebook:first_name").Value; var lastName = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == "urn:facebook:last_name").Value; string gender = getGender(externalIdentity); var userID = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == "urn:facebook:id").Value; var birthDate = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == "urn:facebook:birthdate").Value; var imageURL = string.Format(@"https://graph.facebook.com/{0}/picture?type=normal", userID); //var emailClaim = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email); userToReturn = new ApplicationUser() { UserName = GenerateUserName(i_Model.Email), FirstName = firstName, LastName = lastName, Email = email, Gender = gender, ImageUrl = imageURL }; return userToReturn; }
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return RedirectToAction("Manage"); } if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await AuthenticationManager.GetExternalLoginInfoAsync(); if (info == null) { return View("ExternalLoginFailure"); } var user = new ApplicationUser() { UserName = model.Email, Email = model.Email }; IdentityResult result = await UserManager.CreateAsync(user); if (result.Succeeded) { result = await UserManager.AddLoginAsync(user.Id, info.Login); if (result.Succeeded) { await SignInAsync(user, isPersistent: false); // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // SendEmail(user.Email, callbackUrl, "Confirm your account", "Please confirm your account by clicking this link"); return RedirectToLocal(returnUrl); } } AddErrors(result); } ViewBag.ReturnUrl = returnUrl; return View(model); }
public async Task<IHttpActionResult> RegisterExternal(ExternalLoginConfirmationViewModel model) { if (!this.ModelState.IsValid) { return this.BadRequest(this.ModelState); } var info = await this.Authentication.GetExternalLoginInfoAsync(); if (info == null) { return this.InternalServerError(); } var user = new User() { UserName = model.Username, Email = info.Email }; IdentityResult result = await this.UserManager.CreateAsync(user); if (!result.Succeeded) { return this.GetErrorResult(result); } result = await this.UserManager.AddLoginAsync(user.Id, info.Login); if (!result.Succeeded) { return this.GetErrorResult(result); } return this.Ok(); }