コード例 #1
0
        private async void CreateRolesandUsers()
        {
            ApplicationDbContext context   = new ApplicationDbContext(new DbContextOptions <ApplicationDbContext>());
            var            serviceProvider = new DefaultServiceProviderFactory().CreateServiceProvider(new ServiceCollection());
            var            roleManager     = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context), new List <RoleValidator <IdentityRole> >(), new UpperInvariantLookupNormalizer(), new IdentityErrorDescriber(), new Logger <RoleManager <IdentityRole> >(new LoggerFactory()));
            var            UserManager     = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context), Options.Create <IdentityOptions>(new IdentityOptions()), new PasswordHasher <ApplicationUser>(Options.Create <PasswordHasherOptions>(new PasswordHasherOptions())), new List <UserValidator <ApplicationUser> >(), new List <PasswordValidator <ApplicationUser> >(), new UpperInvariantLookupNormalizer(), new IdentityErrorDescriber(), serviceProvider, new Logger <UserManager <ApplicationUser> >(new LoggerFactory()));
            IdentityResult result;

            if (await UserManager.FindByNameAsync("*****@*****.**") is ApplicationUser user)
            {
                result = await UserManager.AddToRoleAsync(user, "Admin");
            }
            // In Startup iam creating first Admin Role and creating a default Admin User
            if (!await roleManager.RoleExistsAsync("Admin"))
            {
                // first we create Admin rool
                var role = new Microsoft.AspNetCore.Identity.IdentityRole("admin")
                {
                    Name = "Admin"
                };
                await roleManager.CreateAsync(role);

                //Here we create a Admin super user who will maintain the website

                //var user = new ApplicationUser();
                //user.UserName = "******";
                //user.Email = "*****@*****.**";

                //string userPWD = "Peevee1998!";

                //var chkUser = await UserManager.CreateAsync(user, userPWD);

                ////Add default User to Role Admin
                //if (chkUser.Succeeded)
                //{
                //    var result1 = UserManager.AddToRoleAsync(user, "Admin");

                //}
            }

            // creating Creating Manager role
            if (!await roleManager.RoleExistsAsync("User"))
            {
                var role = new Microsoft.AspNetCore.Identity.IdentityRole("User")
                {
                    Name = "User"
                };
                await roleManager.CreateAsync(role);
            }

            // creating Creating Employee role
            if (!await roleManager.RoleExistsAsync("Employee"))
            {
                var role = new Microsoft.AspNetCore.Identity.IdentityRole
                {
                    Name = "Employee"
                };
                await roleManager.CreateAsync(role);
            }
        }
        public async Task Seed()
        {
            try
            {
                //create role
                string id        = "2";
                var    result_ex = await roleManager.FindByIdAsync(id);

                if (result_ex == null)
                {
                    var role = new Microsoft.AspNetCore.Identity.IdentityRole();
                    role.Id             = id;
                    role.Name           = "FieldOfficer";
                    role.NormalizedName = "FIELDOFFICER";
                    var result = await roleManager.CreateAsync(role);
                }

                //create user
                UserDetails user       = null;
                var         result_ex2 = await userManager.FindByEmailAsync("*****@*****.**");

                if (result_ex2 == null)
                {
                    user = new UserDetails()
                    {
                        UserName    = "******",
                        Email       = "*****@*****.**",
                        PhoneNumber = "0771234552",
                        Role        = "FieldOfficer",
                        RoleId      = id
                    };
                    var result2 = await userManager.CreateAsync(user, "Fofficer@123");

                    if (result2.Succeeded)
                    {
                        var role2      = roleManager.FindByIdAsync(id);
                        var roleResult = await userManager.AddToRoleAsync(user, role2.Result.Name);
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }
コード例 #3
0
        public async Task <Microsoft.AspNetCore.Identity.IdentityUser> RemoveUserFromRoleAsync(Microsoft.AspNetCore.Identity.IdentityUser user, string roleName)
        {
            Microsoft.AspNetCore.Identity.IdentityRole role = await GetRoleByNameAsync(roleName);

            IdentityUserRole identityUserRole = await GetIdentityUserRoleAsync(user as Mobsites.AspNetCore.Identity.Cosmos.IdentityUser, role as Mobsites.AspNetCore.Identity.Cosmos.IdentityRole);

            await DeleteIdentityUserRoleAsync(identityUserRole);

            List <string> roles = (user as Mobsites.AspNetCore.Identity.Cosmos.IdentityUser).FlattenRoleNames.Split(',').Where(r => !string.IsNullOrEmpty(r) && r != role.Name).ToList();

            (user as Mobsites.AspNetCore.Identity.Cosmos.IdentityUser).FlattenRoleNames = string.Join(',', roles);

            List <string> roleIds = (user as Mobsites.AspNetCore.Identity.Cosmos.IdentityUser).FlattenRoleIds.Split(',').Where(r => !string.IsNullOrEmpty(r) && r != role.Id).ToList();

            (user as Mobsites.AspNetCore.Identity.Cosmos.IdentityUser).FlattenRoleIds = string.Join(',', roleIds);

            user = await UpdateUserAsync(user);

            return(user);
        }
コード例 #4
0
        private async Task <Microsoft.AspNetCore.Identity.IdentityRole> GetRoleByNameAsync(string roleName)
        {
            var setIterator = containerUsers.GetItemLinqQueryable <Mobsites.AspNetCore.Identity.Cosmos.IdentityRole>().Where(r => r.PartitionKey == "IdentityRole" && r.NormalizedName == roleName.ToUpper()).Take(1).ToFeedIterator();

            Microsoft.AspNetCore.Identity.IdentityRole output = null;

            while (setIterator.HasMoreResults)
            {
                foreach (var role in await setIterator.ReadNextAsync())
                {
                    output = role;
                }
            }

            if (output == null)
            {
                throw new Exception($"No role with name: {roleName}");
            }

            return(output);
        }
コード例 #5
0
        public void Seed(IConfiguration configuration)
        {
            this.Database.EnsureDeleted();
            this.Database.EnsureCreated();

            var adminRole = new Microsoft.AspNetCore.Identity.IdentityRole("Administrator")
            {
                NormalizedName = "Administrator".ToUpper(), ConcurrencyStamp = Guid.NewGuid().ToString()
            };

            Roles.Add(adminRole);

            var admins = new List <ApplicationUser>();

            var hasher   = new ExploitablePasswordHasher <ApplicationUser>();
            var appAdmin = new ApplicationUser()
            {
                UserName           = "******",
                Email              = "*****@*****.**",
                NormalizedUserName = "******".ToUpper(),
                NormalizedEmail    = "*****@*****.**".ToUpper(),
                SecurityStamp      = Guid.NewGuid().ToString(),
                ConcurrencyStamp   = Guid.NewGuid().ToString(),
                LockoutEnabled     = false,
                ProfileImagePath   = "wwwroot/images/businessman_512.png",
                PasswordHash       = hasher.HashPassword(null, "Password1!") //Yeah, I know...Weak on purpose...
            };

            Users.Add(appAdmin);

            var userData = File.ReadAllLines("Users.bak").Where(x => x.Split(',').Count() == 2);
            var r        = new Random(100);

            foreach (var u in userData)
            {
                var x    = u.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                var user = new ApplicationUser()
                {
                    UserName           = x[0],
                    Email              = x[0],
                    PhoneNumber        = $"1.{r.Next().ToString()[0]}{r.Next().ToString()[0]}{r.Next().ToString()[0]}.{r.Next().ToString()[0]}{r.Next().ToString()[0]}{r.Next().ToString()[0]}.{r.Next().ToString()[0]}{r.Next().ToString()[0]}{r.Next().ToString()[0]}{r.Next().ToString()[0]}",
                    NormalizedUserName = x[0].ToUpper(),
                    NormalizedEmail    = x[0].ToUpper(),
                    SecurityStamp      = Guid.NewGuid().ToString(),
                    ConcurrencyStamp   = Guid.NewGuid().ToString(),
                    LockoutEnabled     = true,
                    SSN          = $"{r.Next().ToString()[0]}{r.Next().ToString()[0]}{r.Next().ToString()[0]}-{r.Next().ToString()[0]}{r.Next().ToString()[0]}-{r.Next().ToString()[0]}{r.Next().ToString()[0]}{r.Next().ToString()[0]}{r.Next().ToString()[0]}",
                    PasswordHash = hasher.HashPassword(null, x[1])
                };
                Users.Add(user);
                if (r.NextDouble() >= .95)
                {
                    admins.Add(user);                       //only 5% get to be admin
                }
            }

            SaveChanges();

            UserRoles.Add(new IdentityUserRole <string>()
            {
                RoleId = adminRole.Id, UserId = appAdmin.Id
            });

            foreach (var u in admins)
            {
                UserRoles.Add(new IdentityUserRole <string>()
                {
                    RoleId = adminRole.Id, UserId = u.Id
                });
            }

            SaveChanges();

            var   mgr            = new Managers.BankingAccountManager(configuration);
            float runningBalance = 100000000;
            var   masterAccount  = mgr.CreateAccount(appAdmin, runningBalance);

            var rnd = new Random();
            var max = runningBalance / Users.Count();

            Users.Where(x => x.Id != appAdmin.Id).AsNoTracking().ToList().ForEach(x =>
            {
                var act         = mgr.CreateAccount(x, 0);
                var seedVal     = (float)rnd.NextDouble() * max;
                runningBalance -= seedVal;
                var t           = mgr.CreateTransaction(masterAccount, act, seedVal, $"Banking Account Seeding with {seedVal.ToString("0.00")}", DateTime.Now);
                mgr.CompleteTransaction(t);
            });
        }
コード例 #6
0
        // In this method we will create default User roles and Admin user for login
        public async Task GenerateUserAccounts()
        {
            var userManager = new UserStore <ApplicationUser>(db);
            var roleManager = new RoleStore <IdentityRole>(db);

            // Create Admin Role and Admin User
            if (!roleManager.Roles.Where(a => a.Name == "Admin").Any())
            {
                // first we create Admin role
                var role = new Microsoft.AspNetCore.Identity.IdentityRole();
                role.Name           = "Admin";
                role.NormalizedName = role.Name.ToUpper();
                await roleManager.CreateAsync(role);
            }

            // creating Member role
            if (!roleManager.Roles.Where(a => a.Name == "Manager").Any())
            {
                var role = new Microsoft.AspNetCore.Identity.IdentityRole();
                role.Name           = "Manager";
                role.NormalizedName = role.Name.ToUpper();
                await roleManager.CreateAsync(role);
            }

            // create Member role
            if (!roleManager.Roles.Where(a => a.Name == "Member").Any())
            {
                var role = new Microsoft.AspNetCore.Identity.IdentityRole();
                role.Name           = "Member";
                role.NormalizedName = role.Name.ToUpper();
                await roleManager.CreateAsync(role);
            }


            // create Admin user
            if (!userManager.Users.Where(a => a.UserName == appConfiguration.AdminEmail).Any())
            {
                try
                {
                    // Create a Admin super user who will maintain the website
                    var user = new ApplicationUser();
                    user.UserName           = appConfiguration.AdminEmail;
                    user.Email              = appConfiguration.AdminEmail;
                    user.NormalizedEmail    = appConfiguration.AdminEmail.ToUpper();
                    user.NormalizedUserName = appConfiguration.AdminEmail.ToUpper();
                    user.SecurityStamp      = Guid.NewGuid().ToString("D");
                    var password = new PasswordHasher <ApplicationUser>();
                    var hashed   = password.HashPassword(user, appConfiguration.AdminPwd);
                    user.PasswordHash = hashed;
                    var chkUser = await userManager.CreateAsync(user);

                    //Add default User to Role Admin
                    if (chkUser.Succeeded)
                    {
                        var adminRole = roleManager.FindByNameAsync("Admin");
                        var adminUser = userManager.FindByEmailAsync(appConfiguration.AdminEmail);
                        if (adminRole != null && adminUser != null)
                        {
                            db.UserRoles.Add(new IdentityUserRole <string>()
                            {
                                RoleId = adminRole.Result.Id.ToString(),
                                UserId = adminUser.Result.Id.ToString()
                            });
                            await db.SaveChangesAsync();
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.Write("Error " + ex.Message.ToString());
                }
            }
        }
コード例 #7
0
        public bool Seed(IConfiguration configuration, int seedUserCount = 1000)
        {
            try
            {
                Console.WriteLine("Ensure DB Deleted");
                this.Database.EnsureDeleted();

                Console.WriteLine("Ensure DB Created");
                this.Database.EnsureCreated();

                Console.WriteLine("Creating Admin");

                var adminRole = new Microsoft.AspNetCore.Identity.IdentityRole("Administrator")
                {
                    NormalizedName = "Administrator".ToUpper(), ConcurrencyStamp = Guid.NewGuid().ToString()
                };
                Roles.Add(adminRole);

                var admins = new List <ApplicationUser>();

                var hasher   = new ExploitablePasswordHasher <ApplicationUser>();
                var appAdmin = new ApplicationUser()
                {
                    UserName           = "******",
                    Email              = "*****@*****.**",
                    NormalizedUserName = "******".ToUpper(),
                    NormalizedEmail    = "*****@*****.**".ToUpper(),
                    SecurityStamp      = Guid.NewGuid().ToString(),
                    ConcurrencyStamp   = Guid.NewGuid().ToString(),
                    LockoutEnabled     = false,
                    ProfileImagePath   = "wwwroot/images/businessman_512.png",
                    PasswordHash       = hasher.HashPassword(null, $"Password{DateTime.Now.Day}{DateTime.Now.Year}!") //Yeah, I know...Weak on purpose...
                };

                Users.Add(appAdmin);

                Console.WriteLine("Creating Users");

                var userData = File.ReadAllLines("Users.bak").Where(x => x.Split(',').Count() == 2).OrderBy(x => Guid.NewGuid()).Take(seedUserCount);
                var r        = new Random(100);
                foreach (var u in userData)
                {
                    var x    = u.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                    var user = new ApplicationUser()
                    {
                        UserName           = x[0],
                        Email              = x[0],
                        PhoneNumber        = $"1.{r.Next().ToString()[0]}{r.Next().ToString()[0]}{r.Next().ToString()[0]}.{r.Next().ToString()[0]}{r.Next().ToString()[0]}{r.Next().ToString()[0]}.{r.Next().ToString()[0]}{r.Next().ToString()[0]}{r.Next().ToString()[0]}{r.Next().ToString()[0]}",
                        NormalizedUserName = x[0].ToUpper(),
                        NormalizedEmail    = x[0].ToUpper(),
                        SecurityStamp      = Guid.NewGuid().ToString(),
                        ConcurrencyStamp   = Guid.NewGuid().ToString(),
                        LockoutEnabled     = true,
                        SSN          = $"{r.Next().ToString()[0]}{r.Next().ToString()[0]}{r.Next().ToString()[0]}-{r.Next().ToString()[0]}{r.Next().ToString()[0]}-{r.Next().ToString()[0]}{r.Next().ToString()[0]}{r.Next().ToString()[0]}{r.Next().ToString()[0]}",
                        PasswordHash = hasher.HashPassword(null, x[1])
                    };
                    Console.WriteLine($"Creating {user.UserName}");
                    Users.Add(user);
                    if (r.NextDouble() >= .99)
                    {
                        admins.Add(user);                        //only 1% get to be admin
                    }
                }

                SaveChanges();

                Console.WriteLine($"Selecting Admin");

                UserRoles.Add(new IdentityUserRole <string>()
                {
                    RoleId = adminRole.Id, UserId = appAdmin.Id
                });

                foreach (var u in admins)
                {
                    UserRoles.Add(new IdentityUserRole <string>()
                    {
                        RoleId = adminRole.Id, UserId = u.Id
                    });
                }

                SaveChanges();

                //Guac Access
                if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("POSTGRES_HOSTNAME")) &&
                    !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("POSTGRES_DATABASE")) &&
                    !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("POSTGRES_PASSWORD")) &&
                    !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("POSTGRES_USER")) &&
                    GuacamoleDB.TestConnection().Result)
                {
                    Console.WriteLine($"Adding Guacamole Admin Users");
                    var tasks = new List <Task>();
                    foreach (var user in admins)
                    {
                        tasks.Add(GuacamoleDB.CreateUserEntry(user.UserName));
                    }

                    tasks.Add(GuacamoleDB.CreateSshConnections());

                    Task.WaitAll(tasks.ToArray());
                }
                else
                {
                    Console.WriteLine($"Skipping Guacamole Admin Step");
                }

                //Console Dump Admins
                foreach (var user in admins)
                {
                    Console.WriteLine($"Admin: {user}");
                }

                Console.WriteLine($"Randomly Distributing Funds");

                var   mgr            = new Managers.BankingAccountManager(configuration);
                float runningBalance = 100000000;
                var   masterAccount  = mgr.CreateAccount(appAdmin, runningBalance);

                var rnd = new Random();
                var max = runningBalance / Users.Count();

                var users = Users.Where(x => x.Id != appAdmin.Id).AsNoTracking().ToList();

                //Account Seeding
                var accounts = users.Select(x =>
                {
                    var act         = mgr.CreateAccount(x, 0);
                    var seedVal     = (float)rnd.NextDouble() * max;
                    runningBalance -= seedVal;
                    var t           = mgr.CreateTransaction(masterAccount, act, seedVal, $"Banking Account Seeding with {seedVal.ToString("0.00")}", DateTime.Now, true);
                    mgr.CompleteTransaction(t);
                    return(new { act, seedVal });
                }).ToList();

                //Account Transfers
                accounts.ForEach(x =>
                {
                    accounts.OrderBy(y => Guid.NewGuid()).Take((int)Math.Ceiling(rnd.NextDouble() * 5)).ToList().ForEach(y =>
                    {
                        var xfr = x.seedVal * .1f;
                        var t   = mgr.CreateTransaction(x.act, y.act, xfr, $"Random Transfer with {xfr.ToString("0.00")}", DateTime.Now, true);
                        mgr.CompleteTransaction(t);
                    });
                });

                Console.WriteLine($"Completed Fund Transfers");

                return(true);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return(false);
            }
            finally
            {
            }
        }