private async Task <IEnumerable <Claim> > GetClaimsAsync(BlazorHeroUser user) { var userClaims = await _userManager.GetClaimsAsync(user); var roles = await _userManager.GetRolesAsync(user); var roleClaims = new List <Claim>(); var permissionClaims = new List <Claim>(); foreach (var role in roles) { roleClaims.Add(new Claim(ClaimTypes.Role, role)); var thisRole = await _roleManager.FindByNameAsync(role); var allPermissionsForThisRoles = await _roleManager.GetClaimsAsync(thisRole); permissionClaims.AddRange(allPermissionsForThisRoles); } var claims = new List <Claim> { new(ClaimTypes.NameIdentifier, user.Id), new(ClaimTypes.Email, user.Email), new(ClaimTypes.Name, user.FirstName), new(ClaimTypes.Surname, user.LastName), new(ClaimTypes.MobilePhone, user.PhoneNumber ?? string.Empty) }
private void AddBasicUser() { Task.Run(async() => { //Check if Role Exists var basicRole = new IdentityRole(RoleConstants.BasicRole); var basicRoleInDb = await _roleManager.FindByNameAsync(RoleConstants.BasicRole); if (basicRoleInDb == null) { await _roleManager.CreateAsync(basicRole); _logger.LogInformation("Seeded Basic Role."); } //Check if User Exists var basicUser = new BlazorHeroUser { FirstName = "John", LastName = "Doe", Email = "*****@*****.**", UserName = "******", EmailConfirmed = true, PhoneNumberConfirmed = true, CreatedOn = DateTime.Now, IsActive = true }; var basicUserInDb = await _userManager.FindByEmailAsync(basicUser.Email); if (basicUserInDb == null) { await _userManager.CreateAsync(basicUser, UserConstants.DefaultPassword); await _userManager.AddToRoleAsync(basicUser, RoleConstants.BasicRole); _logger.LogInformation("Seeded User with Basic Role."); } }).GetAwaiter().GetResult(); }
private async Task <string> GenerateJwtAsync(BlazorHeroUser user) { var userClaims = await _userManager.GetClaimsAsync(user); var roles = await _userManager.GetRolesAsync(user); var roleClaims = new List <Claim>(); for (int i = 0; i < roles.Count; i++) { roleClaims.Add(new Claim(ClaimTypes.Role, roles[i])); } var claims = new List <Claim> { new Claim(ClaimTypes.NameIdentifier, user.Id), new Claim(ClaimTypes.Email, user.Email), new Claim(ClaimTypes.Name, user.FirstName), new Claim(ClaimTypes.Surname, user.LastName), new Claim(ClaimTypes.MobilePhone, user.PhoneNumber ?? string.Empty) } .Union(userClaims) .Union(roleClaims); var secret = Encoding.UTF8.GetBytes(_appConfig.Secret); var token = new JwtSecurityToken( claims: claims, expires: DateTime.UtcNow.AddDays(7), signingCredentials: new SigningCredentials( new SymmetricSecurityKey(secret), SecurityAlgorithms.HmacSha256)); var tokenHandler = new JwtSecurityTokenHandler(); var encryptedToken = tokenHandler.WriteToken(token); return(encryptedToken); }
private void AddAdministrator() { Task.Run(async() => { //Check if Role Exists var adminRole = new IdentityRole(Constants.AdministratorRole); var adminRoleInDb = await _roleManager.FindByNameAsync(Constants.AdministratorRole); if (adminRoleInDb == null) { await _roleManager.CreateAsync(adminRole); _logger.LogInformation("Seeded Administrator Role."); } //Check if User Exists var superUser = new BlazorHeroUser { FirstName = "Mukesh", LastName = "Murugan", Email = "*****@*****.**", UserName = "******", EmailConfirmed = true, PhoneNumberConfirmed = true, CreatedOn = DateTime.Now, IsActive = true }; var superUserInDb = await _userManager.FindByEmailAsync(superUser.Email); if (superUserInDb == null) { await _userManager.CreateAsync(superUser, Constants.DefaultPassword); await _userManager.AddToRoleAsync(superUser, Constants.AdministratorRole); _logger.LogInformation("Seeded User with Administrator Role."); } }).GetAwaiter().GetResult(); }
public async Task <IResult> RegisterAsync(RegisterRequest request, string origin) { var userWithSameUserName = await _userManager.FindByNameAsync(request.UserName); if (userWithSameUserName != null) { return(await Result.FailAsync($"{_localizer["Username"]} '{request.UserName}' {_localizer["is already taken."]}")); } var user = new BlazorHeroUser { Email = request.Email, FirstName = request.FirstName, LastName = request.LastName, UserName = request.UserName, PhoneNumber = request.PhoneNumber, IsActive = request.ActivateUser, EmailConfirmed = request.AutoConfirmEmail }; var userWithSameEmail = await _userManager.FindByEmailAsync(request.Email); if (userWithSameEmail == null) { var result = await _userManager.CreateAsync(user, request.Password); if (result.Succeeded) { await _userManager.AddToRoleAsync(user, RoleConstants.BasicRole); if (!request.AutoConfirmEmail) { var verificationUri = await SendVerificationEmail(user, origin); var mailRequest = new MailRequest { From = "*****@*****.**", To = user.Email, Body = $"{_localizer["Please confirm your account by"]} <a href='{verificationUri}'>{_localizer["clicking here"]}</a>.", Subject = _localizer["Confirm Registration"] }; BackgroundJob.Enqueue(() => _mailService.SendAsync(mailRequest)); return(await Result <string> .SuccessAsync(user.Id, message : _localizer[$"User Registered. Please check your Mailbox to verify!"])); } return(await Result <string> .SuccessAsync(user.Id, message : _localizer[$"User Registered"])); } else { return(await Result.FailAsync(result.Errors.Select(a => a.Description).ToList())); } } else { return(await Result.FailAsync($"{_localizer["Email"]} {request.Email } {_localizer["is already registered."]}")); } }
private async Task <string> SendVerificationEmail(BlazorHeroUser user, string origin) { var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); var route = "api/identity/user/confirm-email/"; var _enpointUri = new Uri(string.Concat($"{origin}/", route)); var verificationUri = QueryHelpers.AddQueryString(_enpointUri.ToString(), "userId", user.Id); verificationUri = QueryHelpers.AddQueryString(verificationUri, "code", code); return(verificationUri); }
public async Task <IResult> RegisterAsync(RegisterRequest request, string origin) { var userWithSameUserName = await _userManager.FindByNameAsync(request.UserName); if (userWithSameUserName != null) { return(Result.Fail($"Username '{request.UserName}' is already taken.")); } var user = new BlazorHeroUser { Email = request.Email, FirstName = request.FirstName, LastName = request.LastName, UserName = request.UserName, PhoneNumber = request.PhoneNumber, IsActive = request.ActivateUser, EmailConfirmed = request.AutoConfirmEmail }; var userWithSameEmail = await _userManager.FindByEmailAsync(request.Email); if (userWithSameEmail == null) { var result = await _userManager.CreateAsync(user, request.Password); if (result.Succeeded) { await _userManager.AddToRoleAsync(user, Constants.BasicRole.ToString()); if (!request.AutoConfirmEmail) { var verificationUri = await SendVerificationEmail(user, origin); //TODO: Attach Email Service here and configure it via appsettings await _mailService.SendAsync(new MailRequest() { From = "*****@*****.**", To = user.Email, Body = $"Please confirm your account by <a href='{verificationUri}'>clicking here</a>.", Subject = "Confirm Registration" }); return(Result <string> .Success(user.Id, message : $"User Registered. Confirmation Mail has been delivered to the Mailbox.")); } return(Result <string> .Success(user.Id, message : $"User Registered!")); } else { return(Result.Fail(result.Errors.Select(a => a.Description).ToList())); } } else { return(Result.Fail($"Email {request.Email } is already registered.")); } }
private void AddAdministrator() { Task.Run(async() => { //Check if Role Exists var adminRole = new BlazorHeroRole(RoleConstants.AdministratorRole, _localizer["Administrator role with full permissions"]); var adminRoleInDb = await _roleManager.FindByNameAsync(RoleConstants.AdministratorRole); if (adminRoleInDb == null) { await _roleManager.CreateAsync(adminRole); adminRoleInDb = await _roleManager.FindByNameAsync(RoleConstants.AdministratorRole); _logger.LogInformation(_localizer["Seeded Administrator Role."]); } //Check if User Exists var superUser = new BlazorHeroUser { FirstName = "Mukesh", LastName = "Murugan", Email = "*****@*****.**", UserName = "******", EmailConfirmed = true, PhoneNumberConfirmed = true, CreatedOn = DateTime.Now, IsActive = true }; var superUserInDb = await _userManager.FindByEmailAsync(superUser.Email); if (superUserInDb == null) { await _userManager.CreateAsync(superUser, UserConstants.DefaultPassword); var result = await _userManager.AddToRoleAsync(superUser, RoleConstants.AdministratorRole); if (result.Succeeded) { _logger.LogInformation(_localizer["Seeded Default SuperAdmin User."]); } else { foreach (var error in result.Errors) { _logger.LogError(error.Description); } } } foreach (var permission in Permissions.GetRegisteredPermissions()) { await _roleManager.AddPermissionClaim(adminRoleInDb, permission); } }).GetAwaiter().GetResult(); }
private void AddAdministrator() { Task.Run(async() => { //Check if Role Exists var adminRole = new BlazorHeroRole(RoleConstants.AdministratorRole, _localizer["Administrator role with full permissions"]); var adminRoleInDb = await _roleManager.FindByNameAsync(RoleConstants.AdministratorRole); if (adminRoleInDb == null) { await _roleManager.CreateAsync(adminRole); _logger.LogInformation(_localizer["Seeded Administrator Role."]); } //Check if User Exists var superUser = new BlazorHeroUser { FirstName = "Mukesh", LastName = "Murugan", Email = "*****@*****.**", UserName = "******", EmailConfirmed = true, PhoneNumberConfirmed = true, CreatedOn = DateTime.Now, IsActive = true }; var superUserInDb = await _userManager.FindByEmailAsync(superUser.Email); if (superUserInDb == null) { await _userManager.CreateAsync(superUser, UserConstants.DefaultPassword); var result = await _userManager.AddToRoleAsync(superUser, RoleConstants.AdministratorRole); if (result.Succeeded) { foreach (var prop in typeof(Permissions).GetNestedTypes().SelectMany(c => c.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy))) { var propertyValue = prop.GetValue(null); if (propertyValue is not null) { await _roleManager.AddPermissionClaim(adminRole, propertyValue.ToString()); } } } _logger.LogInformation(_localizer["Seeded User with Administrator Role."]); } }).GetAwaiter().GetResult(); }
private void AddAdministrator() { Task.Run(async() => { //Check if Role Exists var adminRole = new IdentityRole(RoleConstant.AdministratorRole); var adminRoleInDb = await _roleManager.FindByNameAsync(RoleConstant.AdministratorRole); if (adminRoleInDb == null) { await _roleManager.CreateAsync(adminRole); _logger.LogInformation("Seeded Administrator Role."); } //Check if User Exists var superUser = new BlazorHeroUser { FirstName = "Vibhu", LastName = "Banga", Email = "*****@*****.**", UserName = "******", EmailConfirmed = true, PhoneNumberConfirmed = true, CreatedOn = DateTime.Now, IsActive = true }; var superUserInDb = await _userManager.FindByEmailAsync(superUser.Email); if (superUserInDb == null) { await _userManager.CreateAsync(superUser, UserConstant.DefaultPassword); var result = await _userManager.AddToRoleAsync(superUser, RoleConstant.AdministratorRole); if (result.Succeeded) { await _roleManager.GeneratePermissionClaimByModule(adminRole, PermissionModules.Users); await _roleManager.GeneratePermissionClaimByModule(adminRole, PermissionModules.Roles); await _roleManager.GeneratePermissionClaimByModule(adminRole, PermissionModules.Products); await _roleManager.GeneratePermissionClaimByModule(adminRole, PermissionModules.Brands); } _logger.LogInformation("Seeded User with Administrator Role."); } }).GetAwaiter().GetResult(); }
private async Task <IEnumerable <Claim> > GetClaimsAsync(BlazorHeroUser user) { var userClaims = await _userManager.GetClaimsAsync(user); var roles = await _userManager.GetRolesAsync(user); var roleClaims = new List <Claim>(); var permissionClaims = new List <Claim>(); for (int i = 0; i < roles.Count; i++) { roleClaims.Add(new Claim(ClaimTypes.Role, roles[i])); var thisRole = await _roleManager.FindByNameAsync(roles[i]); var allPermissionsForThisRoles = await _roleManager.GetClaimsAsync(thisRole); foreach (var permission in allPermissionsForThisRoles) { permissionClaims.Add(permission); } } var claims = new List <Claim> { new Claim(ClaimTypes.NameIdentifier, user.Id), new Claim(ClaimTypes.Email, user.Email), new Claim(ClaimTypes.Name, user.FirstName), new Claim(ClaimTypes.Surname, user.LastName), new Claim(ClaimTypes.MobilePhone, user.PhoneNumber ?? string.Empty) } .Union(userClaims) .Union(roleClaims) .Union(permissionClaims); return(claims); }
private async Task <string> GenerateJwtAsync(BlazorHeroUser user) { var token = GenerateEncryptedToken(GetSigningCredentials(), await GetClaimsAsync(user)); return(token); }
public async Task <IResult> RegisterAsync(RegisterRequest request, string origin) { var userWithSameUserName = await _userManager.FindByNameAsync(request.UserName); if (userWithSameUserName != null) { return(await Result.FailAsync(string.Format(_localizer["Username {0} is already taken."], request.UserName))); } var user = new BlazorHeroUser { Email = request.Email, FirstName = request.FirstName, LastName = request.LastName, UserName = request.UserName, PhoneNumber = request.PhoneNumber, IsActive = request.ActivateUser, EmailConfirmed = request.AutoConfirmEmail }; if (!string.IsNullOrWhiteSpace(request.PhoneNumber)) { var userWithSamePhoneNumber = await _userManager.Users.FirstOrDefaultAsync(x => x.PhoneNumber == request.PhoneNumber); if (userWithSamePhoneNumber != null) { return(await Result.FailAsync(string.Format(_localizer["Phone number {0} is already registered."], request.PhoneNumber))); } } var userWithSameEmail = await _userManager.FindByEmailAsync(request.Email); if (userWithSameEmail == null) { var result = await _userManager.CreateAsync(user, request.Password); if (result.Succeeded) { await _userManager.AddToRoleAsync(user, RoleConstants.BasicRole); if (!request.AutoConfirmEmail) { var verificationUri = await SendVerificationEmail(user, origin); var mailRequest = new MailRequest { From = "*****@*****.**", To = user.Email, Body = string.Format(_localizer["Please confirm your account by <a href='{0}'>clicking here</a>."], verificationUri), Subject = _localizer["Confirm Registration"] }; BackgroundJob.Enqueue(() => _mailService.SendAsync(mailRequest)); return(await Result <string> .SuccessAsync(user.Id, string.Format(_localizer["User {0} Registered. Please check your Mailbox to verify!"], user.UserName))); } return(await Result <string> .SuccessAsync(user.Id, string.Format(_localizer["User {0} Registered."], user.UserName))); } else { return(await Result.FailAsync(result.Errors.Select(a => _localizer[a.Description].ToString()).ToList())); } } else { return(await Result.FailAsync(string.Format(_localizer["Email {0} is already registered."], request.Email))); } }