Example #1
0
 public void UserStoreMethodsThrowWhenDisposedTest()
 {
     var db = UnitTestHelper.CreateDefaultDb();
     var store = new UserStore<IdentityUser>(db);
     store.Dispose();
     Assert.Throws<ObjectDisposedException>(() => AsyncHelper.RunSync(() => store.AddClaimAsync(null, null)));
     Assert.Throws<ObjectDisposedException>(() => AsyncHelper.RunSync(() => store.AddLoginAsync(null, null)));
     Assert.Throws<ObjectDisposedException>(() => AsyncHelper.RunSync(() => store.AddToRoleAsync(null, null)));
     Assert.Throws<ObjectDisposedException>(() => AsyncHelper.RunSync(() => store.GetClaimsAsync(null)));
     Assert.Throws<ObjectDisposedException>(() => AsyncHelper.RunSync(() => store.GetLoginsAsync(null)));
     Assert.Throws<ObjectDisposedException>(() => AsyncHelper.RunSync(() => store.GetRolesAsync(null)));
     Assert.Throws<ObjectDisposedException>(() => AsyncHelper.RunSync(() => store.IsInRoleAsync(null, null)));
     Assert.Throws<ObjectDisposedException>(() => AsyncHelper.RunSync(() => store.RemoveClaimAsync(null, null)));
     Assert.Throws<ObjectDisposedException>(() => AsyncHelper.RunSync(() => store.RemoveLoginAsync(null, null)));
     Assert.Throws<ObjectDisposedException>(
         () => AsyncHelper.RunSync(() => store.RemoveFromRoleAsync(null, null)));
     Assert.Throws<ObjectDisposedException>(() => AsyncHelper.RunSync(() => store.RemoveClaimAsync(null, null)));
     Assert.Throws<ObjectDisposedException>(() => AsyncHelper.RunSync(() => store.FindAsync(null)));
     Assert.Throws<ObjectDisposedException>(() => AsyncHelper.RunSync(() => store.FindByIdAsync(null)));
     Assert.Throws<ObjectDisposedException>(() => AsyncHelper.RunSync(() => store.FindByNameAsync(null)));
     Assert.Throws<ObjectDisposedException>(() => AsyncHelper.RunSync(() => store.UpdateAsync(null)));
     Assert.Throws<ObjectDisposedException>(() => AsyncHelper.RunSync(() => store.DeleteAsync(null)));
     Assert.Throws<ObjectDisposedException>(
         () => AsyncHelper.RunSync(() => store.SetEmailConfirmedAsync(null, true)));
     Assert.Throws<ObjectDisposedException>(() => AsyncHelper.RunSync(() => store.GetEmailConfirmedAsync(null)));
     Assert.Throws<ObjectDisposedException>(
         () => AsyncHelper.RunSync(() => store.SetPhoneNumberConfirmedAsync(null, true)));
     Assert.Throws<ObjectDisposedException>(
         () => AsyncHelper.RunSync(() => store.GetPhoneNumberConfirmedAsync(null)));
 }
Example #2
0
        public async void AddToRoleAsync_GivenAUserAndRole_AddsTheUserToTheRole()
        {
            var applicationDatabaseConfiguration = new ApplicationDatabaseConfiguration();
            var userStore = new UserStore<User>(applicationDatabaseConfiguration);

            var user = new User
            {
                Email = "*****@*****.**",
                IsEmailConfirmed = true,
                PasswordHash = "PasswordHash",
                PhoneNumber = "PhoneNumber",
                IsPhoneNumberConfirmed = true,
                IsTwoFactorEnabled = false,
                LockoutEndDateUtc = null,
                IsLockoutEnabled = true,
                AccessFailedCount = 0,
                UserName = "******",
                IsAccountActive = true
            };

            await userStore.CreateAsync(user);

            await userStore.AddToRoleAsync(user, "Admin");

            var roles = await userStore.GetRolesAsync(user);

            roles.Should().HaveCount(1);
            roles[0].Should().Be("Admin");
        }
        public void GivenHaveRoles_WhenDeleteUser_ThenDeletingCausesNoCascade()
        {
            var user      = new IdentityUser("Lukz 04");
            var role      = new IdentityRole("ADM");
            var store     = new UserStore <IdentityUser>(_session);
            var roleStore = new RoleStore <IdentityRole>(_session);

            roleStore.CreateAsync(role);
            store.CreateAsync(user);
            store.AddToRoleAsync(user, "ADM");

            Assert.IsTrue(_session.Query <IdentityRole>().Any(x => x.Name == "ADM"));
            Assert.IsTrue(_session.Query <IdentityUser>().Any(x => x.UserName == "Lukz 04"));

            var result = store.DeleteAsync(user);

            Assert.IsNull(result.Exception);
            Assert.IsFalse(this._session.Query <IdentityUser>().Any(x => x.UserName == "Lukz 04"));
            Assert.IsTrue(this._session.Query <IdentityRole>().Any(x => x.Name == "ADM"));
        }
Example #4
0
        public Task SeedSuperUser()
        {
            var roleStore = new RoleStore <IdentityRole>(_context);
            var userStore = new UserStore <ApplicationUser>(_context);

            var user = new ApplicationUser
            {
                UserName           = "******",
                NormalizedUserName = "******",
                Email           = "*****@*****.**",
                NormalizedEmail = "*****@*****.**",
                EmailConfirmed  = true,
                LockoutEnabled  = false,
                SecurityStamp   = Guid.NewGuid().ToString()
            };

            var hasher         = new PasswordHasher <ApplicationUser>();
            var hashedPassword = hasher.HashPassword(user, "admin");

            user.PasswordHash = hashedPassword;

            var hasAdminRole = _context.Roles.Any(roles => roles.Name == "Admin");

            if (!hasAdminRole)
            {
                roleStore.CreateAsync(new IdentityRole {
                    Name           = "Admin",
                    NormalizedName = "admin"
                });
            }
            var hasSuperUser = _context.Users.Any(u => u.NormalizedUserName == user.UserName);

            if (!hasSuperUser)
            {
                userStore.CreateAsync(user);
                userStore.AddToRoleAsync(user, "Admin");
            }

            _context.SaveChangesAsync();
            return(Task.CompletedTask);
        }
Example #5
0
        public void SeedSuperUser()
        {
            var hasher = new PasswordHasher <ApplicationUser>();
            var user   = new ApplicationUser
            {
                UserName           = "******",
                NormalizedUserName = "******",
                Email           = "*****@*****.**",
                NormalizedEmail = "*****@*****.**",
                EmailConfirmed  = true,
                LockoutEnabled  = false,
                SecurityStamp   = Guid.NewGuid().ToString(),
            };

            var hashedPassword = hasher.HashPassword(user, "Test12!");

            user.PasswordHash = hashedPassword;

            var roleStore         = new RoleStore <IdentityRole>(_context);
            var isAdminRoleExists = _context.Roles.Any(r => r.Name == "Admin");

            if (!isAdminRoleExists)
            {
                roleStore.CreateAsync(new IdentityRole
                {
                    Name           = "Admin",
                    NormalizedName = "Admin"
                }).Wait();
            }

            var userStore          = new UserStore <ApplicationUser>(_context);
            var isSuperAdminExists = _context.Users.Any(u => u.UserName == user.UserName);

            if (!isSuperAdminExists)
            {
                userStore.CreateAsync(user).Wait();
                userStore.AddToRoleAsync(user, "Admin").Wait();
            }

            _context.SaveChangesAsync().Wait();
        }
        public void Seed()
        {
            string[] roles = new string[] { "methodist", "teacher", "student" };

            foreach (string role in roles)
            {
                var roleStore = new RoleStore <IdentityRole>(_context);

                if (!_context.Roles.Any(r => r.Name == role))
                {
                    roleStore.CreateAsync(new IdentityRole {
                        Name = role, NormalizedName = role.ToUpper()
                    }).Wait();
                }
            }

            var user = new User
            {
                UserName           = "******",
                NormalizedUserName = "******",
                Email           = "*****@*****.**",
                NormalizedEmail = "*****@*****.**",
                EmailConfirmed  = true,
                SecurityStamp   = Guid.NewGuid().ToString(),
                IsConfirmed     = true
            };

            if (!_context.Users.Any(u => u.UserName == user.UserName))
            {
                var password = new PasswordHasher <User>();
                var hashed   = password.HashPassword(user, "root");
                user.PasswordHash = hashed;

                var userStore = new UserStore <User>(_context);
                var result    = userStore.CreateAsync(user);
                userStore.AddToRoleAsync(user, roles[0]).Wait();
            }

            _context.SaveChangesAsync();
        }
Example #7
0
        public async void Seed()
        {
            string[] roles = new string[] { "Admin", "Staff", "Parent", "Student" };
            //var roleStore = new RoleStore<IdentityRole>(db);
            foreach (string r in roles)
            {
                if (!db.Roles.Any(x => x.Name == r))
                {
                    db.Roles.Add(new IdentityRole {
                        Name = r, NormalizedName = r.ToUpper()
                    });
                }
            }

            if (!db.Users.Any(x => x.UserName == "Admin"))
            {
                var userStore = new UserStore <IdentityUser>(db);
                var hasher    = new PasswordHasher <IdentityUser>();
                var user      = new IdentityUser {
                    UserName = "******", NormalizedUserName = "******"
                };
                user.PasswordHash = hasher.HashPassword(user, "@Open1234");
                await userStore.CreateAsync(user);

                await userStore.AddToRoleAsync(user, "Admin");
            }
            if (!db.Users.Any(x => x.UserName == "esad"))
            {
                var userStore = new UserStore <IdentityUser>(db);
                var hasher    = new PasswordHasher <IdentityUser>();
                var user      = new IdentityUser {
                    UserName = "******", NormalizedUserName = "******"
                };
                user.PasswordHash = hasher.HashPassword(user, "@Open1234");
                await userStore.CreateAsync(user);

                await userStore.AddToRoleAsync(user, "Staff");
            }
            await db.SaveChangesAsync();
        }
        public void WhenRemoveUserFromRole_ThenDoNotDeleteRole_BugFix()
        {
            var user      = new IdentityUser("Lukz 05");
            var role      = new IdentityRole("ADM05");
            var store     = new UserStore <IdentityUser>(_session);
            var roleStore = new RoleStore <IdentityRole>(_session);

            roleStore.CreateAsync(role);
            store.CreateAsync(user);
            store.AddToRoleAsync(user, "ADM05");

            Assert.IsTrue(_session.Query <IdentityRole>().Any(x => x.Name == "ADM05"));
            Assert.IsTrue(_session.Query <IdentityUser>().Any(x => x.UserName == "Lukz 05"));
            Assert.IsTrue(store.IsInRoleAsync(user, "ADM05").Result);

            var result = store.RemoveFromRoleAsync(user, "ADM05");

            Assert.IsNull(result.Exception);
            Assert.IsFalse(store.IsInRoleAsync(user, "ADM05").Result);
            Assert.IsTrue(_session.Query <IdentityUser>().Any(x => x.UserName == "Lukz 05"));
            Assert.IsTrue(_session.Query <IdentityRole>().Any(x => x.Name == "ADM05"));
        }
        void SeedPatient1()
        {
            try
            {
                var patient1 = new AppUser
                {
                    UserName           = "******",
                    Surname            = "Kowalska1",
                    City               = "Świecie",
                    ZipCode            = "86-100",
                    NormalizedUserName = "******",
                    Email              = "*****@*****.**",
                    NormalizedEmail    = "*****@*****.**",
                    EmailConfirmed     = true,
                    LockoutEnabled     = false,
                    SecurityStamp      = Guid.NewGuid().ToString()
                };



                if (!context.Users.Any(u => u.UserName == "Patient1"))
                {
                    var userStore = new UserStore <AppUser>(context);


                    var password = new PasswordHasher <AppUser>();
                    var hashed   = password.HashPassword(patient1, "Sekret123@");
                    patient1.PasswordHash = hashed;

                    userStore.CreateAsync(patient1).Wait();
                    userStore.AddToRoleAsync(patient1, "Pacjent").Wait();
                }

                context.SaveChanges();
            }
            catch (Exception ex)
            {
            }
        }
        public async Task Seed(DatabaseContext context)
        {
            var roles = new List <string>
            {
                "Manager",
                "User"
            };

            var user = new User
            {
                UserName           = "******",
                NormalizedUserName = "******",
                LockoutEnabled     = false,
                SecurityStamp      = Guid.NewGuid().ToString()
            };

            var roleStore = new RoleStore <IdentityRole>(context);

            foreach (var roleName in roles)
            {
                if (!roleStore.Roles.Any(e => e.Name == roleName))
                {
                    await roleStore.CreateAsync(new IdentityRole(roleName) { NormalizedName = roleName.ToUpper() });
                }
            }

            if (!context.Users.Any(u => u.UserName == user.UserName))
            {
                var password = new PasswordHasher <User>();
                var hashed   = password.HashPassword(user, "+");
                user.PasswordHash   = hashed;
                using var userStore = new UserStore <User>(context);
                await userStore.CreateAsync(user);

                await userStore.AddToRoleAsync(user, "Manager");
            }

            await context.SaveChangesAsync();
        }
        public async void SeedAdminUser()
        {
            var user = new ApplicationUser {
                UserName           = "******",
                NormalizedUserName = "******",
                Email           = "*****@*****.**",
                NormalizedEmail = "*****@*****.**",
                FirstName       = "David",
                LastName        = "Buckley",
                EmailConfirmed  = true,
                LockoutEnabled  = false,
                SecurityStamp   = Guid.NewGuid().ToString()
            };

            var roleStore = new RoleStore <IdentityRole>(_context);

            if (!_context.Roles.Any(r => r.Name == "admin" || r.Name == "manager" || r.Name == "agent"))
            {
                await roleStore.CreateAsync(new IdentityRole { Name = "admin", NormalizedName = "admin" });

                await roleStore.CreateAsync(new IdentityRole { Name = "manager", NormalizedName = "manager" });

                await roleStore.CreateAsync(new IdentityRole { Name = "agent", NormalizedName = "agent" });
            }

            if (!_context.Users.Any(u => u.UserName == user.UserName))
            {
                var password = new PasswordHasher <ApplicationUser>();
                var hashed   = password.HashPassword(user, "Test12345!");
                user.PasswordHash = hashed;
                var userStore = new UserStore <ApplicationUser>(_context);
                await userStore.CreateAsync(user);

                userStore.AddToRoleAsync(user, "admin");
            }

            await _context.SaveChangesAsync();
        }
        public async Task SeedAdminUser()
        {
            await _context.Database.MigrateAsync();

            var user = new ApplicationUser
            {
                UserName           = "******",
                NormalizedUserName = "******",
                Email              = "*****@*****.**",
                NormalizedEmail    = "*****@*****.**",
                EmailConfirmed     = true,
                LockoutEnabled     = false,
                SecurityStamp      = Guid.NewGuid().ToString(),
                UserRegisteredDate = DateTime.Now,
                UserFullName       = "Hamid Mosalla",
                UserGender         = "Male"
            };

            var roleStore = new RoleStore <IdentityRole>(_context);

            if (!_context.Roles.Any(r => r.Name == "admin"))
            {
                await roleStore.CreateAsync(new IdentityRole { Name = "admin", NormalizedName = "admin" });
            }

            if (!_context.Users.Any(u => u.UserName == user.UserName))
            {
                var password = new PasswordHasher <ApplicationUser>();
                var hashed   = password.HashPassword(user, "Mc2^6csQ^U88H5pz");
                user.PasswordHash = hashed;
                var userStore = new UserStore <ApplicationUser>(_context);
                await userStore.CreateAsync(user);

                await userStore.AddToRoleAsync(user, "admin");
            }

            await _context.SaveChangesAsync();
        }
Example #13
0
        public async Task Test_RemoveFromRoleAsync()
        {
            // prepare
            using var userStore = new UserStore(Connection);
            using var roleStore = new RoleStore(Connection);
            var role1 = new IdentityRole <long> {
                Name = "name"
            };
            await roleStore.CreateAsync(role1, CancellationToken.None);

            var user = new IdentityUser <long> {
                UserName = "******"
            };
            await userStore.CreateAsync(user, CancellationToken.None);

            await userStore.AddToRoleAsync(user, "name", CancellationToken.None);

            // act
            await userStore.RemoveFromRoleAsync(user, "name", CancellationToken.None);

            // assert
            Assert.False(await userStore.IsInRoleAsync(user, "name", CancellationToken.None));
        }
 public async System.Threading.Tasks.Task <OperationResult <Company> > CreateCompany(Company company)
 {
     return(await System.Threading.Tasks.Task.Factory.StartNew <OperationResult <Company> >(() =>
     {
         OperationResult <Company> result = new OperationResult <Company>();
         try
         {
             company.OwnerId = CurrentUser.Id;
             Company created = CompaniesRepository.CreateOrUpdate(company);
             if (created.Id > 0)
             {
                 UserStore.AddToRoleAsync(CurrentUser, RoleNames.CompanyOwner);
                 result.SingleResult = created;
                 result.Result = true;
             }
         }
         catch (Exception ex)
         {
             LoggingService.Log(ex);
         }
         return result;
     }));
 }
Example #15
0
        public static async void Initialize(ApplicationDbContext context, UserManager <ApplicationUser> userManager)
        {
            context.Database.EnsureCreated();

            //if (context.Users.Any())
            //{
            //    return;
            //}

            var roles = new string[] { "User", "Admin" };

            foreach (var role in roles)
            {
                var roleStore = new RoleStore <IdentityRole>(context);
                await roleStore.CreateAsync(new IdentityRole()
                {
                    Name           = role,
                    NormalizedName = role.ToLower()
                });

                var user = new ApplicationUser
                {
                    UserName           = string.Concat(role, "@smetko.bg").ToLower(),
                    NormalizedUserName = string.Concat(role, "@smetko.bg").ToLower(),
                    Email           = string.Concat(role, "@smetko.bg"),
                    NormalizedEmail = string.Concat(role, "@smetko.bg").ToLower(),
                    EmailConfirmed  = true,
                    LockoutEnabled  = false,
                    SecurityStamp   = Guid.NewGuid().ToString()
                };

                var userStore = new UserStore <ApplicationUser>(context);
                await userStore.AddToRoleAsync(user, role.ToLower());

                await userManager.CreateAsync(user, "parola");
            }
        }
        public async void SeedAdminUser()
        {
            var user = new ApplicationUser
            {
                Title              = "Mr",
                FirstName          = "Muhammad",
                LastName           = "Aamir",
                UserName           = "******",
                NormalizedUserName = "******",
                Email              = "*****@*****.**",
                NormalizedEmail    = "*****@*****.**",
                EmailConfirmed     = true,
                LockoutEnabled     = false,
                SecurityStamp      = Guid.NewGuid().ToString()
            };

            var roleStore = new RoleStore <IdentityRole>(_context);

            if (!_context.Roles.Any(r => r.Name == "Admin"))
            {
                await roleStore.CreateAsync(new IdentityRole { Name = "Admin", NormalizedName = "ADMIN" });
            }

            if (!_context.Users.Any(u => u.UserName == user.UserName))
            {
                var password = new PasswordHasher <ApplicationUser>();
                var hashed   = password.HashPassword(user, "Shararti14321**");
                user.PasswordHash = hashed;
                var userStore = new UserStore <ApplicationUser>(_context);
                await userStore.CreateAsync(user);

                await userStore.AddToRoleAsync(user, "Admin");
            }

            await _context.SaveChangesAsync();
        }
Example #17
0
        private static ApplicationUser CreateUser(IdentityDatabaseContext context, string login, string password,
                                                  string eMail, string role)
        {
            var user = new ApplicationUser
            {
                UserName           = login,
                Email              = eMail,
                NormalizedUserName = login.Normalize(),
                NormalizedEmail    = eMail.Normalize(),
                EmailConfirmed     = false,
                LockoutEnabled     = false,
                SecurityStamp      = Guid.NewGuid().ToString(),
            };
            var passwordHasher = new PasswordHasher <ApplicationUser>();

            user.PasswordHash = passwordHasher.HashPassword(user, password);
            var userStore = new UserStore <ApplicationUser>(context);

            userStore.CreateAsync(user).Wait();
            userStore.AddToRoleAsync(user, role).Wait();

            context.SaveChanges();
            return(user);
        }
Example #18
0
        public async Task SeedUserAsync()
        {
            var userStore = new UserStore <ApplicationUser>(_context);
            var hasher    = new PasswordHasher <ApplicationUser>();

            for (int i = 0; i < 20; i++)
            {
                if (!_context.Users.Any(c => c.UserName == $"User{i}"))
                {
                    var user = new ApplicationUser()
                    {
                        UserName           = $"User{i}",
                        NormalizedUserName = $"User{i}",
                        DisplayName        = $"ユーザー{i}さん"
                    };
                    var hashed = hasher.HashPassword(user, $"userPass{i}");
                    user.PasswordHash = hashed;
                    await userStore.CreateAsync(user);

                    await userStore.AddToRoleAsync(user, "admin");
                }
            }
            await _context.SaveChangesAsync();
        }
Example #19
0
        public static async Task Seed(IdentityServerDbContext dbContext)
        {
            var roleStore = new RoleStore <IdentityRole>(dbContext);
            await roleStore.CreateAsync(new IdentityRole
            {
                Id             = Guid.NewGuid().ToString(),
                Name           = "user",
                NormalizedName = "user"
            });

            await roleStore.CreateAsync(new IdentityRole
            {
                Id             = Guid.NewGuid().ToString(),
                Name           = "admin",
                NormalizedName = "admin"
            });

            var userStore = new UserStore <AppUser>(dbContext);
            var password  = new PasswordHasher <AppUser>();
            var rootUser  = new AppUser
            {
                Id                 = Guid.NewGuid().ToString(),
                UserName           = "******",
                Email              = "*****@*****.**",
                NormalizedEmail    = "*****@*****.**",
                NormalizedUserName = "******",
                SecurityStamp      = Guid.NewGuid().ToString("D"),
                LockoutEnabled     = true,
                ShippingAddress    = new Core.SharedKernel.AddressInfo(Guid.NewGuid(), "123 Address", "HCM", "TB district", "7000", "VN")
            };

            rootUser.PasswordHash = password.HashPassword(rootUser, "root");
            await userStore.CreateAsync(rootUser);

            await userStore.AddToRoleAsync(rootUser, "admin");
        }
Example #20
0
        public async Task ShouldThrow_WritingTo_Database()
        {
            // Deleting the role should fail because of a table lock
            var currentTimeOut = _appDb.DbContext.CommandTimeOut;

            using (var da = (DataAccessAdapter)_appDb.DbContext.GetNewAdapter())
            {
                await da.StartTransactionAsync(IsolationLevel.Serializable, "transaction1");

                da.SaveTransaction("transaction1");
                // lock the table for completely
                await da.ExecuteSQLAsync(CancellationToken.None,
                                         $"SELECT 1 FROM [{_appDb.DbContext.Schema}].[{da.GetPersistentTableName(new IdentityRoleEntity())}] WITH (TABLOCKX)");

                // Trying to update will fail because the table is locked
                _appDb.DbContext.CommandTimeOut = 2;
                Assert.ThrowsAsync <Exception>(async() => await _userStore.RemoveFromRoleAsync(_user, Constants.RoleName.TournamentManager, CancellationToken.None));
                Assert.ThrowsAsync <Exception>(async() => await _userStore.AddToRoleAsync(_user, Constants.RoleName.TournamentManager, CancellationToken.None));
                da.Rollback("transaction1");
            }
            _appDb.DbContext.CommandTimeOut = currentTimeOut;
        }
Example #21
0
        public static void Initialize(ApplicationDbContext db, IServiceProvider serviceProvider)
        {
            var roleStore = new RoleStore <IdentityRole>(db);

            if (!db.Roles.Any(r => r.Name == "Admin"))
            {
                roleStore.CreateAsync(new IdentityRole {
                    Name = "Admin", NormalizedName = "Admin"
                });
            }

            db.SaveChanges();

            if (!db.Roles.Any(r => r.Name == "Member"))
            {
                roleStore.CreateAsync(new IdentityRole {
                    Name = "Member", NormalizedName = "Member"
                });
            }

            db.SaveChanges();

            if (!db.Users.Any(u => u.UserName == "a"))
            {
                var adminProfile = new ApplicationUser
                {
                    UserName           = "******",
                    NormalizedUserName = "******",
                    FirstName          = "Admin",
                    LastName           = "User",
                    Email           = "[email protected]",
                    NormalizedEmail = "[email protected]",
                    EmailConfirmed  = true,
                    LockoutEnabled  = false,
                    SecurityStamp   = Guid.NewGuid().ToString()
                };

                db.Users.Add(adminProfile);

                var password = new PasswordHasher <ApplicationUser>();
                var hashed   = password.HashPassword(adminProfile, "P@ssw0rd");
                adminProfile.PasswordHash = hashed;

                var userStore = new UserStore <ApplicationUser>(db);
                var result    = userStore.CreateAsync(adminProfile);

                userStore.AddToRoleAsync(adminProfile, "Admin");
                userStore.AddToRoleAsync(adminProfile, "Member");

                db.SaveChanges();
            }

            if (!db.Users.Any(u => u.UserName == "m"))
            {
                var memberProfile = new ApplicationUser
                {
                    UserName           = "******",
                    NormalizedUserName = "******",
                    FirstName          = "Member",
                    LastName           = "User",
                    Email           = "[email protected]",
                    NormalizedEmail = "[email protected]",
                    EmailConfirmed  = true,
                    LockoutEnabled  = false,
                    SecurityStamp   = Guid.NewGuid().ToString()
                };

                db.Users.Add(memberProfile);

                var password = new PasswordHasher <ApplicationUser>();
                var hashed   = password.HashPassword(memberProfile, "P@ssw0rd");
                memberProfile.PasswordHash = hashed;

                var userStore = new UserStore <ApplicationUser>(db);
                var result    = userStore.CreateAsync(memberProfile);

                userStore.AddToRoleAsync(memberProfile, "Member");

                db.SaveChanges();
            }

            if (!db.Activities.Any())
            {
                db.Activities.Add
                    (new Activity()
                {
                    Description  = "Senior's Golf Tournament",
                    CreationDate = DateTime.Now
                });

                db.Activities.Add(new Activity()
                {
                    Description  = "Leadership General Assembly Meeting",
                    CreationDate = DateTime.Now
                });

                db.Activities.Add(new Activity()
                {
                    Description  = "Youth Bowling Tournament",
                    CreationDate = DateTime.Now
                });

                db.Activities.Add(new Activity()
                {
                    Description  = "Young ladies cooking lessons",
                    CreationDate = DateTime.Now
                });

                db.Activities.Add(new Activity()
                {
                    Description  = "Youth craft lessons",
                    CreationDate = DateTime.Now
                });
                db.Activities.Add(new Activity()
                {
                    Description  = "Youth choir practice",
                    CreationDate = DateTime.Now
                });
                db.Activities.Add(new Activity()
                {
                    Description  = "Lunch",
                    CreationDate = DateTime.Now
                });
                db.Activities.Add(new Activity()
                {
                    Description  = "Pancake Breakfast",
                    CreationDate = DateTime.Now
                });
                db.Activities.Add(new Activity()
                {
                    Description  = "Swimming Lessons for the youth",
                    CreationDate = DateTime.Now
                });
                db.Activities.Add(new Activity()
                {
                    Description  = "Swimming Exercise for parents",
                    CreationDate = DateTime.Now
                });
                db.Activities.Add(new Activity()
                {
                    Description  = "Bingo Tournament",
                    CreationDate = DateTime.Now
                });
                db.Activities.Add(new Activity()
                {
                    Description  = "BBQ Lunch",
                    CreationDate = DateTime.Now
                });
                db.Activities.Add(new Activity()
                {
                    Description  = "Garage Sale",
                    CreationDate = DateTime.Now
                });

                db.SaveChanges();
            }
            ;


            if (!db.Events.Any())
            {
                db.Events.Add(new Event
                {
                    EventStart   = new DateTime(2017, 4, 4, 8, 30, 0),
                    EventEnd     = new DateTime(2017, 4, 4, 10, 30, 0),
                    Username     = "******",
                    CreationDate = DateTime.Now,
                    IsActive     = true,
                    ActivityId   = db.Activities.FirstOrDefault(f => f.Description == "Senior's Golf Tournament").ActivityId
                });
                db.Events.Add(new Event
                {
                    EventStart   = new DateTime(2017, 4, 5, 8, 30, 0),
                    EventEnd     = new DateTime(2017, 4, 5, 10, 30, 0),
                    Username     = "******",
                    CreationDate = DateTime.Now,
                    IsActive     = true,
                    ActivityId   = db.Activities.FirstOrDefault(f => f.Description == "Leadership General Assembly Meeting").ActivityId
                });
                db.Events.Add(new Event
                {
                    EventStart   = new DateTime(2017, 4, 7, 17, 30, 0),
                    EventEnd     = new DateTime(2017, 4, 7, 19, 15, 0),
                    Username     = "******",
                    CreationDate = DateTime.Now,
                    IsActive     = true,
                    ActivityId   = db.Activities.FirstOrDefault(f => f.Description == "Youth Bowling Tournament").ActivityId
                });
                db.Events.Add(new Event
                {
                    EventStart   = new DateTime(2017, 4, 7, 19, 00, 0),
                    EventEnd     = new DateTime(2017, 4, 7, 20, 00, 0),
                    Username     = "******",
                    CreationDate = DateTime.Now,
                    IsActive     = true,
                    ActivityId   = db.Activities.FirstOrDefault(f => f.Description == "Young ladies cooking lessons").ActivityId
                });
                db.Events.Add(new Event
                {
                    EventStart   = new DateTime(2017, 4, 8, 8, 30, 0),
                    EventEnd     = new DateTime(2017, 4, 8, 10, 30, 0),
                    Username     = "******",
                    CreationDate = DateTime.Now,
                    IsActive     = true,
                    ActivityId   = db.Activities.FirstOrDefault(f => f.Description == "Youth craft lessons").ActivityId
                });
            }
            ;

            db.SaveChanges();
        }
Example #22
0
        public async void SeedAdminUser()
        {
            var user = new IdentityUser
            {
                UserName           = "******",
                NormalizedUserName = "******",
                Email           = "*****@*****.**",
                NormalizedEmail = "*****@*****.**",
                EmailConfirmed  = true,
                LockoutEnabled  = false,
                SecurityStamp   = Guid.NewGuid().ToString()
            };

            var roleStore = new RoleStore <IdentityRole>(_context);

            if (!_context.Roles.Any(r => r.Name == "admin"))
            {
                await roleStore.CreateAsync(new IdentityRole { Name = "admin", NormalizedName = "admin" });
            }

            if (!_context.Users.Any(u => u.UserName == user.UserName))
            {
                var password = new PasswordHasher <IdentityUser>();
                var hashed   = password.HashPassword(user, "hola");
                user.PasswordHash = hashed;
                var userStore2 = new UserStore <IdentityUser>(_context);
                await userStore2.CreateAsync(user);

                await userStore2.AddToRoleAsync(user, "admin");
            }

            await _context.SaveChangesAsync();


            var userStore = new UserStore <IdentityUser>(_context);
            var password2 = new PasswordHasher <IdentityUser>();
            var hashed2   = password2.HashPassword(user, "hola");

            IdentityUser user0, user1;

            if (_context.Users.Any(u => u.UserName == "*****@*****.**"))
            {
                user0 = _context.Users.First(u => u.UserName == "*****@*****.**");
            }
            else
            {
                user0 = new IdentityUser {
                    UserName = "******", Email = "*****@*****.**", PasswordHash = hashed2
                };
                var result = userStore.CreateAsync(user0).Result;
            }
            if (_context.Users.Any(u => u.UserName == "*****@*****.**"))
            {
                user1 = _context.Users.First(u => u.UserName == "*****@*****.**");
            }
            else
            {
                user1 = new IdentityUser {
                    UserName = "******", Email = "*****@*****.**", PasswordHash = hashed2
                };
                var result = userStore.CreateAsync(user1).Result;
            }
        }
Example #23
0
        public async void IsInRoleAsync_GivenAUserAndARole_ReturnsTrueIfUserIsInRole()
        {
            var applicationDatabaseConfiguration = new ApplicationDatabaseConfiguration();
            var userStore = new UserStore<User>(applicationDatabaseConfiguration);

            var user = new User
            {
                Email = "*****@*****.**",
                IsEmailConfirmed = true,
                PasswordHash = "PasswordHash",
                PhoneNumber = "PhoneNumber",
                IsPhoneNumberConfirmed = true,
                IsTwoFactorEnabled = false,
                LockoutEndDateUtc = null,
                IsLockoutEnabled = true,
                AccessFailedCount = 0,
                UserName = "******",
                IsAccountActive = true
            };

            await userStore.CreateAsync(user);

            await userStore.AddToRoleAsync(user, "User");

            var isInRole  = await userStore.IsInRoleAsync(user, "User");

            isInRole.Should().BeTrue();
        }
Example #24
0
        private static void CreateUsers(ApplicationDbContext context)
        {
            var hasher = new PasswordHasher <ApplicationUser>();
            var store  = new UserStore <ApplicationUser>(context);

            if (!context.Users.Any())
            {
                ApplicationUser[] users =
                {
                    new ApplicationUser
                    {
                        Id                 = "1a",
                        FName              = "Stephen",
                        LName              = "King",
                        Email              = "*****@*****.**",
                        NormalizedEmail    = "*****@*****.**",
                        UserName           = "******",
                        NormalizedUserName = "******",
                        SecurityStamp      = Guid.NewGuid().ToString()
                    },
                    new ApplicationUser
                    {
                        Id                 = "2b",
                        FName              = "Jason",
                        LName              = "Voorhees",
                        Email              = "*****@*****.**",
                        NormalizedEmail    = "*****@*****.**",
                        UserName           = "******",
                        NormalizedUserName = "******",
                        SecurityStamp      = Guid.NewGuid().ToString()
                    },
                    new ApplicationUser
                    {
                        Id                 = "3c",
                        FName              = "Mike",
                        LName              = "Myers",
                        Email              = "*****@*****.**",
                        NormalizedEmail    = "*****@*****.**",
                        UserName           = "******",
                        NormalizedUserName = "******",
                        SecurityStamp      = Guid.NewGuid().ToString()
                    },
                    new ApplicationUser
                    {
                        Id                 = "4d",
                        FName              = "Freddy",
                        LName              = "Krueger",
                        Email              = "*****@*****.**",
                        NormalizedEmail    = "*****@*****.**",
                        UserName           = "******",
                        NormalizedUserName = "******",
                        SecurityStamp      = Guid.NewGuid().ToString()
                    },
                    new ApplicationUser
                    {
                        Id                 = "5e",
                        FName              = "Bubba",
                        LName              = "Sawyer",
                        Email              = "*****@*****.**",
                        NormalizedEmail    = "*****@*****.**",
                        UserName           = "******",
                        NormalizedUserName = "******",
                        SecurityStamp      = Guid.NewGuid().ToString()
                    }
                };

                context.Users.AddRange(users);

                foreach (var user in users)
                {
                    user.PasswordHash = hasher.HashPassword(user, "qwerty123!");
                }

                store.AddToRoleAsync(users[0], "ADMIN");
                store.AddToRoleAsync(users[1], "MANAGER");
                store.AddToRoleAsync(users[2], "WORKER");
                store.AddToRoleAsync(users[3], "WORKER");
                store.AddToRoleAsync(users[4], "MANAGER");
            }
        }
Example #25
0
        public async void Seed()
        {
            var admin = new ApplicationUser
            {
                UserName           = "******",
                NormalizedUserName = "******",
                Email           = "*****@*****.**",
                NormalizedEmail = "*****@*****.**",
                EmailConfirmed  = true,
                LockoutEnabled  = false,
                SecurityStamp   = Guid.NewGuid().ToString()
            };

            var roleStore = new RoleStore <IdentityRole>(_appContext);

            if (!_appContext.Roles.Any(r => r.Name == "admin"))
            {
                await roleStore.CreateAsync(new IdentityRole { Name = "admin", NormalizedName = "admin" });
            }

            if (!_appContext.Users.Any(u => u.UserName == admin.UserName))
            {
                var password = new PasswordHasher <ApplicationUser>();
                var hashed   = password.HashPassword(admin, "admin15");
                admin.PasswordHash = hashed;
                var userStore = new UserStore <ApplicationUser>(_appContext);
                await userStore.CreateAsync(admin);

                await userStore.AddToRoleAsync(admin, "admin");

                var realUser = new User
                {
                    UserId   = admin.Id,
                    FullName = "Administrator",
                    Username = "******",
                    Email    = admin.Email
                };

                _yoctoContext.Users.Add(realUser);
            }

            if (!_yoctoContext.DeviceTypes.Any())
            {
                var types = new List <DeviceType>
                {
                    new DeviceType
                    {
                        Id          = Guid.NewGuid().ToString(),
                        Name        = "RPi3",
                        Description = "Raspberry Pi 3"
                    }
                };
                _yoctoContext.DeviceTypes.AddRange(types);
            }

            if (!_yoctoContext.ReadingTypes.Any())
            {
                var types = new List <ReadingType>
                {
                    new ReadingType
                    {
                        Id          = Guid.NewGuid().ToString(),
                        Name        = "Temperature OneWire",
                        Description = "Temperature sensor reading using OneWire protocol."
                    }
                };
                _yoctoContext.ReadingTypes.AddRange(types);
            }

            await _appContext.SaveChangesAsync();

            await _yoctoContext.SaveChangesAsync();
        }
Example #26
0
        public async Task<ActionResult> addRole(string userID, string roleID)
        {
            ajaxReturnData data = new ajaxReturnData();

            try
            {
                using (ApplicationDbContext DB = new ApplicationDbContext())
                {
                    ApplicationUser user = new ApplicationUser();

                    var store = new UserStore<ApplicationUser>(DB);
                    UserManager<ApplicationUser> um = new UserManager<ApplicationUser>(store);
                    user = um.FindById(userID);
                    var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(DB));
                    IdentityRole role = RoleManager.FindById(roleID);
                    await store.AddToRoleAsync(user, role.Name);
                    await store.UpdateAsync(user);

                    data.statusCode = (int)statusCodes.successRun;
                    data.message = "Role '" + role.Name + "' added to user '" + user.UserName + "'";

                }

            }
            catch(Exception ex)
            {

                data.statusCode = (int)statusCodes.fail;
                data.message = "Failed to add role to user; Error is: "+ ex.Message;
            }
            

            
            return Json(data);
        }
        public async Task AddToRoleAsync([FromBody] User user, string role, [FromServices] WebStoreContext db)
        {
            await _UserStore.AddToRoleAsync(user, role);

            await db.SaveChangesAsync();    //сохранение изменений в БД - здесь не через UserStore.UpdateAsync ! (т.к. видимо затрагивает не только пользователя, но и другие таблицы в БД)
        }
Example #28
0
 public Task AddToRoleAsync(IUser user, string roleName)
 {
     return(_userStore.AddToRoleAsync((MongoApplicationUser)user, roleName));
 }
        public void GetAllRoles()
        {
            var user1 = new IdentityUser("Lukz 04");
            var user2 = new IdentityUser("Moa 01");
            var user3 = new IdentityUser("Win 02");
            var user4 = new IdentityUser("Andre 03");
            var role = new IdentityRole("ADM");
            var role2 = new IdentityRole("USR");
            var store = new UserStore<IdentityUser>(this._session);
            var roleStore = new RoleStore<IdentityRole>(this._session);

            roleStore.CreateAsync(role);
            roleStore.CreateAsync(role2);
            store.CreateAsync(user1);
            store.CreateAsync(user2);
            store.CreateAsync(user3);
            store.CreateAsync(user4);
            store.AddToRoleAsync(user1, "ADM");
            store.AddToRoleAsync(user2, "ADM");
            store.AddToRoleAsync(user3, "ADM");
            store.AddToRoleAsync(user4, "ADM");
            store.AddToRoleAsync(user1, "USR");
            store.AddToRoleAsync(user4, "USR");

            Assert.IsTrue(this._session.Query<IdentityRole>().Any(x => x.Name == "ADM"));
            Assert.IsTrue(this._session.Query<IdentityUser>().Any(x => x.UserName == "Lukz 04"));

            Assert.IsTrue(this._session.Query<IdentityUser>().Any(x => x.UserName == "Andre 03"));

            var resul = roleStore.Roles;

            Assert.AreEqual(2, resul.Count());
        }
        public ActionResult UpdateUser(string Id, string UserName, string RoleName, string roleId)
        {
            try
            {
                var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(dbEntity));
                using (var store = new UserStore<ApplicationUser>(new ApplicationDbContext()))
                {
                    var userReloaded = store.Users.Where(u => u.Id == Id).FirstOrDefault();
                    userReloaded.Roles.Clear();
                    var result = store.AddToRoleAsync(userReloaded, RoleName);
                    var result2 = store.UpdateAsync(userReloaded);
                    if (result.IsCompleted && result2.IsCompleted)
                    {
                        store.Context.SaveChanges();
                    }
                }

                var userVm = new
                {
                    Id = Id,
                    UserName = UserName,
                    RoleName = RoleName
                };

                return Json(new { Result = "OK", Data = userVm, Message = "Cambios Guardados." });

            }
            catch (Exception e)
            {
                return Json(new { Result = "ERROR", Message = e.Message });
            }
        }
        public void WhenRemoveUserFromRole_ThenDoNotDeleteRole_BugFix()
        {
            var user = new IdentityUser("Lukz 05");
            var role = new IdentityRole("ADM05");
            var store = new UserStore<IdentityUser>(_session);
            var roleStore = new RoleStore<IdentityRole>(_session);

            roleStore.CreateAsync(role);
            store.CreateAsync(user);
            store.AddToRoleAsync(user, "ADM05");

            Assert.IsTrue(_session.Query<IdentityRole>().Any(x => x.Name == "ADM05"));
            Assert.IsTrue(_session.Query<IdentityUser>().Any(x => x.UserName == "Lukz 05"));
            Assert.IsTrue(store.IsInRoleAsync(user, "ADM05").Result);

            var result = store.RemoveFromRoleAsync(user, "ADM05");

            Assert.IsNull(result.Exception);
            Assert.IsFalse(store.IsInRoleAsync(user, "ADM05").Result);
            Assert.IsTrue(_session.Query<IdentityUser>().Any(x => x.UserName == "Lukz 05"));
            Assert.IsTrue(_session.Query<IdentityRole>().Any(x => x.Name == "ADM05"));
        }
Example #32
0
 public Task AddToRoleAsync(IUser user, string roleName, CancellationToken cancellationToken)
 {
     return(innerStore.AddToRoleAsync((WrappedIdentityUser)user, roleName, cancellationToken));
 }
Example #33
0
        public static async Task SeedData(this IApplicationBuilder builder)
        {
            var provider     = builder.ApplicationServices;
            var scopeFactory = provider.GetRequiredService <IServiceScopeFactory>();

            using (var scope = scopeFactory.CreateScope())
                using (var dbContext = scope.ServiceProvider.GetService <ApplicationDbContext>())
                {
                    var user = new ApplicationUser
                    {
                        UserName           = "******",
                        NormalizedUserName = "******",
                        Email           = "*****@*****.**",
                        NormalizedEmail = "*****@*****.**",
                        EmailConfirmed  = true,
                        LockoutEnabled  = false,
                        SecurityStamp   = Guid.NewGuid().ToString()
                    };
                    var adminUser = new ApplicationUser
                    {
                        UserName           = "******",
                        NormalizedUserName = "******",
                        Email           = "*****@*****.**",
                        NormalizedEmail = "*****@*****.**",
                        EmailConfirmed  = true,
                        LockoutEnabled  = false,
                        SecurityStamp   = Guid.NewGuid().ToString()
                    };
                    var roleStore = new RoleStore <IdentityRole>(dbContext);

                    if (!dbContext.Roles.Any(r => r.Name == "admin"))
                    {
                        await roleStore.CreateAsync(new IdentityRole { Name = "admin", NormalizedName = "admin" });
                    }

                    if (!dbContext.Roles.Any(r => r.Name == "user"))
                    {
                        await roleStore.CreateAsync(new IdentityRole { Name = "user", NormalizedName = "user" });
                    }

                    if (!dbContext.Users.Any(u => u.UserName == user.UserName))
                    {
                        var password = new PasswordHasher <ApplicationUser>();
                        var hashed   = password.HashPassword(user, "password");
                        user.PasswordHash = hashed;
                        var userStore = new UserStore <ApplicationUser>(dbContext);
                        await userStore.CreateAsync(user);

                        await userStore.AddToRoleAsync(user, "user");
                    }

                    if (!dbContext.Users.Any(u => u.UserName == adminUser.UserName))
                    {
                        var password = new PasswordHasher <ApplicationUser>();
                        var hashed   = password.HashPassword(adminUser, "password");
                        adminUser.PasswordHash = hashed;
                        var userStore = new UserStore <ApplicationUser>(dbContext);
                        await userStore.CreateAsync(adminUser);

                        await userStore.AddToRoleAsync(adminUser, "admin");
                    }

                    await dbContext.SaveChangesAsync();
                }
        }
Example #34
0
 private static async Task AddRole(ApplicationUser user, string role, ApplicationDbContext dbContext)
 {
     var userStore = new UserStore <ApplicationUser, ApplicationRole, ApplicationDbContext, int>(dbContext);
     await userStore.AddToRoleAsync(user, role);
 }
 public async Task AddToRoleAsync([FromBody] User user, string roleName)
 {
     await _userStore.AddToRoleAsync(user, roleName);
 }
        public void GivenHaveRoles_WhenDeleteUser_ThenDeletingCausesNoCascade()
        {
            var user = new IdentityUser("Lukz 04");
            var role = new IdentityRole("ADM");
            var store = new UserStore<IdentityUser>(_session);
            var roleStore = new RoleStore<IdentityRole>(_session);

            roleStore.CreateAsync(role);
            store.CreateAsync(user);
            store.AddToRoleAsync(user, "ADM");

            Assert.IsTrue(_session.Query<IdentityRole>().Any(x => x.Name == "ADM"));
            Assert.IsTrue(_session.Query<IdentityUser>().Any(x => x.UserName == "Lukz 04"));

            var result = store.DeleteAsync(user);

            Assert.IsNull(result.Exception);
            Assert.IsFalse(this._session.Query<IdentityUser>().Any(x => x.UserName == "Lukz 04"));
            Assert.IsTrue(this._session.Query<IdentityRole>().Any(x => x.Name == "ADM"));
        }
        public async Task UserStorePublicNullCheckTest()
        {
            Assert.Throws <ArgumentNullException>("factory",
                                                  () => new UserStore <IdentityUser>(null));
            var store = new UserStore <IdentityUser>(CreateTestContext());
            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.GetUserIdAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.GetUserNameAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.SetUserNameAsync(null, null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.CreateAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.UpdateAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.DeleteAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.AddClaimsAsync(null, null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.ReplaceClaimAsync(null, null, null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.RemoveClaimsAsync(null, null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.GetClaimsAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.GetLoginsAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.GetRolesAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.AddLoginAsync(null, null));

            await
            Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.RemoveLoginAsync(null, null, null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.AddToRoleAsync(null, null));

            await
            Assert.ThrowsAsync <ArgumentNullException>("user",
                                                       async() => await store.RemoveFromRoleAsync(null, null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.IsInRoleAsync(null, null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.GetPasswordHashAsync(null));

            await
            Assert.ThrowsAsync <ArgumentNullException>("user",
                                                       async() => await store.SetPasswordHashAsync(null, null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.GetSecurityStampAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user",
                                                             async() => await store.SetSecurityStampAsync(null, null));

            await Assert.ThrowsAsync <ArgumentNullException>("login",
                                                             async() => await store.AddLoginAsync(new IdentityUser("fake"), null));

            await Assert.ThrowsAsync <ArgumentNullException>("claims",
                                                             async() => await store.AddClaimsAsync(new IdentityUser("fake"), null));

            await Assert.ThrowsAsync <ArgumentNullException>("claims",
                                                             async() => await store.RemoveClaimsAsync(new IdentityUser("fake"), null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.GetEmailConfirmedAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user",
                                                             async() => await store.SetEmailConfirmedAsync(null, true));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.GetEmailAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.SetEmailAsync(null, null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.GetPhoneNumberAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.SetPhoneNumberAsync(null, null));

            await Assert.ThrowsAsync <ArgumentNullException>("user",
                                                             async() => await store.GetPhoneNumberConfirmedAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user",
                                                             async() => await store.SetPhoneNumberConfirmedAsync(null, true));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.GetTwoFactorEnabledAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user",
                                                             async() => await store.SetTwoFactorEnabledAsync(null, true));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.GetAccessFailedCountAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.GetLockoutEnabledAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.SetLockoutEnabledAsync(null, false));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.GetLockoutEndDateAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user",
                                                             async() => await store.SetLockoutEndDateAsync(null, new DateTimeOffset()));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.ResetAccessFailedCountAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user",
                                                             async() => await store.IncrementAccessFailedCountAsync(null));

            await Assert.ThrowsAsync <ArgumentException>("normalizedRoleName",
                                                         async() => await store.AddToRoleAsync(new IdentityUser("fake"), null));

            await Assert.ThrowsAsync <ArgumentException>("normalizedRoleName",
                                                         async() => await store.RemoveFromRoleAsync(new IdentityUser("fake"), null));

            await Assert.ThrowsAsync <ArgumentException>("normalizedRoleName",
                                                         async() => await store.IsInRoleAsync(new IdentityUser("fake"), null));

            await Assert.ThrowsAsync <ArgumentException>("normalizedRoleName",
                                                         async() => await store.AddToRoleAsync(new IdentityUser("fake"), ""));

            await Assert.ThrowsAsync <ArgumentException>("normalizedRoleName",
                                                         async() => await store.RemoveFromRoleAsync(new IdentityUser("fake"), ""));

            await Assert.ThrowsAsync <ArgumentException>("normalizedRoleName",
                                                         async() => await store.IsInRoleAsync(new IdentityUser("fake"), ""));
        }
Example #38
0
        public async Task AddToRoleAsync([FromBody] User user, string role, [FromServices] WebStoreDB db)
        {
            await _UserStore.AddToRoleAsync(user, role);

            await db.SaveChangesAsync();
        }
Example #39
0
 public void UserStorePublicNullCheckTest()
 {
     var store = new UserStore<IdentityUser>();
     ExceptionHelper.ThrowsArgumentNull(() => AsyncHelper.RunSync(() => store.CreateAsync(null)), "user");
     ExceptionHelper.ThrowsArgumentNull(() => AsyncHelper.RunSync(() => store.UpdateAsync(null)), "user");
     ExceptionHelper.ThrowsArgumentNull(() => AsyncHelper.RunSync(() => store.DeleteAsync(null)), "user");
     ExceptionHelper.ThrowsArgumentNull(() => AsyncHelper.RunSync(() => store.AddClaimAsync(null, null)), "user");
     ExceptionHelper.ThrowsArgumentNull(() => AsyncHelper.RunSync(() => store.RemoveClaimAsync(null, null)),
         "user");
     ExceptionHelper.ThrowsArgumentNull(() => AsyncHelper.RunSync(() => store.GetClaimsAsync(null)), "user");
     ExceptionHelper.ThrowsArgumentNull(() => AsyncHelper.RunSync(() => store.GetLoginsAsync(null)), "user");
     ExceptionHelper.ThrowsArgumentNull(() => AsyncHelper.RunSync(() => store.GetRolesAsync(null)), "user");
     ExceptionHelper.ThrowsArgumentNull(() => AsyncHelper.RunSync(() => store.AddLoginAsync(null, null)), "user");
     ExceptionHelper.ThrowsArgumentNull(() => AsyncHelper.RunSync(() => store.RemoveLoginAsync(null, null)),
         "user");
     ExceptionHelper.ThrowsArgumentNull(() => AsyncHelper.RunSync(() => store.AddToRoleAsync(null, null)), "user");
     ExceptionHelper.ThrowsArgumentNull(() => AsyncHelper.RunSync(() => store.RemoveFromRoleAsync(null, null)),
         "user");
     ExceptionHelper.ThrowsArgumentNull(() => AsyncHelper.RunSync(() => store.IsInRoleAsync(null, null)), "user");
     ExceptionHelper.ThrowsArgumentNull(() => AsyncHelper.RunSync(() => store.GetPasswordHashAsync(null)), "user");
     ExceptionHelper.ThrowsArgumentNull(() => AsyncHelper.RunSync(() => store.SetPasswordHashAsync(null, null)),
         "user");
     ExceptionHelper.ThrowsArgumentNull(() => AsyncHelper.RunSync(() => store.GetSecurityStampAsync(null)),
         "user");
     ExceptionHelper.ThrowsArgumentNull(
         () => AsyncHelper.RunSync(() => store.SetSecurityStampAsync(null, null)), "user");
     ExceptionHelper.ThrowsArgumentNull(
         () => AsyncHelper.RunSync(() => store.AddClaimAsync(new IdentityUser("fake"), null)), "claim");
     ExceptionHelper.ThrowsArgumentNull(
         () => AsyncHelper.RunSync(() => store.RemoveClaimAsync(new IdentityUser("fake"), null)), "claim");
     ExceptionHelper.ThrowsArgumentNull(
         () => AsyncHelper.RunSync(() => store.AddLoginAsync(new IdentityUser("fake"), null)), "login");
     ExceptionHelper.ThrowsArgumentNull(
         () => AsyncHelper.RunSync(() => store.RemoveLoginAsync(new IdentityUser("fake"), null)), "login");
     ExceptionHelper.ThrowsArgumentNull(() => AsyncHelper.RunSync(() => store.FindAsync(null)), "login");
     ExceptionHelper.ThrowsArgumentNull(() => AsyncHelper.RunSync(() => store.GetEmailConfirmedAsync(null)),
         "user");
     ExceptionHelper.ThrowsArgumentNull(
         () => AsyncHelper.RunSync(() => store.SetEmailConfirmedAsync(null, true)), "user");
     ExceptionHelper.ThrowsArgumentNull(() => AsyncHelper.RunSync(() => store.GetEmailAsync(null)), "user");
     ExceptionHelper.ThrowsArgumentNull(() => AsyncHelper.RunSync(() => store.SetEmailAsync(null, null)), "user");
     ExceptionHelper.ThrowsArgumentNull(() => AsyncHelper.RunSync(() => store.GetPhoneNumberAsync(null)), "user");
     ExceptionHelper.ThrowsArgumentNull(() => AsyncHelper.RunSync(() => store.SetPhoneNumberAsync(null, null)),
         "user");
     ExceptionHelper.ThrowsArgumentNull(
         () => AsyncHelper.RunSync(() => store.GetPhoneNumberConfirmedAsync(null)), "user");
     ExceptionHelper.ThrowsArgumentNull(
         () => AsyncHelper.RunSync(() => store.SetPhoneNumberConfirmedAsync(null, true)), "user");
     ExceptionHelper.ThrowsArgumentNull(() => AsyncHelper.RunSync(() => store.GetTwoFactorEnabledAsync(null)),
         "user");
     ExceptionHelper.ThrowsArgumentNull(
         () => AsyncHelper.RunSync(() => store.SetTwoFactorEnabledAsync(null, true)), "user");
     ExceptionHelper.ThrowsArgumentNullOrEmpty(
         () => AsyncHelper.RunSync(() => store.AddToRoleAsync(new IdentityUser("fake"), null)), "roleName");
     ExceptionHelper.ThrowsArgumentNullOrEmpty(
         () => AsyncHelper.RunSync(() => store.RemoveFromRoleAsync(new IdentityUser("fake"), null)), "roleName");
     ExceptionHelper.ThrowsArgumentNullOrEmpty(
         () => AsyncHelper.RunSync(() => store.IsInRoleAsync(new IdentityUser("fake"), null)), "roleName");
 }