private async Task <ClaimsPrincipal> StoreRememberClient(GroupyfyUser user, string role = null, Guid?corporateId = null, Guid?offerId = null) { var userId = await _userManager.GetUserIdAsync(user); var rememberBrowserIdentity = new ClaimsIdentity(IdentityConstants.TwoFactorRememberMeScheme); rememberBrowserIdentity.AddClaim(new Claim(ClaimTypes.Name, user.UserName)); rememberBrowserIdentity.AddClaim(new Claim(JwtClaimTypes.Name, user.UserName)); rememberBrowserIdentity.AddClaim(new Claim("sub", userId)); if (!string.IsNullOrEmpty(role)) { rememberBrowserIdentity.AddClaim(new Claim(JwtClaimTypes.Role, role)); } if (!string.IsNullOrEmpty(corporateId?.ToString())) { rememberBrowserIdentity.AddClaim(new Claim("corporateId", corporateId.ToString())); } if (!string.IsNullOrEmpty(offerId?.ToString())) { rememberBrowserIdentity.AddClaim(new Claim("offerId", offerId.ToString())); } if (_userManager.SupportsUserSecurityStamp) { var stamp = await _userManager.GetSecurityStampAsync(user); rememberBrowserIdentity.AddClaim(new Claim(_signInManager.Options.ClaimsIdentity.SecurityStampClaimType, stamp)); } return(new ClaimsPrincipal(rememberBrowserIdentity)); }
private async Task LoadSharedKeyAndQrCodeUriAsync(GroupyfyUser user) { // Load the authenticator key & QR code URI to display on the form var unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user); if (string.IsNullOrEmpty(unformattedKey)) { await _userManager.ResetAuthenticatorKeyAsync(user); unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user); } SharedKey = FormatKey(unformattedKey); var email = await _userManager.GetEmailAsync(user); AuthenticatorUri = GenerateQrCodeUri(email, unformattedKey); }
public async Task <IActionResult> OnPostConfirmationAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); // Get the information about the user from the external login provider var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { ErrorMessage = "Error loading external login information during confirmation."; return(RedirectToPage("./Login", new { ReturnUrl = returnUrl })); } if (ModelState.IsValid) { var user = new GroupyfyUser { UserName = Input.Email, Email = Input.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(LocalRedirect(returnUrl)); } } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } LoginProvider = info.LoginProvider; ReturnUrl = returnUrl; return(Page()); }
/// <summary> /// Adds the given <paramref name="normalizedRoleName"/> to the specified <paramref name="user"/> with optional <paramref name="corporateId"/>. /// </summary> /// <param name="user"></param> /// <param name="normalizedRoleName"></param> /// <param name="corporateId"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public async Task AddToGroupyfyRoleAsync(GroupyfyUser user, string normalizedRoleName, Guid?corporateId, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException(nameof(user)); } if (string.IsNullOrWhiteSpace(normalizedRoleName)) { throw new ArgumentException("ValueCannotBeNullOrEmpty", nameof(normalizedRoleName)); } var roleEntity = await FindRoleAsync(normalizedRoleName, cancellationToken); if (roleEntity == null) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "RoleNotFound", normalizedRoleName)); } await Context.UserRoles.AddAsync(new GroupyfyUserRole(user.Id, roleEntity.Id, corporateId)); }
/// <summary> /// Returns a flag indicating if the specified user is a member of the give <paramref name="normalizedRoleName"/>. /// </summary> /// <param name="user">The user whose role membership should be checked.</param> /// <param name="normalizedRoleName">The role to check membership of</param> /// <param name="CorporateId">The corporate id to filter with</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>A <see cref="Task{TResult}"/> containing a flag indicating if the specified user is a member of the given group. If the /// user is a member of the group the returned value with be true, otherwise it will be false.</returns> public async Task <bool> IsInGroupyfyRoleAsync(GroupyfyUser user, string normalizedRoleName, Guid?corporateId, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException(nameof(user)); } if (string.IsNullOrWhiteSpace(normalizedRoleName)) { throw new ArgumentException("ValueCannotBeNullOrEmpty", nameof(normalizedRoleName)); } var role = await FindRoleAsync(normalizedRoleName, cancellationToken); if (role != null) { var userRole = await FindGroupyfyUserRoleAsync(user.Id, role.Id, corporateId, cancellationToken); return(userRole != null); } return(false); }
/// <summary> /// Retrieves the roles the specified <paramref name="user"/> is a member of. /// </summary> /// <param name="user">The user whose roles should be retrieved.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>A <see cref="Task{TResult}"/> that contains the roles the user is a member of.</returns> public async Task <IList <KeyValuePair <string, Guid?> > > GetGroupyfyRolesAsync(GroupyfyUser user, bool hasPassword = true, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException(nameof(user)); } return(await Context.UserRoles .Join(Context.Roles, ur => ur.RoleId, r => r.Id, (userRole, role) => new { UserRole = userRole, Role = role }) .Where(x => x.UserRole.RoleId == x.Role.Id && x.UserRole.UserId == user.Id && x.Role.HasPassword == hasPassword) .Select(x => new KeyValuePair <string, Guid?>(x.Role.Name, x.UserRole.CorporateId)) .ToListAsync(cancellationToken)); }
public async Task <IActionResult> OnPostAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); if (!ModelState.IsValid) { return(Page()); } if (Input.Role.ToLower() == "candidate") { var user = await _userManager.FindByNameAsync(Input.Email); if (user != null) { var isUserInCandidateRoleForCorporate = await _userManager.IsInGroupyfyRoleAsync(user, "candidate", Input.CorporateId); if (isUserInCandidateRoleForCorporate) { ModelState.AddModelError("candidate", "Candidate already exists for this corporate"); return(Page()); } var assignRoleResult = await _userManager.AddToGroupyfyRoleAsync(user, Input.Role, Input.CorporateId); if (!assignRoleResult.Succeeded) { return(LocalRedirect($"/home/error?errorId={assignRoleResult.Errors.ToArray()[0].Code}")); } await _signInManager.SignInAsync(user, isPersistent : false); return(LocalRedirect(returnUrl)); } else { user = new GroupyfyUser { UserName = Input.Email, Email = Input.Email }; var result = await _userManager.CreateAsync(user); if (result.Succeeded) { var assignRoleResult = await _userManager.AddToGroupyfyRoleAsync(user, "candidate", Input.CorporateId); if (!assignRoleResult.Succeeded) { return(LocalRedirect($"/home/error?errorId={assignRoleResult.Errors.ToArray()[0].Code}")); } _logger.LogInformation("Candidate created"); await _signInManager.SignInAsync(user, isPersistent : false); return(LocalRedirect(returnUrl)); } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } } else { var user = new GroupyfyUser { UserName = Input.Email, Email = Input.Email }; var result = await _userManager.CreateAsync(user, Input.Password); if (result.Succeeded) { var assignRoleResult = await _userManager.AddToGroupyfyRoleAsync(user, Input.Role, Input.CorporateId); if (!assignRoleResult.Succeeded) { return(LocalRedirect($"/home/error?errorId={assignRoleResult.Errors.ToArray()[0].Code}")); } _logger.LogInformation("User created a new account with password."); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); var callbackUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { userId = user.Id, code = code }, protocol: Request.Scheme); await _emailSender.SendEmailAsync(Input.Email, "Confirm your email", $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>."); await _signInManager.SignInAsync(user, isPersistent : false); return(LocalRedirect(returnUrl)); } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } // If we got this far, something failed, redisplay form return(Page()); }
private async Task <GroupyfyUser> 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 GroupyfyUser { 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); }