public async Task <IActionResult> ForgotPassword(ForgotPasswordViewModel model) { if (ModelState.IsValid) { BejebejeUser user = await _userManager.FindByEmailAsync(model.Email); if (user == null || !(await _userManager.IsEmailConfirmedAsync(user))) { // Don't reveal that the user does not exist or is not confirmed return(RedirectToPage("./ForgotPasswordConfirmation")); } // For more information on how to enable account confirmation and password reset please // visit https://go.microsoft.com/fwlink/?LinkID=532713 string code = await _userManager.GeneratePasswordResetTokenAsync(user); string callbackUrl = Url.Action( "ResetPassword", "Account", new { code }, Request.Scheme); EmailForgotPasswordViewModel viewModel = new EmailForgotPasswordViewModel(); viewModel.UserDisplayUsername = user.DisplayUsername; viewModel.Code = callbackUrl; viewModel.UserEmailAddress = user.Email; await _emailService.SendForgotPasswordEmailAsync(viewModel); return(RedirectToAction("ForgotPasswordConfirmation")); } return(RedirectToAction("Index", "Home")); }
public async Task <IActionResult> ResetPassword(ResetPasswordViewModel model) { if (!ModelState.IsValid) { return(View(model)); } BejebejeUser user = await _userManager.FindByEmailAsync(model.Email); if (user == null) { // Don't reveal that the user does not exist return(RedirectToAction("ResetPasswordConfirmation")); } IdentityResult result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password); if (result.Succeeded) { return(RedirectToAction("ResetPasswordConfirmation")); } foreach (IdentityError error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } return(View(model)); }
public async Task GetProfileDataAsync(ProfileDataRequestContext context) { BejebejeUser user = await _userManager.GetUserAsync(context.Subject); IList <string> roles = await _userManager.GetRolesAsync(user); IList <Claim> roleClaims = new List <Claim>(); foreach (string role in roles) { roleClaims.Add(new Claim(JwtClaimTypes.Role, role)); } context.IssuedClaims.AddRange(roleClaims); }
public async Task <IActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { BejebejeUser user = new BejebejeUser { UserName = model.Email, Email = model.Email, DisplayUsername = model.Username }; IdentityResult result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { string code = await _userManager.GenerateEmailConfirmationTokenAsync(user); string callbackUrl = Url.Action( "ConfirmEmail", "Account", new { userId = user.Id, code }, Request.Scheme); EmailRegistrationViewModel emailViewModel = new EmailRegistrationViewModel(); emailViewModel.UserDisplayUsername = model.Username; emailViewModel.Code = callbackUrl; emailViewModel.UserEmailAddress = model.Email; await _emailService.SendRegistrationEmailAsync(emailViewModel); await _signInManager.SignInAsync(user, isPersistent : false); return(View("ConfirmRegistration")); } foreach (IdentityError error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } return(View(model)); }
public async Task <IActionResult> ConfirmEmail(string userId, string code) { if (userId == null || code == null) { return(RedirectToAction("Index", "Home")); } BejebejeUser user = await _userManager.FindByIdAsync(userId); if (user == null) { return(NotFound($"Unable to load user with ID '{userId}'.")); } IdentityResult result = await _userManager.ConfirmEmailAsync(user, code); if (!result.Succeeded) { throw new InvalidOperationException($"Error confirming email for user with ID '{userId}':"); } return(View("EmailConfirmed")); }
public async Task <IActionResult> Login(LoginInputModel model, string button) { // check if we are in the context of an authorization request AuthorizationRequest context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl); // the user clicked the "cancel" button if (button != "login") { if (context != null) { // if the user cancels, send a result back into IdentityServer as if they // denied the consent (even if this client does not require consent). // this will send back an access denied OIDC error response to the client. await _interaction.GrantConsentAsync(context, ConsentResponse.Denied); // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null if (await _clientStore.IsPkceClientAsync(context.ClientId)) { // if the client is PKCE then we assume it's native, so this change in how to // return the response is for better UX for the end user. return(View("Redirect", new RedirectViewModel { RedirectUrl = model.ReturnUrl })); } return(Redirect(model.ReturnUrl)); } else { // since we don't have a valid context, then we just go back to the home page return(Redirect("~/")); } } if (ModelState.IsValid) { Microsoft.AspNetCore.Identity.SignInResult result = await _signInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberLogin, lockoutOnFailure : true); if (result.Succeeded) { Console.WriteLine("User is logged in!"); BejebejeUser user = await _userManager.FindByNameAsync(model.Username); await _events.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.Id, user.UserName)); if (context != null) { if (await _clientStore.IsPkceClientAsync(context.ClientId)) { // if the client is PKCE then we assume it's native, so this change in how to // return the response is for better UX for the end user. return(View("Redirect", new RedirectViewModel { RedirectUrl = model.ReturnUrl })); } // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null return(Redirect(model.ReturnUrl)); } // request for a local page if (Url.IsLocalUrl(model.ReturnUrl)) { return(Redirect(model.ReturnUrl)); } else if (string.IsNullOrEmpty(model.ReturnUrl)) { return(Redirect("~/")); } else { // user might have clicked on a malicious link - should be logged throw new Exception("invalid return URL"); } } await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials")); ModelState.AddModelError(string.Empty, AccountOptions.InvalidCredentialsErrorMessage); } // something went wrong, show form with error LoginViewModel viewModel = await BuildLoginViewModelAsync(model); return(View(viewModel)); }
private async Task <BejebejeUser> AutoProvisionUserAsync(string provider, string providerUserId, IEnumerable <Claim> claims) { // create a list of claims that we want to transfer into our store var filtered = new List <Claim>(); // user's display name var name = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Name)?.Value ?? claims.FirstOrDefault(x => x.Type == ClaimTypes.Name)?.Value; if (name != null) { filtered.Add(new Claim(JwtClaimTypes.Name, name)); } else { var first = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.GivenName)?.Value ?? claims.FirstOrDefault(x => x.Type == ClaimTypes.GivenName)?.Value; var last = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.FamilyName)?.Value ?? claims.FirstOrDefault(x => x.Type == ClaimTypes.Surname)?.Value; if (first != null && last != null) { filtered.Add(new Claim(JwtClaimTypes.Name, first + " " + last)); } else if (first != null) { filtered.Add(new Claim(JwtClaimTypes.Name, first)); } else if (last != null) { filtered.Add(new Claim(JwtClaimTypes.Name, last)); } } // email var email = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Email)?.Value ?? claims.FirstOrDefault(x => x.Type == ClaimTypes.Email)?.Value; if (email != null) { filtered.Add(new Claim(JwtClaimTypes.Email, email)); } var user = new BejebejeUser { UserName = Guid.NewGuid().ToString(), }; var identityResult = await _userManager.CreateAsync(user); if (!identityResult.Succeeded) { throw new Exception(identityResult.Errors.First().Description); } if (filtered.Any()) { identityResult = await _userManager.AddClaimsAsync(user, filtered); if (!identityResult.Succeeded) { throw new Exception(identityResult.Errors.First().Description); } } identityResult = await _userManager.AddLoginAsync(user, new UserLoginInfo(provider, providerUserId, provider)); if (!identityResult.Succeeded) { throw new Exception(identityResult.Errors.First().Description); } return(user); }
public async Task SeedDataAsync() { Console.WriteLine("Seeding the database."); await _context.Database.MigrateAsync(); IdentityRole adminRole = await _roleManager.FindByNameAsync("administrator"); if (adminRole == null) { adminRole = new IdentityRole("administrator"); IdentityResult identityResult = await _roleManager.CreateAsync(adminRole); if (!identityResult.Succeeded) { throw new Exception(identityResult.ToString()); } _logger.LogInformation("created the administrator role."); } IdentityRole moderatorRole = await _roleManager.FindByNameAsync("moderator"); if (moderatorRole == null) { moderatorRole = new IdentityRole("moderator"); IdentityResult identityResult = await _roleManager.CreateAsync(moderatorRole); if (!identityResult.Succeeded) { throw new Exception(identityResult.ToString()); } _logger.LogInformation("created the moderator role."); } BejebejeUser seedUser = await _userManager .FindByNameAsync(SeedConfiguration.Username); if (seedUser == null) { seedUser = new BejebejeUser { UserName = SeedConfiguration.Username, Email = SeedConfiguration.Email, EmailConfirmed = true, DisplayUsername = SeedConfiguration.FirstName, }; IdentityResult identityResult = await _userManager .CreateAsync(seedUser, SeedConfiguration.Password); if (!identityResult.Succeeded) { throw new Exception(identityResult.ToString()); } _logger.LogInformation($"{SeedConfiguration.Username} created"); IdentityResult identityResultOnRoleAssignment = await _userManager .AddToRoleAsync(seedUser, "administrator"); if (!identityResultOnRoleAssignment.Succeeded) { throw new Exception(identityResultOnRoleAssignment.ToString()); } _logger.LogInformation("assigned seed user to administrator role."); } else { _logger.LogError($"{SeedConfiguration.Username} already exists"); } }