예제 #1
0
        public async Task Role_Updated_Distributed_Event_Test()
        {
            var role = await RoleRepository.FindByNormalizedNameAsync(LookupNormalizer.NormalizeName("moderator"));

            var permissionGrantsInRole = await PermissionGrantRepository.GetListAsync("R", role.Name);

            permissionGrantsInRole.ShouldNotBeNull();
            permissionGrantsInRole.Count.ShouldBeGreaterThan(0);
            var count = permissionGrantsInRole.Count;

            using (var uow = UowManager.Begin())
            {
                var identityResult = await RoleManager.SetRoleNameAsync(role, "TestModerator");

                identityResult.Succeeded.ShouldBeTrue();
                await RoleRepository.UpdateAsync(role);

                await uow.CompleteAsync();
            }

            role = await RoleRepository.GetAsync(role.Id);

            role.Name.ShouldBe("TestModerator");

            permissionGrantsInRole = await PermissionGrantRepository.GetListAsync("R", role.Name);

            permissionGrantsInRole.Count.ShouldBe(count);
        }
예제 #2
0
        public async Task CanAddRole()
        {
            var userId   = Guid.NewGuid();
            var roleId   = Guid.NewGuid();
            var username = $"{userId}";
            var user     = new IdentityUser <Guid>
            {
                Id = userId,
                NormalizedEmail    = username + "@test.com",
                Email              = username + "@test.com",
                UserName           = username,
                NormalizedUserName = username
            };

            var store = GetSubject(out var roleStore);
            await roleStore.CreateAsync(new IdentityRole <Guid>
            {
                Id             = roleId,
                Name           = roleId.ToString(),
                NormalizedName = roleId.ToString()
            }, CancellationToken.None);

            var createResult = await store.CreateAsync(user);

            await store.AddToRoleAsync(user, normalizer.NormalizeName(roleId.ToString()));

            var roleFromUser = await store.GetRolesAsync(user);

            var userInRole = await store.GetUsersInRoleAsync(normalizer.NormalizeName(roleId.ToString()));

            Assert.True(createResult.Succeeded);
            Assert.Single(roleFromUser);
            Assert.Single(userInRole);
        }
예제 #3
0
    public async Task FindByIdAsync()
    {
        var user = await _identityUserRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash"));

        user.ShouldNotBeNull();

        (await _identityUserLookupAppService.FindByIdAsync(user.Id)).UserName.ShouldBe(user.UserName);
    }
예제 #4
0
        public async Task Should_Create_Admin_User_And_Role()
        {
            await _identityDataSeeder.SeedAsync("*****@*****.**", "1q2w3E*").ConfigureAwait(false);

            (await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("admin")).ConfigureAwait(false)).ShouldNotBeNull();
            (await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("admin")).ConfigureAwait(false)).Name.ShouldBe("admin");
            (await _roleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("admin")).ConfigureAwait(false)).ShouldNotBeNull();
        }
예제 #5
0
 public void MarkExpired(string userName)
 {
     userName = _normalizer.NormalizeName(userName);
     _cache.Set(
         key: "SlideExpiration: " + userName,
         value: DateTimeOffset.UtcNow,
         absoluteExpirationRelativeToNow: _options.ValidationInterval);
 }
예제 #6
0
    public async Task SetRoleNameAsync()
    {
        var role = await _identityRoleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("moderator"));

        role.ShouldNotBeNull();

        (await _identityRoleManager.SetRoleNameAsync(role, "teacher")).Succeeded.ShouldBeTrue();

        role.Name.ShouldBe("teacher");
    }
예제 #7
0
        public Task <string> GetNormalizedUserNameAsync(TUser user, CancellationToken cancellationToken)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            cancellationToken.ThrowIfCancellationRequested();

            return(Task.FromResult(user.NormalizedUserName ?? _normalizer.NormalizeName(user.UserName)));
        }
        private async Task CreateUserAsync(string userName, string name, string surname, DataSeedContext context)
        {
            await _identityOptions.SetAsync();

            if ((await _identityUserRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName(userName))) != null)
            {
                return;
            }

            var user = new IdentityUser(
                _guidGenerator.Create(),
                userName,
                userName + "@abp.io",
                context.TenantId
                );

            user.Name    = name;
            user.Surname = surname;

            await _identityUserManager.CreateAsync(user,
                                                   "1q2w3E*"
                                                   );

            await _identityUserManager.AddToRoleAsync(user, "admin");
        }
예제 #9
0
        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.NormalizeName(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.NormalizeName(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);
        }
예제 #10
0
        public Task <string> GetNormalizedRoleNameAsync(ApplicationRole role, CancellationToken cancellationToken)
        {
            if (role == null)
            {
                throw new ArgumentNullException(nameof(role));
            }

            return(Task.FromResult(_keyNormalizer.NormalizeName(role.Name)));
        }
예제 #11
0
        public async Task <IdentityResult> Create(TRole role)
        {
            if (Exists || string.IsNullOrEmpty(role.Name))
            {
                return(IdentityResult.Failed());
            }

            // Normalize name
            role.NormalizedName = _normalizer.NormalizeName(role.Name);

            if (!await GrainFactory.AddOrUpdateToLookup(OrleansIdentityConstants.RoleLookup, role.NormalizedName, _id))
            {
                return(IdentityResult.Failed());
            }

            _data.State.Role = role;
            await _data.WriteStateAsync();

            return(IdentityResult.Success);
        }
예제 #12
0
        public async Task SetRolesAsync()
        {
            using (var uow = _unitOfWorkManager.Begin())
            {
                var user = await _identityUserRepository.FindByNormalizedUserNameAsync(
                    _lookupNormalizer.NormalizeName("david")).ConfigureAwait(false);

                user.ShouldNotBeNull();

                var identityResult = await _identityUserManager.SetRolesAsync(user, new List <string>()
                {
                    "moderator",
                }).ConfigureAwait(false);

                identityResult.Succeeded.ShouldBeTrue();
                user.Roles.ShouldContain(x => x.RoleId == _testData.RoleModeratorId);

                await uow.CompleteAsync().ConfigureAwait(false);
            }
        }
예제 #13
0
        private void AddRoles()
        {
            _adminRole = _roleRepository.FindByNormalizedName(_lookupNormalizer.NormalizeName("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);
        }
예제 #14
0
        private async Task AddRoles()
        {
            _adminRole = await _roleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("admin")).ConfigureAwait(false);

            _moderator = new IdentityRole(_testData.RoleModeratorId, "moderator");
            _moderator.AddClaim(_guidGenerator, new Claim("test-claim", "test-value"));
            await _roleRepository.InsertAsync(_moderator).ConfigureAwait(false);

            _supporterRole = new IdentityRole(_guidGenerator.Create(), "supporter");
            await _roleRepository.InsertAsync(_supporterRole).ConfigureAwait(false);
        }
예제 #15
0
 public virtual async Task <IUserData> FindByUserNameAsync(
     string userName,
     CancellationToken cancellationToken = default)
 {
     return((
                await _userRepository.FindByNormalizedUserNameAsync(
                    _lookupNormalizer.NormalizeName(userName),
                    includeDetails: false,
                    cancellationToken: cancellationToken
                    )
                )?.ToAbpUserData());
 }
예제 #16
0
    public async Task AddRoleToOrganizationUnitAsync()
    {
        OrganizationUnit ou        = null;
        IdentityRole     adminRole = null;

        using (var uow = _unitOfWorkManager.Begin())
        {
            ou = await _organizationUnitRepository.GetAsync("OU1", true);

            adminRole = await _identityRoleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("admin"));

            await _organizationUnitManager.AddRoleToOrganizationUnitAsync(adminRole, ou);

            await _organizationUnitRepository.UpdateAsync(ou);

            await uow.CompleteAsync();
        }

        ou = await _organizationUnitRepository.GetAsync("OU1", includeDetails : true);

        ou.Roles.First().RoleId.ShouldBe(adminRole.Id);
    }
        public async Task Register_WhenModelIsValidWithNullPassword_ExpectSuccessAndUserPasswordSet()
        {
            //arrange
            var username = Guid.NewGuid().ToString();
            var user     = new IdentityExpressUser()
            {
                UserName           = username,
                NormalizedUserName = normalizer.NormalizeName(username)
            };

            using (var context = new IdentityExpressDbContext(options))
            {
                context.Users.Add(user);
                context.SaveChanges();
            }

            var registerInputModel = 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(registerInputModel));

            //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);
        }
예제 #18
0
        public async Task Should_Trigger_Distributed_EntityUpdated_Event()
        {
            using (var uow = _unitOfWorkManager.Begin())
            {
                var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash"));

                await _userManager.SetEmailAsync(user, "*****@*****.**");

                _testCounter.GetValue("EntityUpdatedEto<UserEto>").ShouldBe(0);
                await uow.CompleteAsync();
            }

            _testCounter.GetValue("EntityUpdatedEto<UserEto>").ShouldBe(1);
        }
        public async Task <IdentityResult> Create(TUser user)
        {
            if (Exists)
            {
                return(IdentityResult.Failed(_errorDescriber.LoginAlreadyAssociated()));
            }
            if (string.IsNullOrEmpty(user.Email))
            {
                return(IdentityResult.Failed(_errorDescriber.InvalidEmail(user.Email)));
            }
            if (string.IsNullOrEmpty(user.UserName))
            {
                return(IdentityResult.Failed(_errorDescriber.InvalidUserName(user.UserName)));
            }

            // Make sure to set normalized username and email
            user.NormalizedEmail    = _normalizer.NormalizeEmail(user.Email);
            user.NormalizedUserName = _normalizer.NormalizeName(user.UserName);

            if (!await GrainFactory.AddOrUpdateToLookup(OrleansIdentityConstants.EmailLookup, user.NormalizedEmail, _id))
            {
                return(IdentityResult.Failed(_errorDescriber.DuplicateEmail(user.Email)));
            }

            if (!await GrainFactory.AddOrUpdateToLookup(OrleansIdentityConstants.UsernameLookup, user.NormalizedUserName, _id))
            {
                await GrainFactory.SafeRemoveFromLookup(OrleansIdentityConstants.EmailLookup, user.NormalizedEmail, _id);

                return(IdentityResult.Failed(_errorDescriber.DuplicateUserName(user.UserName)));
            }

            _data.State.User = user;

            await _data.WriteStateAsync();

            return(IdentityResult.Success);
        }
예제 #20
0
        public Task SetNormalizedUserNameAsync(ApplicationUser user, string normalizedName,
                                               CancellationToken cancellationToken)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            if (string.IsNullOrEmpty(normalizedName))
            {
                throw new ArgumentNullException(nameof(normalizedName), "Null or empty");
            }

            user.NormalizedUserName = _keyNormalizer.NormalizeName(normalizedName);
            return(Task.CompletedTask);
        }
예제 #21
0
        public async Task RegisterAsync()
        {
            var registerDto = new RegisterDto
            {
                UserName     = "******",
                EmailAddress = "*****@*****.**",
                Password     = "******",
                AppName      = "MVC"
            };

            await _accountAppService.RegisterAsync(registerDto);

            var user = await _identityUserRepository.FindByNormalizedUserNameAsync(
                _lookupNormalizer.NormalizeName("bob.lee"));

            user.ShouldNotBeNull();
            user.UserName.ShouldBe("bob.lee");
            user.Email.ShouldBe("*****@*****.**");

            (await _userManager.CheckPasswordAsync(user, "P@ssW0rd")).ShouldBeTrue();
        }
예제 #22
0
 private string NormalizeKey(string key)
 {
     return(_keyNormalizer == null ? key : _keyNormalizer.NormalizeName(key));
 }
        public async Task AddMemberToOrganizationUnit()
        {
            using (var uow = _unitOfWorkManager.Begin())
            {
                var ou111 = await _organizationUnitRepository.GetAsync(
                    _lookupNormalizer.NormalizeName("OU111"));

                var user = await _identityUserRepository.FindByNormalizedUserNameAsync(
                    _lookupNormalizer.NormalizeName("david"));

                user.ShouldNotBeNull();

                user.OrganizationUnits.Count.ShouldBe(1);
                await _identityUserManager.AddToOrganizationUnitAsync(user.Id, ou111.Id);

                await uow.CompleteAsync();
            }

            var updatedUser = await _identityUserRepository.FindByNormalizedUserNameAsync(
                _lookupNormalizer.NormalizeName("david"));

            updatedUser.OrganizationUnits.Count.ShouldBe(2);
        }
예제 #24
0
        public async Task GetUserIdAsync()
        {
            var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash"));

            user.ShouldNotBeNull();

            (await _identityUserStore.GetUserIdAsync(user)).ShouldBe(user.Id.ToString());
        }
        public Task <string> GetNormalizedUserNameAsync(TUser user, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            return(Task.FromResult(user.NormalizedUserName ?? _normalizer.NormalizeName(user.UserName)));
        }
        private async Task CreateUserWithExtraProperty()
        {
            //"test" user
            const string userName = "******";
            var          user     = await UserRepository.FindByNormalizedUserNameAsync(LookupNormalizer.NormalizeName(userName));

            if (user != null)
            {
                return;
            }

            user = new Volo.Abp.Identity.IdentityUser(
                GuidGenerator.Create(),
                userName,
                "*****@*****.**"
                )
            {
                Name = userName
            };
            user.SetProperty("WarehouseId", GuidGenerator.Create());
            (await UserManager.CreateAsync(user, "1q2w3E*")).CheckErrors();
        }
예제 #27
0
파일: SeedService.cs 프로젝트: grpiccoli/BM
        public async Task Users()
        {
            using var roleStore = new RoleStore <AppRole>(_context);
            using 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 = _normalizer.NormalizeName(item)
                            });
                        }
                        ;

                        foreach (var role in applicationRoles)
                        {
                            await _context.AppRole
                            .AddAsync(role)
                            .ConfigureAwait(false);
                        }
                        await _context.SaveChangesAsync()
                        .ConfigureAwait(false);
                    }
                    var users   = new List <UserInitializerVM>();
                    var userPer = new UserInitializerVM
                    {
                        Name     = "PER",
                        Email    = "*****@*****.**",
                        Key      = "per2018",
                        ImageUri = new Uri("~/images/ico/mejillondechile.svg", UriKind.Relative)
                    };
                    userPer.Roles.Add(RoleData.AppRoles.ElementAt(0));
                    userPer.Plataforma.Add(Plataforma.mytilidb);
                    userPer.Claims.Add("per");
                    users.Add(userPer);
                    var userMitilidb = new UserInitializerVM
                    {
                        Name     = "MytiliDB",
                        Email    = "*****@*****.**",
                        Key      = "sivisam2016",
                        ImageUri = new Uri("~/images/ico/bibliomit.svg", UriKind.Relative)
                    };
                    userMitilidb.Roles.Add(RoleData.AppRoles.ElementAt(0));
                    userMitilidb.Plataforma.Add(Plataforma.mytilidb);
                    userMitilidb.Claims.Add("mitilidb");
                    users.Add(userMitilidb);
                    var userWebmaster = new UserInitializerVM
                    {
                        Name     = "WebMaster",
                        Email    = "*****@*****.**",
                        Key      = "34#$erERdfDFcvCV",
                        ImageUri = new Uri("~/images/ico/bibliomit.svg", UriKind.Relative),
                        Rating   = 10
                    };
                    userWebmaster.Roles.AddRange(RoleData.AppRoles);
                    userWebmaster.Plataforma.AddRange(EnumUtils.Enum2List <Plataforma>());
                    userWebmaster.Claims.AddRange(ClaimData.UserClaims);
                    users.Add(userWebmaster);
                    var userSernapesca = new UserInitializerVM
                    {
                        Name     = "Sernapesca",
                        Email    = "*****@*****.**",
                        Key      = "sernapesca2018",
                        ImageUri = new Uri("~/images/ico/bibliomit.svg", UriKind.Relative)
                    };
                    userSernapesca.Roles.Add(RoleData.AppRoles.ElementAt(0));
                    userSernapesca.Plataforma.Add(Plataforma.boletin);
                    userSernapesca.Claims.Add("sernapesca");
                    users.Add(userSernapesca);
                    var userIntemit = new UserInitializerVM
                    {
                        Name     = "Intemit",
                        Email    = "*****@*****.**",
                        Key      = "intemit2018",
                        ImageUri = new Uri("~/images/ico/bibliomit.svg", UriKind.Relative)
                    };
                    userIntemit.Roles.Add(RoleData.AppRoles.ElementAt(0));
                    userIntemit.Plataforma.Add(Plataforma.psmb);
                    userIntemit.Claims.Add("intemit");
                    users.Add(userIntemit);

                    foreach (var item in users)
                    {
                        var user = new AppUser
                        {
                            UserName           = item.Name,
                            NormalizedUserName = _normalizer.NormalizeName(item.Name),
                            Email           = item.Email,
                            NormalizedEmail = _normalizer.NormalizeEmail(item.Email),
                            EmailConfirmed  = true,
                            LockoutEnabled  = false,
                            SecurityStamp   = Guid.NewGuid().ToString(),
                            ProfileImageUrl = item.ImageUri
                        };

                        user.NormalizedUserName = _normalizer
                                                  .NormalizeName(user.UserName);
                        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 = await _context.Roles
                                         .SingleOrDefaultAsync(r => r.Name == role)
                                         .ConfigureAwait(false);

                            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;
        }
예제 #28
0
        private void AddUserPermissions()
        {
            var david = _userRepository.FindByNormalizedUserName(_lookupNormalizer.NormalizeName("david"));

            AddPermission(TestPermissionNames.MyPermission1, UserPermissionValueProvider.ProviderName, david.Id.ToString());
        }
예제 #29
0
        public async Task UpdateAsync()
        {
            var role = await _identityRoleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("moderator"));

            role.ShouldNotBeNull();

            role.IsDefault = true;
            await _identityRoleStore.UpdateAsync(role);

            role.IsDefault.ShouldBeTrue();
        }
예제 #30
0
        private async Task AddUserPermissions()
        {
            var david = AsyncHelper.RunSync(() => _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("david")));

            await AddPermission(TestPermissionNames.MyPermission1, UserPermissionValueProvider.ProviderName, david.Id.ToString()).ConfigureAwait(false);
        }