public async Task <IActionResult> Register([FromBody] RegisterViewModel model) { if (!ModelState.IsValid) { return(new ValidationFailedResult(ModelState)); } var user = new CrmIdentityUser { Name = model.Name, UserName = model.EmailAddress, Email = model.EmailAddress }; var result = await _userManager.CreateAsync(user, model.Password); if (!result.Succeeded) { return(new ValidationFailedResult(result.Errors.Select(x => x.Description))); } _logger.LogInformation("User created a new account with password."); var identity = await Authenticate(model.EmailAddress, model.Password); var userModel = await GetUserData(identity); return(Ok(userModel)); }
private async Task <UserSummaryViewModel> GetUserData(CrmIdentityUser user) { if (user == null) { return(null); } var roles = await _userManager.GetRolesAsync(user); if (roles.Count == 0) { roles.Add("prospect"); } // generate the jwt for the local user... var jwt = await _jwtFactory.GenerateEncodedToken(user.UserName, _jwtFactory.GenerateClaimsIdentity(user.UserName, user.Id.ToString())); var userModel = new UserSummaryViewModel { //JWT could inject all these properties instead of creating a model, //but a model is a little easier to access from client code without //decoding the token. When this user model starts to contain arrays //of complex data, including it all in the JWT value can get complicated. Id = user.Id, Name = user.Name, EmailAddress = user.Email, JwtToken = jwt, Roles = roles.ToArray(), //each role could be a separate claim in the JWT AccountId = 0 //TODO: load this from registration data }; return(userModel); }
public async Task <IActionResult> ExternalLoginConfirmation(ExternalLoginViewModel model, 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) { throw new ApplicationException("Error loading external login information during confirmation."); } var user = new CrmIdentityUser { 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("User created an account using {Name} provider.", info.LoginProvider); return(RedirectToLocal(returnUrl)); } } AddErrors(result); } ViewData["ReturnUrl"] = returnUrl; return(View(nameof(ExternalLogin), model)); }
public async Task <IActionResult> Register(RegisterViewModel model, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { var user = new CrmIdentityUser { 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); var callbackUrl = Url.EmailConfirmationLink(user.Id, code, Request.Scheme); await _emailSender.SendEmailConfirmationAsync(model.Email, callbackUrl); await _signInManager.SignInAsync(user, isPersistent : false); _logger.LogInformation("User created a new account with password."); return(RedirectToLocal(returnUrl)); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new CrmIdentityUser <string> { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : 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); // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); return(RedirectToAction("Index", "Home")); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task <IActionResult> PostMicrosoft([FromBody] MicrosoftAuthViewModel model) { var verifier = new MicrosoftAuthVerifier <AuthController>(_microsoftAuthSettings, _configuration["HttpHost"] + (model.BaseHref ?? "/"), _logger); var profile = await verifier.AcquireUser(model.AccessToken); if (!profile.IsSuccessful) { _logger.LogWarning("ExternalLoginCallback() unknown error at external login provider, {profile.Error.Message}", profile.Error.Message); return(new ValidationFailedResult(profile.Error.Message, StatusCodes.Status400BadRequest)); } var info = new UserLoginInfo("Microsoft", profile.Id, "Microsoft"); if (info == null || info.ProviderKey == null || info.LoginProvider == null) { _logger.LogWarning("ExternalLoginCallback() unknown error at external login provider"); return(new ValidationFailedResult("Unknown error at external login provider", StatusCodes.Status400BadRequest)); } if (string.IsNullOrWhiteSpace(profile.Mail)) { return(new ValidationFailedResult("Email address not available from Login provider, cannot proceed.", StatusCodes.Status403Forbidden)); } // ready to create the local user account (if necessary) and jwt var user = await _userManager.FindByEmailAsync(profile.Mail); if (user == null) { var appUser = new CrmIdentityUser { Name = profile.DisplayName, Email = profile.Mail, UserName = profile.Mail, PhoneNumber = profile.MobilePhone }; var password = Convert.ToBase64String(Guid.NewGuid().ToByteArray()).Substring(0, 8) + "#1aA"; // #1aA ensures all required character types will be in the random password var identityResult = await _userManager.CreateAsync(appUser, password); if (!identityResult.Succeeded) { return(new ValidationFailedResult("Could not create user.", StatusCodes.Status400BadRequest)); } user = await _userManager.FindByEmailAsync(profile.Mail); if (user == null) { return(new ValidationFailedResult("Failed to create local user account.", StatusCodes.Status400BadRequest)); } } var userModel = await GetUserData(user); return(Ok(userModel)); }
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 CrmIdentityUser <string> { 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 override Task <ClaimsIdentity> CreateUserIdentityAsync(CrmIdentityUser <string> user) { return(user.GenerateUserIdentityAsync <string>(UserManager)); }