Example #1
0
        public static ApplicationUser CreateUser(UserManager<ApplicationUser> userManager, string email, string firstName, string lastName,
           string password, bool lockOutEnabled)
        {
            var user = userManager.FindByName(email);

            if (user == null)
            {
                user = new ApplicationUser
                {
                    UserName = email,
                    Email = email,
                    FirstName = firstName,
                    LastName = lastName,
                    EmailConfirmed = true
                };
                try
                {
                    userManager.Create(user, password);
                }
                catch (Exception ex)
                {
                    Log4NetHelper.Log("Error creating Admin User", LogLevel.ERROR, "AspNetUser", 1, "none", ex);
                }
                userManager.SetLockoutEnabled(user.Id, lockOutEnabled);
            }
            return user;
        }
        public async Task<ActionResult> DisableUser(string userName)
        {

   
            List<string> users;
            List<string> enabledUsers;
            List<string> disabledUsers;
            using (var context = new ApplicationDbContext())
            {

                var userStore = new UserStore<ApplicationUser>(context);
                var userManager = new UserManager<ApplicationUser>(userStore);

                var selectedUser = userManager.FindByName(userName);

                if (selectedUser == null)
                    throw new Exception("User not found!");

                if (!selectedUser.UserName.Equals("[email protected]"))
                {


                    if (!selectedUser.LockoutEnabled)
                    {
                        userManager.SetLockoutEnabled(selectedUser.Id, true);
                        DateTime lockoutDate = DateTime.Now.AddYears(50);
                        await userManager.SetLockoutEndDateAsync(selectedUser.Id, lockoutDate);
                        context.SaveChanges();
                        userManager.Update(selectedUser);
                        ViewBag.ResultMessage = "Disabled successfully !";

                    }
                }
                else
                {
                    ViewBag.ResultMessage = "Cannot disable Admin";
                }

                users = (from u in userManager.Users select u.UserName).ToList();
                disabledUsers = new List<string>(users);
                enabledUsers = new List<string>(users);
                foreach (var user in users)
                {
                    if (!userManager.FindByName(user).LockoutEnabled)
                    {
                        disabledUsers.Remove(user);
                    }
                    else
                    {
                        enabledUsers.Remove(user);
                    }
                }
            }

            ViewBag.EnabledUsers = new SelectList(enabledUsers);
            ViewBag.DisabledUsers = new SelectList(disabledUsers);
            return View();
        }
Example #3
0
        private static void SetupRolesAndUsers(DbContext context)
        {
            var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
            var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
            // add roles
            if (!roleManager.RoleExists(Role.Guest.ToString()))
                roleManager.Create(new IdentityRole(Role.Guest.ToString()));
            if (!roleManager.RoleExists(Role.Supplier.ToString()))
                roleManager.Create(new IdentityRole(Role.Supplier.ToString()));
            if (!roleManager.RoleExists(Role.Deactivated.ToString()))
                roleManager.Create(new IdentityRole(Role.Deactivated.ToString()));
            if (!roleManager.RoleExists(Role.User.ToString()))
                roleManager.Create(new IdentityRole(Role.User.ToString()));
            var adminRole = roleManager.FindByName(Role.Admin.ToString());
            if (adminRole == null)
            {
                adminRole = new IdentityRole(Role.Admin.ToString());
                roleManager.Create(adminRole);
            }
            #if DEBUG
            //add admin user
            var admin = userManager.Find(Admin_User, Admin_Pass);
            if (admin == null)
            {
                admin = new ApplicationUser
                {
                    UserName = Admin_User,
                    Email = Admin_Mail,
                    EmailConfirmed = true
                };
                var result = userManager.Create(admin, Admin_Pass);
                // TODO: verify returned IdentityResult
                userManager.AddToRole(admin.Id, Role.Admin.ToString());
                result = userManager.SetLockoutEnabled(admin.Id, false);
            }

            var rolesForUser = userManager.GetRoles(admin.Id);
            if (!rolesForUser.Contains(adminRole.Name))
            {
                var result = userManager.AddToRole(admin.Id, adminRole.Name);
            }

            //add normal user
            if (userManager.Find("[email protected]", "1q2w3e4r") == null)
            {
                var user = new ApplicationUser
                {
                    UserName = "[email protected]",
                    Email = "[email protected]",
                    EmailConfirmed = true
                };
                userManager.Create(user, "1q2w3e4r");
                // TODO: verify returned IdentityResult
                userManager.AddToRole(user.Id, Role.User.ToString());
            }
            #endif
        }
Example #4
0
        public static void DefaultUser(ApplicationDbContext db)
        {

            var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
            var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db));

            var name = AppConfig.DefaultUser;
            var pwd = AppConfig.DefaultUserPassword;
            const string adminRole = "Admin";
            const string dashboardRole = "Dashboard";
            const string investigateRole = "Investigate";

            //Create Role Admin if it does not exist
            var ar = roleManager.FindByName(adminRole);
            if (ar == null)
            {
                ar = new IdentityRole(adminRole);
                var roleresult = roleManager.Create(ar);
            }

            var dr = roleManager.FindByName(dashboardRole);
            if (dr == null)
            {
                dr = new IdentityRole(dashboardRole);
                var roleresult = roleManager.Create(dr);
            }

            var ir = roleManager.FindByName(investigateRole);
            if (ir == null)
            {
                ir = new IdentityRole(investigateRole);
                var roleresult = roleManager.Create(ir);
            }

            var user = userManager.FindByName(name);
            if (user == null)
            {
                user = new ApplicationUser { UserName = name, Email = name, EmailConfirmed = true };
                var createUser = userManager.Create(user, pwd);
                createUser = userManager.SetLockoutEnabled(user.Id, false);
            }

            // Add user admin to Role Admin if not already added
            var rolesForUser = userManager.GetRoles(user.Id);
            if (!rolesForUser.Contains("Admin"))
            {
                var result = userManager.AddToRole(user.Id, "Admin");
            }
        }
        public static void init(SACAAEContext context)
        {
            var userManager = new UserManager<User>(new UserStore<User>(context));

            const string usernameAdmin = "amasis";
            const string emailAdmin = "[email protected]";
            const string nameAdmin = "Alejandro Masís";
            const string passAdmin = "sacapassword";
            //Admin
            var admin = userManager.FindByName(usernameAdmin);
            if (admin == null)
            {
                admin = new User { UserName = usernameAdmin, Email = emailAdmin, Name = nameAdmin };
                var result = userManager.Create(admin, passAdmin);
                result = userManager.SetLockoutEnabled(admin.Id, false);
            }
        }
Example #6
0
        internal static void DefaultUser(ApplicationDbContext ctx)
        {
            var userManager = new UserManager<User>(new UserStore<User>(ctx));
            var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(ctx));

            var adminUser = AppConfig.DefaultAdminAccount;
            var adminPassword = AppConfig.DefaultAdminAccountPassword;
            const string roleName = "Admin";

            var role = roleManager.FindByName(roleName);
            if (role == null)
            {
                role = new IdentityRole(roleName);
                var createRoleResult = roleManager.Create(role);
            }

            var user = userManager.FindByName(adminUser);
            if (user == null)
            {
                user = new User
                {
                    UserName = adminUser,
                    Email = adminUser,
                    LockoutEnabled = false,
                    EmailConfirmed = true,
                    UserProfile = new UserProfile()
                    {
                        Title = "N/A",
                        Forename = "System",
                        Surname = "Administrator",
                        Alias = "Sysadmin",
                        JobTitle = "Administrator"
                    }
                };
                var createUserResult = userManager.Create(user, adminPassword);
                createUserResult = userManager.SetLockoutEnabled(user.Id, false);
            }

            var rolesForUser = userManager.GetRoles(user.Id);
            if (!rolesForUser.Contains(role.Name))
            {
                var addUserToRoleResult = userManager.AddToRole(user.Id, role.Name);
            }
        }
        public ActionResult Create([Bind(Include = "FirstName,LastName,Email,PhoneNumber,UserName")] ApplicationUser applicationUser)
        {
            if (ModelState.IsValid)
            {
                var userStore = new UserStore<ApplicationUser>(db);
                var userManager = new UserManager<ApplicationUser>(userStore);

                var user = userManager.FindByName(applicationUser.UserName);
                if (user == null)
                {
                    userManager.Create(applicationUser);
                    userManager.SetLockoutEnabled(applicationUser.Id, false);
                    userManager.AddToRoles(applicationUser.Id, Request["Role"]);

                    return RedirectToAction("Index");
                }
            }

            return View(applicationUser);
        }
        public ActionResult EnableUser(string userName)
        {

            List<string> users;
            List<string> enabledUsers;
            List<string> disabledUsers;
            using (var context = new ApplicationDbContext())
            {

                var userStore = new UserStore<ApplicationUser>(context);
                var userManager = new UserManager<ApplicationUser>(userStore);

                var selectedUser = userManager.FindByName(userName);
                if (selectedUser == null)
                    throw new Exception("User not found!");
                if (selectedUser.LockoutEnabled)
                {
                    userManager.SetLockoutEnabled(selectedUser.Id, false);
                    context.SaveChanges();
                    userManager.Update(selectedUser);


                }


                users = (from u in userManager.Users select u.UserName).ToList();
                disabledUsers = new List<string>(users);
                enabledUsers = new List<string>(users);
                foreach (var user in users)
                {
                    if (!userManager.FindByName(user).LockoutEnabled)
                    {
                        disabledUsers.Remove(user);
                    }
                    else
                    {
                        enabledUsers.Remove(user);
                    }
                }
            }
            ViewBag.ResultMessage = "Enabled successfully !";
            ViewBag.EnabledUsers = new SelectList(enabledUsers);
            ViewBag.DisabledUsers = new SelectList(disabledUsers);
            return View("DisableUser");
        }
Example #9
0
        /// <summary>
        ///     Seed the Database with Courses, A default user, and roles
        ///     User and Role Seeding:
        ///     http://stackoverflow.com/questions/29526215/seed-entities-and-users-roles
        /// </summary>
        /// <param name="context">The context.</param>
        public static void Seed(Lab10DbContext context)
        {
            // If No users exist
            if (!context.Users.Any())
            {
                // Wire up Roles services
                var roleStore = new RoleStore<IdentityRole>(context);
                var roleManager = new RoleManager<IdentityRole>(roleStore);

                // Add Roles
                if (roleManager.FindByName(UserRoles.Coordinator) == null)
                    roleManager.Create(new IdentityRole(UserRoles.Coordinator));
                if (roleManager.FindByName(UserRoles.DepartmentChair) == null)
                    roleManager.Create(new IdentityRole(UserRoles.DepartmentChair));
                if (roleManager.FindByName(UserRoles.Instructor) == null)
                    roleManager.Create(new IdentityRole(UserRoles.Instructor));

                // Wire up user services
                var userStore = new UserStore<ApplicationUser>(context);
                var userManager = new UserManager<ApplicationUser>(userStore);

                // Set up the default password
                var password = "[email protected]";
                var hashedPassword = new PasswordHasher().HashPassword(password);

                if (userManager.FindByEmail("[email protected]") == null)
                {
                    var user = AddUser("WeiGong", "[email protected]", hashedPassword);
                    userManager.Create(user, password);
                    userManager.AddToRole(user.Id, UserRoles.Instructor);
                }

                if (userManager.FindByEmail("[email protected]") == null)
                {
                    var user = AddUser("JaneDoe", "[email protected]", hashedPassword);
                    userManager.Create(user, password);
                    userManager.AddToRole(user.Id, UserRoles.Instructor);
                }

                if (userManager.FindByEmail("[email protected]") == null)
                {
                    var user = AddUser("JohnSmith", "[email protected]", hashedPassword);
                    userManager.Create(user, password);
                    userManager.AddToRole(user.Id, UserRoles.Coordinator);
                }

                if (userManager.FindByEmail("[email protected]") == null)
                {
                    var user = AddUser("DavidJones", "[email protected]", hashedPassword);
                    userManager.Create(user, password);
                    userManager.AddToRole(user.Id, UserRoles.Coordinator);
                    userManager.AddToRole(user.Id, UserRoles.Instructor);
                }

                if (userManager.FindByEmail("[email protected]") == null)
                {
                    var user = AddUser("MaryRobinson", "[email protected]", hashedPassword);
                    userManager.Create(user, password);
                    userManager.SetLockoutEnabled(user.Id, false);
                    userManager.AddToRole(user.Id, UserRoles.DepartmentChair);
                }
            }

            // Seed the course Information
            context.Courses.AddOrUpdate(c => c.CourseNumber,
                new Course
                {
                    CourseNumber = "ICT0001",
                    CourseName = "Web Programming",
                    CourseDescription =
                        "Students learn how to manage their laptop environment to gain the best advantage during their college program and later in the workplace. Create backups, install virus protection, manage files through a basic understanding of the Windows Operating System, install and configure the Windows Operating System, install and manage a virtual machine environment. Explore computer architecture including the functional hardware and software components that are needed to run programs. Finally, study basic numerical systems and operations including Boolean logic.",
                    WeeklyHours = 4
                },
                new Course
                {
                    CourseNumber = "ICT0002",
                    CourseName = "Introduction to Computer Programming",
                    CourseDescription =
                        "Learn the fundamental problem-solving methodologies needed in software development, such as structured analysis, structured design, structured programming and introduction to object-oriented programming. Use pseudocode, flowcharting, as well as a programming language to develop solutions to real-world problems of increasing complexity. The basics of robust computer programming, with emphasis on correctness, structure, style and documentation are learned using Java. Theory is reinforced with application by means of practical laboratory assignments.",
                    WeeklyHours = 6
                },
                new Course
                {
                    CourseNumber = "ICT0003",
                    CourseName = "Web Programming I",
                    CourseDescription =
                        "Students learn to develop websites with XHTML, CSS and JavaScript which emphasize structured and modular programming with an object-based paradigm. The course reinforces theory with practical lab assignments to create websites and to explore web-based applications that include client-side script",
                    WeeklyHours = 4
                },
                new Course
                {
                    CourseNumber = "ICT0004",
                    CourseName = "Introduction to Database Systems",
                    CourseDescription =
                        "Students are introduced to the design and development of database systems using a current Database Management System (DBMS). Concepts and terminology of relational databases and design principles using the Entity Relationship model are presented. Students use SQL to create, modify and query a database. - See more at: http://www3.algonquincollege.com/sat/program/internet-applications-web-development/#courses",
                    WeeklyHours = 2
                },
                new Course
                {
                    CourseNumber = "ICT0005",
                    CourseName = "Achieving Success in Changing Environments",
                    CourseDescription =
                        "Rapid changes in technology have created personal and employment choices that challenge each of us to find our place as contributing citizens in the emerging society. Life in the 21st century presents significant opportunities, but it also creates potential hazards and ethical problems that demand responsible solutions. Students explore the possibilities ahead, assess their own aptitudes and strengths, and apply critical thinking and decision-making tools to help resolve some of the important issues in our complex society with its competing interests. - See more at: http://www3.algonquincollege.com/sat/program/internet-applications-web-development/#courses",
                    WeeklyHours = 4
                },
                new Course
                {
                    CourseNumber = "ICT0006",
                    CourseName = "Math Fundamentals",
                    CourseDescription =
                        "Students learn foundational mathematics required in many College technical programs. Students also solve measurement problems involving a variety of units and ratio and proportion problems. They manipulate algebraic expressions and solve equations. Students evaluate exponential and logarithmic expressions, study the trigonometry of right triangles and graph a variety of functions. - See more at: http://www3.algonquincollege.com/sat/program/internet-applications-web-development/#courses",
                    WeeklyHours = 4
                },
                new Course
                {
                    CourseNumber = "ICT0007",
                    CourseName = "Database Systems",
                    CourseDescription =
                        "Students acquire practical experience using Oracle, an object-relational database management system. Advanced topics in database design are covered. Students have hands-on use of SQL, SQL scripts, PL/SQL and embedded SQL in host programs. Database concepts covered include data storage and retrieval, administration data warehouse, data mining, decision support, business intelligence, security and transaction control. Students also explore the use of open source database software. - See more at: http://www3.algonquincollege.com/sat/program/internet-applications-web-development/#courses",
                    WeeklyHours = 6
                },
                new Course
                {
                    CourseNumber = "ICT0008",
                    CourseName = "Web Programming II",
                    CourseDescription =
                        "Through the study of C# and ASP.net, students learn the concepts of object-oriented programming as applied to the design, the development, and the debugging of ASP.net web. Object-oriented concepts, such as encapsulation, inheritance, abstraction and polymorphism are covered and reinforced with practical applications. The course also continues the development of Web Programming concepts by examining and using HTML form elements, HTML server controls and web server controls, the ASP.NET Page class, its inherent Page, Request, Response and Cookies objects. - See more at: http://www3.algonquincollege.com/sat/program/internet-applications-web-development/#courses",
                    WeeklyHours = 3
                },
                new Course
                {
                    CourseNumber = "ICT0009",
                    CourseName = "Network Operating Systems",
                    CourseDescription =
                        "Students are introduced to the concepts behind implementing the Windows server and the Linux operating systems in a multiple user, computer and Internet Protocol (IP) networked environment. Topics include managing and updating user accounts, access rights to files and directories, Transmission Control Protocol/Internet Protocol (TCP/IP) and TCP/IP services: Domain Name System (DNS), Hyper Text Transfer Protocol (HTTP) and File Transfer Protocol (FTP). The course reinforces theory with practical lab assignments to install and configure both operating systems and the services mentioned. - See more at: http://www3.algonquincollege.com/sat/program/internet-applications-web-development/#courses",
                    WeeklyHours = 4
                },
                new Course
                {
                    CourseNumber = "ICT0010",
                    CourseName = "Web Imaging and Animations",
                    CourseDescription =
                        "Students are introduced to basic concepts and techniques used to produce graphics, animations and video optimized for the World Wide Web. Students use Adobe software to create images and animations, build graphical user interfaces and author interactive applications. - See more at: http://www3.algonquincollege.com/sat/program/internet-applications-web-development/#courses",
                    WeeklyHours = 4
                },
                new Course
                {
                    CourseNumber = "ICT0011",
                    CourseName = "Communications I",
                    CourseDescription =
                        "Communication remains an essential skill sought by employers, regardless of discipline or field of study. Using a practical, vocation-oriented approach, students focus on meeting the requirements of effective communication. Through a combination of lectures, exercises, and independent learning, students practise writing, speaking, reading, listening, locating and documenting information, and using technology to communicate professionally. Students develop and strengthen communication skills that contribute to success in both educational and workplace environments. - See more at: http://www3.algonquincollege.com/sat/program/internet-applications-web-development/#courses",
                    WeeklyHours = 2
                },
                new Course
                {
                    CourseNumber = "ICT0012",
                    CourseName = "Web Programming Languages I",
                    CourseDescription =
                        "Emphasis is placed on ways of moving data between web pages and databases using the .NET platform: ASP, ADO, C#, and the .NET Framework. Heavy emphasis is placed on how web applications can interact with databases through ODBC or other technologies. Server-side methods and the advantages of multi-tiered applications are explored. The course concludes with a mini-project to develop a live web application that interacts with a database. - See more at: http://www3.algonquincollege.com/sat/program/internet-applications-web-development/#courses",
                    WeeklyHours = 6
                }
                );
        }