Пример #1
0
        // GET: Admin/Users/Edit/5
        public ActionResult Edit(int?id)
        {
            /* When we edit an User, we desire to show a ListBox with the list of available Roles
             * where the selected are the ones associated to the concerning user.
             * we can change the selection or other data and submit back to the controller to persist the data*/

            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            UserRolesVM userRolesVM = new UserRolesVM
            {
                User = db.Users.Include(u => u.Roles).FirstOrDefault(u => u.UserId == id)
            };

            if (userRolesVM.User == null)
            {
                TempData["Success"] = "Nope";
                return(RedirectToAction("Index"));
            }
            var allUserRolesList = db.Roles.ToList();

            userRolesVM.AllUserRoles = allUserRolesList.Select(o => new SelectListItem
            {
                Text  = o.RoleName,
                Value = o.RoleId.ToString()
            });

            return(View(userRolesVM));
        }
Пример #2
0
        //private static long SqlBulkCopyInsert()
        //{
        //    Stopwatch stopwatch = new Stopwatch();
        //    stopwatch.Start();
        //    DataTable dt = SqlHelper.ExecuteDataset(SqlHelper.GetConnSting(), CommandType.Text, "select  *   from    FROM [RABC].[dbo].[UserRoles] where  ID<0").Tables[0];
        //    string passportKey;
        //    for (int i = 0; i < dt.Columns.Count; i++)
        //    {

        //        DataRow dataRow = dt.NewRow();
        //        dataRow[""] = passportKey;
        //        dataTable.Rows.Add(dataRow);
        //    }
        //    SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(connectionString);
        //    sqlBulkCopy.DestinationTableName = "Passport";
        //    sqlBulkCopy.BatchSize = dataTable.Rows.Count;
        //    SqlConnection sqlConnection = new SqlConnection(connectionString);
        //    sqlConnection.Open();
        //    if (dataTable != null && dataTable.Rows.Count != 0)
        //    {
        //        sqlBulkCopy.WriteToServer(dataTable);
        //    }
        //    sqlBulkCopy.Close(); sqlConnection.Close();
        //    stopwatch.Stop();
        //    return stopwatch.ElapsedMilliseconds;
        //}

        public List <UserRolesVM> GetUserRoles(UserRolesVM vm)
        {
            try
            {
                //  DataPageRequestInfo info = JsonHelper.DeserializeJsonToObject<DataPageRequestInfo>(strData);
                //   StringBuilder where = new StringBuilder("where 1 = 1");
                //   var qm = JsonConvert.DeserializeAnonymousType(info.Conditions, new { Name = "" });
                //List<SqlParameter> parameters = new List<SqlParameter>();
                //if (!string.IsNullOrEmpty(qm.Name))
                //{
                //    SqlParameter param = new SqlParameter("@Name", string.Format("%{0}%", qm.Name));
                //    where.Append(" and Name like @Name");
                //    parameters.Add(param);
                //}
                StringBuilder       selectDataCommand = new StringBuilder(@" 
SELECT  ur.ID ,[UserID] ,[RoleID],r.Name RoleName ,u.Account UserName FROM [RABC].[dbo].[UserRoles] ur 
 join  [dbo].[Users] u  on ur.UserID=u.[ID]
 join  [dbo].[Roles] r  on r.ID=ur.RoleID
");
                List <SqlParameter> paramList         = new List <SqlParameter>();
                if (vm.UserID != 0)
                {
                    selectDataCommand.Append(" where u.ID=@UserID");
                    SqlParameter paramID = new SqlParameter("@UserID", vm.UserID);
                    paramList.Add(paramID);
                }
                //  selectDataCommand.Append(where.ToString());
                return(DataTableToList.DataSetToList <UserRolesVM>(SqlHelper.ExecuteDataset(SqlHelper.GetConnSting(), CommandType.Text, selectDataCommand.ToString(), paramList.ToArray())));
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Пример #3
0
        public List <RolesVM> GetUserNotHaveRoles(UserRolesVM vm)
        {
            try
            {
                //DataPageRequestInfo info = JsonHelper.DeserializeJsonToObject<DataPageRequestInfo>(strData);
                //StringBuilder where = new StringBuilder("where 1 = 1");
                //var qm = JsonConvert.DeserializeAnonymousType(info.Conditions, new { Name = "" });
                //   RolesVM qm = JsonConvert.DeserializeObject<RolesVM>(info.Conditions);
                //  List<SqlParameter> parameters = new List<SqlParameter>();

                StringBuilder selectDataCommand = new StringBuilder(@"  
select  [ID] ,[Name] ,[CreateTime],[Remark] from  [dbo].[Roles] r
where not exists
  (
  select ur.ID from [dbo].[UserRoles] ur  where ur.RoleID=r.ID and ur.UserID=@UserID
  )
");
                SqlParameter  paramUserID       = new SqlParameter("@UserID", vm.UserID);
                return(DataTableToList.DataSetToList <RolesVM>(SqlHelper.ExecuteDataset(SqlHelper.GetConnSting(), CommandType.Text, selectDataCommand.ToString(), paramUserID)));
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Пример #4
0
        public async Task <IActionResult> ManageUserRoles(string userId)
        {
            ViewBag.UserId = userId;
            var user = await userManager.FindByIdAsync(userId);

            if (user != null)
            {
                var model = new List <UserRolesVM>();

                foreach (var role in roleManager.Roles)
                {
                    var userRoles = new UserRolesVM
                    {
                        RoleId   = role.Id,
                        RoleName = role.Name
                    };

                    if (await userManager.IsInRoleAsync(user, role.Name))
                    {
                        userRoles.IsSelected = true;
                    }
                    else
                    {
                        userRoles.IsSelected = false;
                    }

                    model.Add(userRoles);
                }

                return(View(model));
            }

            ViewBag.ErrorMessage = $"User with Id = {userId} cannot be found";
            return(View("NotFound"));
        }
Пример #5
0
        public async Task <IActionResult> OnGetAsync(int?id)
        {
            if (id == null)
            {
                return(RedirectToPage("./Index"));
            }
            var user = await _userManager.FindByIdAsync(id.Value.ToString());

            if (user == null)
            {
                return(NotFound("Nerastas toks vartotojas."));
            }
            UserRole = new UserRolesVM();
            var role = await _roleManager.FindByIdAsync("3");

            UserRole.RoleName = role.Name;
            UserRole.UserName = user.FullName;
            UserRole.UserId   = user.Id;
            UserRole.RoleId   = role.Id;
            if (await _userManager.IsInRoleAsync(user, UserRole.RoleName))
            {
                UserRole.IsSelected = true;
            }
            else
            {
                UserRole.IsSelected = false;
            }

            return(Page());
        }
        public async Task <IActionResult> GetUserRoles(string userId)
        {
            var user = await _userManager.FindByIdAsync(userId);

            if (user == null)
            {
                return(BadRequest("Invalid user id!"));
            }

            List <UserRolesVM> model = new List <UserRolesVM>();

            foreach (var role in _roleManager.Roles)
            {
                UserRolesVM userRolesVM = new UserRolesVM
                {
                    RoleId     = role.Id,
                    RoleName   = role.Name,
                    IsSelected = (await _userManager.IsInRoleAsync(user, role.Name))
                };

                model.Add(userRolesVM);
            }

            return(Ok(model));
        }
Пример #7
0
        public async Task <IActionResult> ManageUserRoles(string userId)
        {
            ViewBag.userId = userId;

            var user = await UserManager.FindByIdAsync(userId);

            if (user == null)
            {
                ViewBag.ErrorMessage = $"User with id = {userId} can not be found";
                return(View("NotFound"));
            }

            var model = new List <UserRolesVM>();

            foreach (var role in RoleManager.Roles)
            {
                var manageUserRolesViewModel = new UserRolesVM
                {
                    RoleId     = role.Id,
                    RoleName   = role.Name,
                    IsSelected = await UserManager.IsInRoleAsync(user, role.Name)
                };

                model.Add(manageUserRolesViewModel);
            }

            return(View(model));
        }
Пример #8
0
        public ActionResult UserRoles()
        {
            UserRolesVM viewModel = new UserRolesVM();

            viewModel.Admins     = _userBL.GetAllUsersInRole("Administrator");
            viewModel.PMs        = _userBL.GetAllUsersInRole("Project Manager");
            viewModel.Devs       = _userBL.GetAllUsersInRole("Developer");
            viewModel.Submitters = _userBL.GetAllUsersInRole("Submitter");
            return(View(viewModel));
        }
Пример #9
0
        public int DeleteUserRoles(UserRolesVM vm)
        {
            StringBuilder sb = new StringBuilder();

            try
            {
                SqlParameter paramID = new SqlParameter("@ID", vm.ID);
                string       sql     = @"DELETE FROM [dbo].[UserRoles] WHERE  ID=@ID ";
                return(SqlHelper.ExecuteNonQuery(SqlHelper.GetConnSting(), CommandType.Text, sql, new SqlParameter[] { paramID }));
            }
            catch (Exception ex)
            {
                return(0);
            }
        }
Пример #10
0
        public async Task <ActionResult> Delete(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Users user = await _unitOfWork.usersRolesRepo.GetAsync((int)id);

            string      roles = RolesToCSV(user);
            UserRolesVM model = new UserRolesVM()
            {
                MyRoles = roles, Username = user.Username
            };

            return(View(model));
        }
Пример #11
0
        public ActionResult Edit(UserRolesVM userRolesVM)
        {
            if (ModelState.IsValid)
            {
                User userToUpdate = db.Users.FirstOrDefault(u => u.UserId == userRolesVM.User.UserId);

                // map the properties we **actually** want to update:
                userToUpdate.UserName      = userRolesVM.User.UserName;
                userToUpdate.UserPassword  = userRolesVM.User.UserPassword;
                userToUpdate.UserEmail     = userRolesVM.User.UserEmail;
                userToUpdate.Birthday      = userRolesVM.User.Birthday;
                userToUpdate.UserLastName  = userRolesVM.User.UserLastName;
                userToUpdate.UserFirstName = userRolesVM.User.UserFirstName;
                userToUpdate.UserAddress   = userRolesVM.User.UserAddress;
                userToUpdate.UserPost      = userRolesVM.User.UserPost;
                userToUpdate.UserGemeente  = userRolesVM.User.UserGemeente;
                userToUpdate.UserName      = userRolesVM.User.UserName;
                userToUpdate.UserPhone     = userRolesVM.User.UserPhone;
                userToUpdate.PasswordHash  = FormsAuthentication.HashPasswordForStoringInConfigFile(userRolesVM.User.UserPassword, "md5");


                var newRoles = db.Roles
                               .Where(r => userRolesVM.SelectedUserRoles.Contains(r.RoleId))
                               .ToList();
                var updatedRoles = new HashSet <int>(userRolesVM.SelectedUserRoles);
                foreach (Role role in db.Roles)
                {
                    if (!updatedRoles.Contains(role.RoleId))
                    {
                        userToUpdate.Roles.Remove(role);
                    }
                    else
                    {
                        userToUpdate.Roles.Add(role);
                    }
                }

                db.Entry(userToUpdate).State = EntityState.Modified;
                db.SaveChanges();
                TempData["Success"] = "De gebruiker werd succesvol gewijzigd";
                return(RedirectToAction("Index"));
            }
            var errors = ModelState.Values.SelectMany(v => v.Errors);

            return(View(userRolesVM));
        }
Пример #12
0
        public async Task <IActionResult> Index()
        {
            var users = await _userManager.Users.ToListAsync();

            var userRolesVM = new List <UserRolesVM>();

            foreach (Profile user in users)
            {
                var thisViewModel = new UserRolesVM();
                thisViewModel.userId   = user.Id;
                thisViewModel.Email    = user.Email;
                thisViewModel.UserName = user.UserName;
                thisViewModel.Roles    = await GetUserRoles(user);

                userRolesVM.Add(thisViewModel);
            }
            return(View(userRolesVM));
        }
Пример #13
0
        private UserRolesVM PopulateUserRolesViewModel(UserSM user, IEnumerable <string> rolesForUser)
        {
            var model = new UserRolesVM();

            model.Id        = user.Id;
            model.UserName  = user.UserName;
            model.Name      = user.FirstName + " " + user.LastName;
            model.Email     = user.Email;
            model.UserRoles = Enum.GetValues(typeof(UserRole)).Cast <UserRole>().Select(x => new CheckBoxListItemVM
            {
                Id          = x.ToString(),
                DisplayName = x.ToString()
            }).ToList();

            model.UserRoles.ForEach(x => x.IsChecked = rolesForUser.Contains(x.Id));

            return(model);
        }
Пример #14
0
        public async Task <IActionResult> Index()
        {
            var users = await _userManager.Users.ToListAsync();

            var userRolesViewModel = new List <UserRolesVM>();

            foreach (Korisnik user in users)
            {
                var thisViewModel = new UserRolesVM();
                thisViewModel.KorisnikID = user.Id;
                thisViewModel.Email      = user.Email;
                thisViewModel.Ime        = user.Ime;
                thisViewModel.Prezime    = user.Prezime;
                thisViewModel.Roles      = await GetUserRoles(user);

                userRolesViewModel.Add(thisViewModel);
            }
            return(View(userRolesViewModel));
        }
Пример #15
0
        public ActionResult AddUserRoles(UserRolesVM userRolesVM)
        {
            //var roleStore = new RoleStore<IdentityRole>(context);
            //var roleMngr = new RoleManager<IdentityRole>(roleStore);
            var role = roleManager.Roles.Where(p => p.Id == userRolesVM.RoleId).FirstOrDefault();

            if (!userManager.IsInRole(userRolesVM.UserId, role.Name))
            {
                //Add role to the user
                userManager.AddToRole(userRolesVM.UserId, role.Name);
            }

            var roles = roleManager.Roles.ToList();

            ViewBag.UserId = new SelectList(applicationUsers, "Id", "UserName");
            ViewBag.RoleId = new SelectList(roles, "Id", "Name");

            return(View());
        }
Пример #16
0
        public async Task <ActionResult> Index()
        {
            List <UserRolesVM> viewModels = new List <UserRolesVM>();
            var users = await _unitOfWork.usersRolesRepo.GetAllUsersAsync();

            foreach (var user in users)
            {
                string      roles = RolesToCSV(user);
                UserRolesVM userRolesViewModel = new UserRolesVM()
                {
                    Id = user.ID, MyRoles = roles, Username = user.Username
                };
                viewModels.Add(userRolesViewModel);
            }
            if (viewModels == null)
            {
                return(HttpNotFound());
            }
            return(View(viewModels));
        }
Пример #17
0
        public ActionResult AssignRole(UserRolesVM uvm)
        {
            string msg = string.Empty;

            if (ModelState.IsValid)
            {
                using (AuthenticationDb db = new AuthenticationDb())
                {
                    var us = db.Users.Include("Roles").FirstOrDefault(x => x.UserId == uvm.UserId);
                    var ro = db.Roles.FirstOrDefault(x => x.RoleId == uvm.RoleId);


                    db.Users.Include("Roles").FirstOrDefault(x => x.UserId == uvm.UserId).Roles.Add(ro);

                    db.SaveChanges();
                    ViewBag.UserList = db.Users.ToList();
                    ViewBag.RoleList = db.Roles.ToList();
                }
            }
            return(View());
        }
Пример #18
0
        public async Task <IActionResult> UpdateRole(UserRolesVM model)
        {
            if (ModelState.IsValid)
            {
                if (User.Claims.FirstOrDefault(x => x.Type == "sub")?.Value == model.Id)
                {
                    StatusMessage = new StatusMessageVM(false, "Cannot update the logged-in user's role");
                    return(RedirectToAction("Index"));
                }

                var addToRoles      = new List <string>();
                var removeFromRoles = new List <string>();
                foreach (var r in model.UserRoles)
                {
                    if (r.IsChecked)
                    {
                        addToRoles.Add(r.Id);
                    }
                    else
                    {
                        removeFromRoles.Add(r.Id);
                    }
                }
                await _accountService.UpdateUserRolesAsync(model.Id, addToRoles, removeFromRoles);

                StatusMessage = new StatusMessageVM(true, "User Roles Updated for " + model.UserName);
                return(RedirectToAction("Index"));
            }

            var user = await _accountService.FindUserByIdAsync(model.Id);

            var rolesForUser = await _accountService.GetRolesForUserAsync(user);

            var m = PopulateUserRolesViewModel(user, rolesForUser);

            return(View("UpdateRole", m));
        }
        public async Task <IActionResult> EditUserRoles(string userId)
        {
            ViewBag.userId = userId;
            AppUser SelectedUser = await userManager.FindByIdAsync(userId);

            if (SelectedUser == null)
            {
                ViewBag.ErrorMsg = $"Resource with id {userId} not found";
                return(View("NotFound"));
            }
            List <UserRolesVM> UserRoleList = new List <UserRolesVM>();

            foreach (var Role in roleManager.Roles)
            {
                var userRoleVM = new UserRolesVM {
                    RoleId = Role.Id, RoleName = Role.Name
                };

                _ = (await userManager.IsInRoleAsync(SelectedUser, Role.Name)) == true ? userRoleVM.IsSelected = true : userRoleVM.IsSelected = false;

                UserRoleList.Add(userRoleVM);
            }
            return(View(UserRoleList));
        }
Пример #20
0
        private void ribeDeleteUserRole_Click(object sender, EventArgs e)
        {
            UserRolesVM userRolesVM = this.gvUserRoles.GetRow(this.gvUserRoles.FocusedRowHandle) as UserRolesVM;//获取选中行的实体

            if (userRolesVM.UserName.ToLower() == "admin" || userRolesVM.RoleName.ToLower() == "admin")
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("can not delete role or user  admin!", "提示", MessageBoxButtons.OK);
                return;
            }


            int resDeleteUserRoles = _bll.DeleteUserRoles(userRolesVM);

            if (resDeleteUserRoles > 0)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("删除成功!", "提示", MessageBoxButtons.OK);
                RequestUserRolesData();
                this.slueUsers.EditValue = null;
            }
            else
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("删除失败!", "提示", MessageBoxButtons.OK);
            }
        }
Пример #21
0
        public IActionResult PostUserRolesAssociation([FromBody] UserRolesVM UserRolesVM)
        {
            if (ModelState.IsValid)
            {
                List <int> ClaimRolesIds = new List <int>();
                foreach (var role in UserRolesVM.Roles)
                {
                    //check roles exist?
                    Roles rolesVM = context.Roles.FirstOrDefault(p => p.Role.ToLower().Equals(role.Role.ToLower()));
                    if (rolesVM == null)
                    {
                        var addRole = context.Roles.Add(new Roles()
                        {
                            Role = role.Role
                        });
                        context.SaveChanges();
                        role.Id = addRole.Entity.Id;
                    }
                    else
                    {
                        role.Id = rolesVM.Id;
                    }

                    foreach (var claim in role.Claims)
                    {
                        //check claims exist?
                        Claims claimsVM = context.Claims.FirstOrDefault(p => p.Claim.ToLower().Equals(claim.Claim.ToLower()));
                        if (claimsVM == null)
                        {
                            var addClaim = context.Claims.Add(new Claims()
                            {
                                Claim = claim.Claim
                            });
                            context.SaveChanges();
                            claim.Id = addClaim.Entity.Id;
                        }
                        else
                        {
                            claim.Id = claimsVM.Id;
                        }

                        //check ClaimRoles exist? If not Add them...
                        ClaimRoles claimRolesVM = context.ClaimRoles.FirstOrDefault(p => p.RolesId == role.Id && p.ClaimsId == claim.Id);
                        if (claimRolesVM == null)
                        {
                            var claimRoles = context.ClaimRoles.Add(new ClaimRoles()
                            {
                                ClaimsId = claim.Id, RolesId = role.Id
                            });
                            context.SaveChanges();
                            ClaimRolesIds.Add(claimRoles.Entity.Id);
                        }
                        else
                        {
                            ClaimRolesIds.Add(claimRolesVM.Id);
                        }
                    }

                    //check UserClaimRoles exist....
                    foreach (var claimRolesId in ClaimRolesIds)
                    {
                        var UserClaimRoles = context.UserClaimRoles.FirstOrDefault(p => p.ClaimRolesId == claimRolesId && p.UserInformationId == new Guid(UserRolesVM.UserInformationId));
                        if (UserClaimRoles == null)
                        {
                            var userClaimRoles = context.UserClaimRoles.Add(new UserClaimRoles()
                            {
                                ClaimRolesId = claimRolesId, UserInformationId = new Guid(UserRolesVM.UserInformationId)
                            });
                            context.SaveChanges();
                        }
                    }
                }
                return(Ok());
            }
            else
            {
                return(StatusCode(500));
            }
        }
Пример #22
0
        //private static long SqlBulkCopyInsert()
        //{
        //    Stopwatch stopwatch = new Stopwatch();
        //    stopwatch.Start();
        //    DataTable dt = SqlHelper.ExecuteDataset(SqlHelper.GetConnSting(), CommandType.Text, "select  *   from    FROM [ClearAPEXDB].[dbo].[UserRoles] where  ID<0").Tables[0];
        //    string passportKey;
        //    for (int i = 0; i < dt.Columns.Count; i++)
        //    {

        //        DataRow dataRow = dt.NewRow();
        //        dataRow[""] = passportKey;
        //        dataTable.Rows.Add(dataRow);
        //    }
        //    SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(connectionString);
        //    sqlBulkCopy.DestinationTableName = "Passport";
        //    sqlBulkCopy.BatchSize = dataTable.Rows.Count;
        //    SqlConnection sqlConnection = new SqlConnection(connectionString);
        //    sqlConnection.Open();
        //    if (dataTable != null && dataTable.Rows.Count != 0)
        //    {
        //        sqlBulkCopy.WriteToServer(dataTable);
        //    }
        //    sqlBulkCopy.Close(); sqlConnection.Close();
        //    stopwatch.Stop();
        //    return stopwatch.ElapsedMilliseconds;
        //}

        public List <UserRolesVM> GetUserRoles(UserRolesVM vm)
        {
            return(_dal.GetUserRoles(vm));
        }
Пример #23
0
 public int DeleteUserRoles(UserRolesVM vm)
 {
     return(_dal.DeleteUserRoles(vm));
 }
Пример #24
0
 public List <RolesVM> GetUserNotHaveRoles(UserRolesVM vm)
 {
     return(_dal.GetUserNotHaveRoles(vm));
 }