public IActionResult CreateRole(Role role)
 {
     if (ModelState.IsValid)
     {
         var newRole = new ManageRoles();
         if(!newRole.CheckIfRoleExist(role))
         {
             if (newRole.AddRole(role))
             {
                 return RedirectToAction("ListRoles", "Administration");
             }
             else
             {
                 ModelState.AddModelError("All", "Add role attempt unsuscessfull, please try again or refer to the error log");
                 return View();
             }
         }
         else
         {
             ModelState.AddModelError("All","Role already exists, please enter a new role.");
             return View();
         }
     }
     return View();
 }
        public List <UserViewModel> GetSortedUsers(string role)
        {
            //Instance of the ManageRoles class to get the user's role
            ManageRoles man = new ManageRoles();
            //List of view models to return
            List <UserViewModel> viewModel = new List <UserViewModel>();
            //A list of all the users in the database
            List <ApplicationUser> users = _db.Users.ToList();

            //Get all the users from the list with the right role and adding them to te view model
            foreach (var tmp in users)
            {
                if (man.UserIsInRole(tmp.Id, role))
                {
                    viewModel.Add(new UserViewModel()
                    {
                        Id       = tmp.Id,
                        FullName = tmp.FullName,
                        SSN      = tmp.SSN,
                        Email    = tmp.Email,
                        UserRole = man.GetUserRole(tmp.Email)
                    });
                }
                ;
            }
            //Return the view model
            return(viewModel);
        }
Esempio n. 3
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            /// <summary>
            /// Creates the user roles when the application starts
            /// if they don't exist already
            /// </summary>
            ManageRoles manager = new ManageRoles();

            if (!manager.RoleExists("Administrator"))
            {
                manager.CreateRole("Administrator");
            }
            if (!manager.RoleExists("Student"))
            {
                manager.CreateRole("Student");
            }
            if (!manager.RoleExists("Teacher"))
            {
                manager.CreateRole("Teacher");
            }
        }
        public UserViewModel GetUserBySSN(string userSSN)
        {
            //Instance of the ManageRoles class to get the user's role
            ManageRoles man = new ManageRoles();
            //Get the right user from the database
            var user = _db.Users.Where(x => x.SSN == userSSN).FirstOrDefault();

            //if the user exists add him to a view model and return it, otherwise throw exception
            if (user != null)
            {
                var viewModel = new UserViewModel
                {
                    FullName = user.FullName,
                    SSN      = user.SSN,
                    Email    = user.Email,
                    UserRole = man.GetUserRole(user.Email)
                };

                return(viewModel);
            }
            else
            {
                throw new ArgumentNullException();
            }
        }
        public ActionResult DeleteUser(RegisterViewModel model)
        {
            if (ManageRoles.IsUserInRole(model.Email, App_Role.Users))
            {
                ManageRoles.RemoveUserFromRole(model.Email, App_Role.Users);
            }
            if (ManageRoles.IsUserInRole(model.Email, App_Role.SuperUsers))
            {
                ManageRoles.RemoveUserFromRole(model.Email, App_Role.SuperUsers);
            }

            ApplicationUser user = UserManager.FindByEmail(model.Email);
            IdentityResult  ir   = UserManager.Delete(user);

            TempData["DeletedUser"] = model.Email;
            if (ir.Succeeded)
            {
                TempData["DeletedText"] = " has been deleted.";
            }
            else
            {
                TempData["DeletedText"] = " could not be deleted.";
            }
            return(RedirectToAction("UserDeleted", "Security"));
        }
Esempio n. 6
0
 public ActionResult ManageRoles(ManageRoles model)
 {
     if (db.Users.Any(x => x.Id == model.Email))
     {
         var user    = db.Users.Find(model.Email);
         var result1 = UserManager.AddToRole(user.Id, "Admin");
     }
     return(RedirectToAction("Index", "Home", null));
 }
Esempio n. 7
0
 protected override void Dispose(bool disposing)
 {
     if (disposing)
     {
         roles = null;
         GC.Collect();
         GC.SuppressFinalize(this);
     }
     base.Dispose(disposing);
 }
        public IActionResult Register()
        {
            var roles = new ManageRoles().GetRoles();

            if (roles.Count > 0)
            {
                ViewBag.Roles = roles;
            }
            return(View());
        }
 public IActionResult EditRole(Role role)
 {
     var editRole = new ManageRoles();
     if(editRole.EditRoleById(role))
     {
         return RedirectToAction("ListRoles", "Administration");
     }
     else
     {
         ModelState.AddModelError("All", "Edit role unsusccesful");
         return View();
     }
 }
 public IActionResult EditRole(int id)
 {
     var finder = new ManageRoles();
     var roleToEdit = finder.GetRoleById(id);
     
     if (roleToEdit == null)
     {
         ViewBag.ErrorMessage = $"Role with Id = {id} cannot be found";
         return View("Error");
     }
     ViewBag.UsersInRole = finder.GetUsersInRole(id);
     return View(roleToEdit);
 }
Esempio n. 11
0
        private void manageRolesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (Form form in Application.OpenForms)
            {
                if (form.GetType() == typeof(ManageRoles))
                {
                    form.Activate();
                    return;
                }
            }
            ManageRoles rols = new ManageRoles();

            rols.MdiParent = this;
            rols.Show();
            rols.WindowState = FormWindowState.Normal;
        }
        public IActionResult EditUserInRole(int id)
        {

            var finder = new ManageRoles();
            var role = finder.GetRoleById(id);
            if (role == null)
            {
                ViewBag.ErrorMessage = $"Role with Id = {id} cannot be found";
                return View("Error");
            }
            ViewBag.Role = role;

            var users = new UserManager().GetUsersByRole(role);

            return View(users);
        }
        public void EditUserBySSN(UserViewModel user)
        {
            //Instance of the ManageRoles class to get the user's role
            ManageRoles man = new ManageRoles();
            //Find the right user
            var model = _db.Users.Where(x => x.SSN == user.SSN).FirstOrDefault();

            //If the user dosn't exist throw an exception otherwise change the user information
            if (model == null)
            {
                //TODO: kasta villu
                throw new ArgumentNullException();
            }
            else
            {
                model.FullName = user.FullName;
                model.SSN      = user.SSN;
                model.Email    = user.Email;

                if (man.GetUserRole(model.Email) != null)
                {
                    man.ClearUserRoles(model.Id);
                }
                man.AddUserToRole(model.Id, user.UserRole);
            }
            try
            {
                _db.SaveChanges();
            }
            catch (DbEntityValidationException ex)
            {
                foreach (var error in ex.EntityValidationErrors)
                {
                    Console.WriteLine("====================");
                    Console.WriteLine("Entity {0} in state {1} has validation errors:",
                                      error.Entry.Entity.GetType().Name, error.Entry.State);
                    foreach (var ve in error.ValidationErrors)
                    {
                        Console.WriteLine("\tProperty: {0}, Error: {1}",
                                          ve.PropertyName, ve.ErrorMessage);
                    }
                    Console.WriteLine();
                }
                throw;
            }
        }
        public IActionResult EditUserInRole(List<UserRoleModel> model, int id)
        {
            var role = new ManageRoles().GetRoleById(id);
            var result = new ManageRoles();
            
            if (role.RoleName == null)
            {
                ViewBag.ErrorMessage = $"Role with Id = {id} cannot be found";
                return View("Error");
            }

            for (int i = 0; i < model.Count; i++)
            {
                var user = new UserManager().GetUserById(model[i].UserId);

                if (!string.IsNullOrEmpty(user.Role))
                {
                    if (model[i].IsSelected && (user.Role != role.RoleName))
                    {
                        result.RemoveUserFromRole(user);
                        result.AddUserToRole(user, role);
                        continue;

                    }
                    else if (!model[i].IsSelected && (user.Role == role.RoleName))
                    {
                        result.RemoveUserFromRole(user);
                        continue;
                    }
                    else
                    {
                        continue;
                    }
                }

                else
                {
                    result.AddUserToRole(user, role);
                    continue;
                }

            }
            return RedirectToAction("EditRole", new { id = id });
        }
        public async Task <ActionResult> CreateUser(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                ApplicationUser existingUser = UserManager.FindByEmail(model.Email);
                if (existingUser != null)
                {
                    TempData["NewUser"] = model.Email;
                    return(RedirectToAction("UserAlreadyExists", "Security"));
                }

                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };

                // Does email already exist?

                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    ManageRoles.AddUserToRole(model.Email, App_Role.Users);
                    if (model.MakeSuperUser)
                    {
                        ManageRoles.AddUserToRole(model.Email, App_Role.SuperUsers);
                    }
                    // Don't sign them in.
                    //await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
                    TempData["NewUser"] = model.Email;
                    return(RedirectToAction("UserCreated", "Security"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
 public IActionResult ListRoles()
 {
     var roles = new ManageRoles().GetRoles();
     return View(roles);
 }
 public IActionResult Create(ManageRoles obj)
 {
     _db.ManageRoles.Add(obj);
     _db.SaveChanges();
     return(RedirectToAction("Index"));
 }
 public IActionResult Edit(ManageRoles obj)
 {
     _db.ManageRoles.Update(obj);
     _db.SaveChanges();
     return(RedirectToAction("Index"));
 }
Esempio n. 19
0
        public async Task <ActionResult> Register(RegisterViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var UserExist = _service.CheckIfUserExist(model.SSN);
                if (!UserExist)
                {
                    var user = new ApplicationUser {
                        UserName = model.Email, Email = model.Email
                    };
                    user.FullName = model.FullName;
                    user.SSN      = model.SSN;

                    var result = await UserManager.CreateAsync(user, model.Password);

                    if (result.Succeeded)
                    {
                        //await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

                        ManageRoles addTo = new ManageRoles();
                        if (model.Role == "Administrator")
                        {
                            addTo.AddUserToRole(user.Id, "Administrator");
                        }
                        if (model.Role == "Teacher")
                        {
                            addTo.AddUserToRole(user.Id, "Teacher");
                        }
                        if (model.Role == "Student")
                        {
                            addTo.AddUserToRole(user.Id, "Student");
                        }

                        if (model.CourseID.HasValue)
                        {
                            if (model.Role == "Student")
                            {
                                UserService userService = new UserService();
                                userService.AddStudentToCourse(model.CourseID.Value, user.Id);
                            }
                            if (model.Role == "Teacher")
                            {
                                CourseService courseService = new CourseService();
                                var           course        = courseService.GetCourseByID(model.CourseID.Value);
                                course.TeacherID = user.Id;
                                courseService.EditCourseById(course);
                            }
                        }
                        // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                        // Send an email with this link
                        // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                        // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                        // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                        return(RedirectToAction("Index", "User"));
                    }
                    AddErrors(result);
                }
                else
                {
                    return(View("Error"));
                }
            }
            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Esempio n. 20
0
 public HomeController(ManageRoles man) : base(man: man)
 {
 }