public async Task <bool> Initialize() { bool isChanged = Database.EnsureCreated(); var newRoles = AppUser.Role.Names.Where(n => !Roles.Where(r => string.Equals(n, r.Name)).Any()).Select(n => new IdentityRole(n)).ToList(); if (newRoles.Any()) { await Roles.AddRangeAsync(newRoles); isChanged = true; } if (!Users.Any()) { if (!await CreateUser(AppUser.DefaultAdminUserName, AppUser.DefaultAdminUserPassword, "", true)) { return(false); } var adminUser = await Users.Where(u => u.UserName == AppUser.DefaultAdminUserName).FirstOrDefaultAsync(); var adminRole = await Roles.Where(r => r.Name == AppUser.Role.Admin).FirstOrDefaultAsync(); await UserRoles.AddAsync(new IdentityUserRole <string> { UserId = adminUser.Id, RoleId = adminRole.Id, }); isChanged = true; } if (!System.Any()) { await System.AddAsync(new DBConfig.System { Email = new DBConfig.System.EmailServer() }); isChanged = true; } if (isChanged) { await SaveChangesAsync(); } AppUser.Role.IdNameMap = await Roles.Where(r => AppUser.Role.Names.Contains(r.Name)).ToDictionaryAsync(r => r.Id, r => r.Name); AppUser.Role.NameIdMap = AppUser.Role.IdNameMap.ToDictionary(p => p.Value, p => p.Key); return(true); }
public async Task AddToRoleAsync(User user, string roleName, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) { throw new ArgumentNullException(nameof(user)); } if (string.IsNullOrWhiteSpace(roleName)) { throw new ArgumentException("Role name may not be null or empty."); } var roleEntity = await FindRoleAsync(roleName, cancellationToken); if (roleEntity == null) { throw new InvalidOperationException($"Role {roleName} does not exist."); } await UserRoles.AddAsync(new UserRole(user, roleEntity), cancellationToken); await SaveChanges(cancellationToken); }