public async Task Should_Create_Admin_User_And_Role() { await _identityDataSeeder.SeedAsync("1q2w3E*"); (await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.Normalize("admin"))).ShouldNotBeNull(); (await _roleRepository.FindByNormalizedNameAsync(_lookupNormalizer.Normalize("admin"))).ShouldNotBeNull(); }
public virtual async Task SeedAsync( string adminUserPassword, IEnumerable <string> adminRolePermissions = null, Guid?tenantId = null) { const string adminUserName = "******"; const string adminRoleName = "admin"; //"admin" user var adminUser = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.Normalize(adminUserName)); if (adminUser != null) { return; } adminUser = new IdentityUser(_guidGenerator.Create(), adminUserName, "*****@*****.**", tenantId); CheckIdentityErrors(await _userManager.CreateAsync(adminUser, adminUserPassword)); //"admin" role var adminRole = await _roleRepository.FindByNormalizedNameAsync(_lookupNormalizer.Normalize(adminRoleName)); if (adminRole == null) { adminRole = new IdentityRole(_guidGenerator.Create(), adminRoleName, tenantId); CheckIdentityErrors(await _roleManager.CreateAsync(adminRole)); if (adminRolePermissions != null) { await AddRolePermissionsAsync(adminRole, adminRolePermissions); } } CheckIdentityErrors(await _userManager.AddToRoleAsync(adminUser, adminRoleName)); }
public async Task <RegisterResponse> RegisterAsync(RegisterRequest request) { var response = new RegisterResponse(); var userFinded = await _users.AsNoTracking() .AnyAsync(d => d.Email.ToLower() == request.Email.ToLower().Trim()); if (userFinded) { return(response.ReturnWithCode(AuthenticationMessageHelper.Code.UserExists.Value(), AuthenticationMessageHelper.ResponseMessages)); } var passwordBanedList = _options.Value.PasswordsBanList; if (passwordBanedList.Any(d => d == request.Password)) { return(response.ReturnWithCode(AuthenticationMessageHelper.Code.RegisterUserInvalidPass.Value(), AuthenticationMessageHelper.ResponseMessages)); } var user = _mapper.Map <User>(request); user.PasswordHash = _securityService.GetSha256Hash(request.Password); user.NormalizedEmail = _keyNormalizer.Normalize(user.Email); user.NormalizedUserName = _keyNormalizer.Normalize(user.UserName); _users.Add(user); await _unitOfWork.SaveChangesAsync(); return(response.ReturnWithCode(AuthenticationMessageHelper.Code.RegisterSuccess.Value(), AuthenticationMessageHelper.ResponseMessages)); }
public async Task FindByIdAsync() { var user = await _identityUserRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.Normalize("john.nash")); user.ShouldNotBeNull(); (await _identityUserLookupAppService.FindByIdAsync(user.Id)).UserName.ShouldBe(user.UserName); }
public async Task SetRoleNameAsync() { var role = await _identityRoleRepository.FindByNormalizedNameAsync(_lookupNormalizer.Normalize("moderator")); role.ShouldNotBeNull(); (await _identityRoleManager.SetRoleNameAsync(role, "teacher")).Succeeded.ShouldBeTrue(); role.Name.ShouldBe("teacher"); }
public static DelegateConsentEntity Create(DelegateConsent consent, ILookupNormalizer normalizer) { Guard.ArgumentNotNull(consent, nameof(consent)); Guard.ArgumentNotNull(normalizer, nameof(normalizer)); return(new DelegateConsentEntity { ClientId = normalizer.Normalize(consent.ClientId), UserName = normalizer.Normalize(consent.UserName), Scopes = string.Join(Constants.SeperatorString.ToString(), consent.Scopes.Select(it => normalizer.Normalize(it))) }); }
public void SeedRoles() { var lastRoles = _roles.AsNoTracking().ToList(); List <SystemRoleItem> generatorRoles = new List <SystemRoleItem>(); var generalRoles = SystemRoles.GetAll; foreach (var role in generalRoles) { generatorRoles.Add(role); } if (!generatorRoles.Any()) { foreach (var groupRole in _groupRoles.ToList()) { _groupRoles.Remove(groupRole); } foreach (var role in _roles.ToList()) { _roles.Remove(role); } _unitOfWork.SaveChanges(); return; } if (!generatorRoles.Select(d => d.Name.ToLower()).Distinct().SequenceEqual(lastRoles.Select(d => d.Name.ToLower()).Distinct())) { foreach (var groupRole in _groupRoles.ToList()) { _groupRoles.Remove(groupRole); } foreach (var role in _roles.ToList()) { _roles.Remove(role); } foreach (var role in generatorRoles) { _roles.Add(new Role { NameFa = role.NameFa, Name = role.Name, Description = role.Description, RoleType = (RoleType)role.Type, RoleCategory = (RoleCategory)role.Category, NormalizedName = _keyNormalizer.Normalize(role.Name) }); } _unitOfWork.SaveChanges(); } }
/// <summary> /// Creates a new <see cref="ApplicationEntity"/>. /// </summary> /// <param name="application">The <see cref="Application"/> on which the new <see cref="ApplicationEntity"/> is created based.</param> /// <param name="normalizer">The <see cref="ILookupNormalizer"/> to normalize the client identifer.</param> /// <exception cref="ArgumentNullException">Specified <paramref name="application"/> is null.</exception> /// <exception cref="ArgumentNullException">Specified <paramref name="normalizer"/> is null.</exception> public static ApplicationEntity Create(Application application, ILookupNormalizer normalizer) { Guard.ArgumentNotNull(application, nameof(application)); Guard.ArgumentNotNull(normalizer, nameof(normalizer)); return(new ApplicationEntity { ClientId = normalizer.Normalize(application.ClientId), ClientSecret = application.ClientSecret, RedirectUris = normalizer.Normalize(string.Join(Constants.SeperatorString.ToString(), application.RedirectUris.Select(it => it.ToString().ToLowerInvariant()).ToArray())), ClientType = (int)application.ClientType, Owner = normalizer.Normalize(application.Owner), ApplicationName = application.ApplicationName }); }
public async Task SetEmailAsync(TUser user, string email, CancellationToken cancellationToken) { await SetNormalizedEmailAsync(user, _normalizer.Normalize(user.Email), cancellationToken); user.Email = email; await _userCollection.UpdateAsync(user); }
public async Task Resgiter_WhenModelIsValidWithNullPassword_ExpectSuccessAndUserPasswordSet() { //arrange var username = Guid.NewGuid().ToString(); var user = new IdentityExpressUser() { UserName = username, NormalizedUserName = normalizer.Normalize(username) }; using (var context = new IdentityExpressDbContext(options)) { context.Users.Add(user); context.SaveChanges(); } var model = new RegisterInputModel { ConfirmPassword = "******", Password = "******", Username = username }; var list = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("ConfirmPassword", "Password123!"), new KeyValuePair <string, string>("Password", "Password123!"), new KeyValuePair <string, string>("Username", username) }; //act var result = await client.PostAsync("/account/register", new FormUrlEncodedContent(list)); //assert Assert.True(result.IsSuccessStatusCode); IdentityExpressUser foundUser; using (var context = new IdentityExpressDbContext(options)) { foundUser = await context.Users.FirstOrDefaultAsync(x => x.UserName == username); } Assert.NotNull(foundUser); Assert.NotNull(foundUser.PasswordHash); }
public virtual async Task <IdentityDataSeedResult> SeedAsync( string adminEmail, string adminPassword, Guid?tenantId = null) { Check.NotNullOrWhiteSpace(adminEmail, nameof(adminEmail)); Check.NotNullOrWhiteSpace(adminPassword, nameof(adminPassword)); var result = new IdentityDataSeedResult(); //"admin" user const string adminUserName = "******"; var adminUser = await _userRepository.FindByNormalizedUserNameAsync( _lookupNormalizer.Normalize(adminUserName) ); if (adminUser != null) { return(result); } adminUser = new IdentityUser( _guidGenerator.Create(), adminUserName, adminEmail, tenantId ) { Name = adminUserName }; (await _userManager.CreateAsync(adminUser, adminPassword)).CheckErrors(); result.CreatedAdminUser = true; //"admin" role const string adminRoleName = "admin"; var adminRole = await _roleRepository.FindByNormalizedNameAsync(_lookupNormalizer.Normalize(adminRoleName)); if (adminRole == null) { adminRole = new IdentityRole( _guidGenerator.Create(), adminRoleName, tenantId ) { IsStatic = true, IsPublic = true }; (await _roleManager.CreateAsync(adminRole)).CheckErrors(); result.CreatedAdminRole = true; } (await _userManager.AddToRoleAsync(adminUser, adminRoleName)).CheckErrors(); return(result); }
public async Task SetRolesAsync() { using (var uow = _unitOfWorkManager.Begin()) { var user = await _identityUserRepository.FindByNormalizedUserNameAsync( _lookupNormalizer.Normalize("david")); user.ShouldNotBeNull(); var identityResult = await _identityUserManager.SetRolesAsync(user, new List <string>() { "moderator", }); identityResult.Succeeded.ShouldBeTrue(); user.Roles.ShouldContain(x => x.RoleId == _testData.RoleModeratorId); await uow.CompleteAsync(); } }
private void AddRoles() { _adminRole = _roleRepository.FindByNormalizedName(_lookupNormalizer.Normalize("admin")); _moderator = new IdentityRole(_testData.RoleModeratorId, "moderator"); _moderator.AddClaim(_guidGenerator, new Claim("test-claim", "test-value")); _roleRepository.Insert(_moderator); _supporterRole = new IdentityRole(_guidGenerator.Create(), "supporter"); _roleRepository.Insert(_supporterRole); }
public async Task <IUserData> FindByUserNameAsync( string userName, CancellationToken cancellationToken = default) { return(( await _userRepository.FindByNormalizedUserNameAsync( _lookupNormalizer.Normalize(userName), includeDetails: false, cancellationToken: cancellationToken ) )?.ToAbpUserData()); }
/// <summary> /// Creates a new <see cref="OAuthGrantEntity"/>. /// </summary> /// <param name="clientId">The client identifier.</param> /// <param name="userName">Name of the user.</param> /// <param name="authorizationCode">The authorization code.</param> /// <param name="accessToken">The access token.</param> /// <param name="refreshToken">The refresh token.</param> /// <param name="normalizer">The normalizer.</param> /// <returns></returns> public static OAuthGrantEntity Create( string clientId, string userName, string authorizationCode, string accessToken, string refreshToken, ILookupNormalizer normalizer) { Guard.ArgumentNotNullOrWhiteSpace(clientId, nameof(clientId)); Guard.ArgumentNotNullOrWhiteSpace(userName, nameof(userName)); Guard.ArgumentNotNull(normalizer, nameof(normalizer)); return(new OAuthGrantEntity { ClientId = normalizer.Normalize(clientId), UserName = normalizer.Normalize(userName), AuthorizationCode = authorizationCode, AccessToken = accessToken, RefreshToken = refreshToken }); }
public virtual async Task <IdentityDataSeedResult> SeedAsync( string adminUserPassword, Guid?tenantId = null) { var result = new IdentityDataSeedResult(); const string adminUserName = "******"; const string adminRoleName = "admin"; //"admin" user var adminUser = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.Normalize(adminUserName)); if (adminUser != null) { return(result); } adminUser = new IdentityUser(_guidGenerator.Create(), adminUserName, "*****@*****.**", tenantId); adminUser.Name = adminUserName; CheckIdentityErrors(await _userManager.CreateAsync(adminUser, adminUserPassword)); result.CreatedAdminUser = true; //"admin" role var adminRole = await _roleRepository.FindByNormalizedNameAsync(_lookupNormalizer.Normalize(adminRoleName)); if (adminRole == null) { adminRole = new IdentityRole(_guidGenerator.Create(), adminRoleName, tenantId); adminRole.IsStatic = true; adminRole.IsPublic = true; CheckIdentityErrors(await _roleManager.CreateAsync(adminRole)); result.CreatedAdminRole = true; } CheckIdentityErrors(await _userManager.AddToRoleAsync(adminUser, adminRoleName)); return(result); }
public async Task Should_Trigger_Distributed_EntityUpdated_Event() { using (var uow = _unitOfWorkManager.Begin()) { var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.Normalize("john.nash")); await _userManager.SetEmailAsync(user, "*****@*****.**"); _testCounter.GetValue("EntityUpdatedEto<UserEto>").ShouldBe(0); await uow.CompleteAsync(); } _testCounter.GetValue("EntityUpdatedEto<UserEto>").ShouldBe(1); }
public async Task AddUserToRole(string id, string roleName, CancellationToken cancellationToken = default(CancellationToken)) { var normalizedRoleName = keyNormalizer.Normalize(roleName); var user = await userStore.FindByIdAsync(id, cancellationToken); if (user == null) { throw new Exception($"user {id} not found"); } await userStore.AddToRoleAsync(user, normalizedRoleName, cancellationToken); }
public async Task RegisterAsync() { var registerDto = new RegisterDto() { UserName = "******", EmailAddress = "*****@*****.**", Password = "******", AppName = "MVC" }; await _accountAppService.RegisterAsync(registerDto); var user = await _identityUserRepository.FindByNormalizedUserNameAsync( _lookupNormalizer.Normalize("bob.lee")); user.ShouldNotBeNull(); user.UserName.ShouldBe("bob.lee"); user.Email.ShouldBe("*****@*****.**"); (await _userManager.CheckPasswordAsync(user, "P@ssW0rd")).ShouldBeTrue(); }
public async Task <IUser> CreateUserAsync(string username, string email, string[] roleNames, string password, Action <string, string> reportError) { if (await _userManager.FindByEmailAsync(email) != null) { ReportError(string.Empty, "Email 重复", reportError); } var roles = await _roleProvider.GetRolesAsync(); var userRoles = roleNames.Where(e => !roles.Select(r => r.Rolename).Contains(e)) .Select(e => new UserRole() { Role = new Role(e) { NormalizedRolename = _keyNormalizer.Normalize(e) } }).ToList(); userRoles.AddRange(roles.Where(e => roleNames.Contains(e.Rolename)) .Select(e => new UserRole() { RoleId = ((Role)e).Id }).ToList()); var user = new User { Username = username, Email = email, Roles = userRoles }; var identityResult = await _userManager.CreateAsync(user, password); if (!identityResult.Succeeded) { ReportError(string.Empty, "创建不成功", reportError); } return(user); }
public static string ConvertRoleToId(this IRole user, ILookupNormalizer lookupNormalizer) { return lookupNormalizer.Normalize($"IdentityRole:{user.RoleId}".ToLower()); }
public async Task UpdateAsync() { var role = await _identityRoleRepository.FindByNormalizedNameAsync(_lookupNormalizer.Normalize("moderator")); role.ShouldNotBeNull(); role.IsDefault = true; await _identityRoleStore.UpdateAsync(role); role.IsDefault.ShouldBeTrue(); }
public async Task GetUserIdAsync() { var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.Normalize("john.nash")); user.ShouldNotBeNull(); (await _identityUserStore.GetUserIdAsync(user)).ShouldBe(user.Id.ToString()); }
public static string ConvertEmailToId(string email, ILookupNormalizer lookupNormalizer) { return lookupNormalizer.Normalize($"IdentityUser:{email}"); }
/// <summary> /// Gets a normalized representation of the specified <paramref name="key"/>. /// </summary> /// <param name="key">The value to normalize.</param> /// <returns>A normalized representation of the specified <paramref name="key"/>.</returns> public virtual string NormalizeKey(string key) { return((keyNormalizer == null) ? key : keyNormalizer.Normalize(key)); }
public async Task <User> FindUserByNameAsync(string userName) { string normalizedName = keyNormalizer.Normalize(userName); return(await context.Users.FirstOrDefaultAsync(u => u.NormalizedUserName == normalizedName)); }
private Identity UpdateNormalizedProperties(Identity identity) { identity.NormalizedEmail = _keyNormalizer.Normalize(identity.Email); return(identity); }
private void AddUserPermissions() { var david = _userRepository.FindByNormalizedUserName(_lookupNormalizer.Normalize("david")); AddPermission(TestPermissionNames.MyPermission1, UserPermissionValueProvider.ProviderName, david.Id.ToString()); }
public static string ConvertSessionKeyToId(this string sessionKey, ILookupNormalizer lookupNormalizer) { return lookupNormalizer.Normalize($"IdentitySession:{sessionKey}"); }
public async Task Users() { var roleStore = new RoleStore <AppRole>(_context); var userStore = new UserStore <AppUser>(_context); if (!_context.AppUserRole.Any()) { if (!_context.Users.Any()) { if (!_context.AppRole.Any()) { var applicationRoles = new List <AppRole> { }; foreach (var item in RoleData.AppRoles) { applicationRoles.Add( new AppRole { CreatedDate = DateTime.Now, Name = item, Description = "", NormalizedName = item.ToLower() }); } ; foreach (var role in applicationRoles) { await _context.AppRole.AddAsync(role) .ConfigureAwait(false); } await _context.SaveChangesAsync().ConfigureAwait(false); } var users = new UserInitializerVM[] { new UserInitializerVM { Name = "WebMaster", Email = "*****@*****.**", Roles = RoleData.AppRoles.ToArray(), Key = "34#$erERdfDFcvCV", Image = "/images/logo.svg", Rating = 10, Claims = ClaimData.UserClaims.ToArray() }, }; foreach (var item in users) { var user = new AppUser { UserName = item.Name, NormalizedUserName = _normalizer.Normalize(item.Name), Email = item.Email, NormalizedEmail = _normalizer.Normalize(item.Email), EmailConfirmed = true, LockoutEnabled = false, SecurityStamp = Guid.NewGuid().ToString(), ProfileImageUrl = item.Image }; var hasher = new PasswordHasher <AppUser>(); var hashedPassword = hasher.HashPassword(user, item.Key); user.PasswordHash = hashedPassword; foreach (var claim in item.Claims) { user.Claims.Add(new IdentityUserClaim <string> { ClaimType = claim, ClaimValue = claim }); } foreach (var role in item.Roles) { var roller = _context.Roles.SingleOrDefault(r => r.Name == role); user.Roles.Add(new IdentityUserRole <string> { UserId = user.Id, RoleId = roller.Id }); } await _context.Users.AddAsync(user) .ConfigureAwait(false); } await _context.SaveChangesAsync() .ConfigureAwait(false); } } return; }
private string NormalizeKey(string key) { return(_keyNormalizer == null ? key : _keyNormalizer.Normalize(key)); }
public async Task <string> GetNormalizedUserNameAsync(User user, CancellationToken cancellationToken) { return(await Task.FromResult(_normalizer.Normalize(user.Email))); }