public ActionResult GroupPage(string Wade, int GroupId) { if (Wade == "-1") { UserInGroup u = new UserInGroup(); foreach (var g in db.UserInGroups.ToList()) { if (g.UserName == User.Identity.Name && g.GroupId == GroupId) { u = g; } } db.UserInGroups.Remove(u); db.SaveChanges(); } else if (Wade == "-2") { db.AddUserInGroup(GroupId, User.Identity.Name); db.SaveChanges(); } else { Article a = db.Articles.Find(Convert.ToInt32(Wade)); a.GroupId = 0; db.SaveChanges(); } Group m = db.Groups.Find(GroupId); m.Articles = db.ArticleByGroup(GroupId); m.Users = db.UsersByGroup(GroupId); return(View("GroupPage", m)); }
public ActionResult GroupPage(string wade, int groupId) { switch (wade) { case "-1": var user = new UserInGroup(); foreach (var group in db.UserInGroups.ToList()) { if (group.UserName == User.Identity.Name && group.GroupId == groupId) { user = group; } } db.UserInGroups.Remove(user); db.SaveChanges(); break; case "-2": db.AddUserInGroup(groupId, User.Identity.Name); db.SaveChanges(); break; default: db.Articles.Find(Convert.ToInt32(wade)).GroupId = 0; db.SaveChanges(); break; } var model = db.Groups.Find(groupId); model.Articles = db.ArticleByGroup(groupId); model.Users = db.UsersByGroup(groupId); return(View("GroupPage", model)); }
//Post: Groups/JoinGroup public async Task <IActionResult> JoinGroup(int?id) { if (id == null) { return(NotFound()); } //Gets the current user var user = await this._userManager.GetUserAsync(User); //Gets the group with id sent from Groups/Details view var group = await this._context.Groups .FirstOrDefaultAsync(i => i.GroupId == id); //Adds new row in the UsersIngroups table where the current user is not admin var joinGroup = new UserInGroup() { UserId = user.Id, User = user, GroupId = (int)id, Group = group }; this._context.UsersInGroups.Add(joinGroup); await this._context.SaveChangesAsync(); return(RedirectToAction("MyGroups")); }
public void CreateGroup(string Name, int[] IDs) { if (Name.Length < 1) { Callback.Error("Input group name!"); return; } if (BaseOnlineUser.MainBase.Groups.FirstOrDefault((x) => x.Name == Name && x.Deleted == false) != null) { Callback.Error("Group with this name is already registered!"); return; } Group newGrp = BaseOnlineUser.MainBase.Groups.Add(new Group { Name = Name, Deleted = false }); UserInGroup usrInGrp = BaseOnlineUser.MainBase.UsersInGroups.Add(new UserInGroup { GroupID = newGrp.ID, UserID = BaseOnlineUser.BaseUser.ID, RoleID = 1, Muted = false }); BaseOnlineUser.MainBase.SaveChanges(); foreach (var item in BaseOnlineUser.Sessions) { item.Callback.RNewGroup(new RMUserInGroup(usrInGrp)); } if (IDs != null) { AddUsersToGroup(newGrp.ID, IDs); } return; }
public ActionResult InsertUserInGroup(string data, string ma_nhom_nguoi_dung) { if (accessDetail.them || accessDetail.sua) { using (var dbConn = Helpers.OrmliteConnection.openConn()) { dbConn.Delete <Core.Entities.UserInGroup>("id_nhom_nguoi_dung={0}", ma_nhom_nguoi_dung); string[] separators = { "@@" }; var listUserId = data.Split(separators, StringSplitOptions.RemoveEmptyEntries); foreach (var uid in listUserId) { var usr = dbConn.SingleOrDefault <User>("id = " + uid); UserInGroup newdata = new UserInGroup(); newdata.ma_nguoi_dung = usr.ma_nguoi_dung; newdata.id_nhom_nguoi_dung = int.Parse(ma_nhom_nguoi_dung); newdata.ngay_tao = DateTime.Now; newdata.nguoi_tao = User.Identity.Name; dbConn.Insert(newdata); } return(Json(new { success = true })); } } else { return(Json(new { success = false, error = "Bạn không có quyền cập nhật dữ liệu" })); } }
public void SendMessage(int groupID, string message) { UserInGroup usrGrp = BaseOnlineUser.BaseUser.UsersInGroups.FirstOrDefault((x) => x.GroupID == groupID); if (usrGrp == null) { Callback.RLeaveGroup(new RGroup(new Group { ID = groupID })); return; } if (message.Length < 1) { return; } GroupMessage msg = BaseOnlineUser.MainBase.GroupsMessages.Add(new GroupMessage { UserID = usrGrp.UserID, GroupID = usrGrp.GroupID, MessageSource = message }); BaseOnlineUser.MainBase.SaveChanges(); foreach (var item in BaseOnlineUser.OnlineUsers.Where((x) => x.BaseUser.UsersInGroups.FirstOrDefault((z) => z.GroupID == usrGrp.GroupID) != null)) { item.Sessions.ForEach((x) => x.Callback.RNewMessage(new RUser(usrGrp.User, false), new RGroupMessage(msg))); } }
public async Task <MessageInfo> UpdateAsync([FromBody] UserInGroup user) { // Item.CREATED_BY = 1; //Item.CREATED_ON = DateTime.Now; user.LAST_EDITED_BY = 1; user.LAST_EDITED_ON = DateTime.Now; MessageInfo obj = new MessageInfo(); try { var roles = await _userInGroupService.UpdateAsync(user); if (roles > 0) { obj.Info = "200"; obj.Message = "Successfully Updated"; } else { obj.Info = "400"; obj.Message = "Updation Failed"; } } catch (Exception Ex) { obj.Info = "400"; obj.Message = Ex.Message; } return(obj); }
//public async static Task<List<Group>> getAllUsersInGroup(string pass) //{ // var userInGroup = await conectDB.getUserOfGroup(pass); // return ; //} public async static Task <bool> AgreeToAddGroup(string pass, string phone) { try { UserProfile user = await conectDB.getUser(phone); Group g = await conectDB.getGroup(pass); if (g != null) { UserInGroup users = new UserInGroup(); users.UserPhoneGroup = user.Phone; g.Users.Add(users); g.OkUsers.Add(users); await conectDB.UpdateGroup(g); //TODO:שמירה בדטה בייס return(true); } return(false); } catch (Exception) { throw; } }
public void RemoveUserFromGroup(int groupID, int userID) { if (BaseOnlineUser.BaseUser.UsersInGroups == null) { Callback.RLeaveGroup(new RGroup(new Group { ID = groupID })); return; } UserInGroup usrGrp = BaseOnlineUser.BaseUser.UsersInGroups.FirstOrDefault((x) => x.GroupID == groupID); if (usrGrp == null) { Callback.RLeaveGroup(new RGroup(new Group { ID = groupID })); return; } UserInGroup usrGrpEdt = usrGrp.Group.UsersInGroups.FirstOrDefault((x) => x.UserID == userID); if (usrGrpEdt == null) { return; } User usrLeave = usrGrpEdt.User; if (usrGrp.RoleID >= usrGrpEdt.RoleID) { Callback.Error("You can't remove this user!"); return; } Console.WriteLine(usrGrpEdt.User.Login + " leave from group " + usrGrpEdt.Group.Name + " by " + BaseOnlineUser.BaseUser.Login); BaseOnlineUser.MainBase.UsersInGroups.Remove(usrGrpEdt); BaseOnlineUser.MainBase.SaveChanges(); if (BaseOnlineUser.OnlineUsers.FirstOrDefault((x) => x.BaseUser.ID == userID) != null) { foreach (var item in BaseOnlineUser.OnlineUsers.FirstOrDefault((x) => x.BaseUser.ID == userID).Sessions) { item.Callback.RLeaveGroup(new RGroup(usrGrp.Group)); } } UserInGroup tomp; foreach (var item in BaseOnlineUser.OnlineUsers) { tomp = usrGrp.Group.UsersInGroups.FirstOrDefault((s) => s.User.ID == item.BaseUser.ID); if (tomp != null) { foreach (var res in item.Sessions) { res.Callback.RLeaveUserInGroup(new RGroup(usrGrp.Group), new RUser(usrLeave, BaseOnlineUser.OnlineUsers.FirstOrDefault((x) => x.BaseUser.ID == usrLeave.ID) != null)); } } } }
public void LeaveFromGroup(int ID) { UserInGroup usrGrp = BaseOnlineUser.BaseUser.UsersInGroups.FirstOrDefault((x) => x.GroupID == ID); if (usrGrp != null) { Group grp = usrGrp.Group; User usr = usrGrp.User; if (usrGrp.RoleID == 1) { Console.WriteLine("Remove group " + grp.Name + " by " + BaseOnlineUser.BaseUser.Login); foreach (var item in BaseOnlineUser.OnlineUsers) { usrGrp = item.BaseUser.UsersInGroups.FirstOrDefault((x) => x.GroupID == ID); if (usrGrp != null) { foreach (var ites in item.Sessions) { ites.Callback.RLeaveGroup(new RGroup(grp)); } } } BaseOnlineUser.MainBase.Groups.Remove(grp); } else { Console.WriteLine("Leave group " + grp.Name + " by " + BaseOnlineUser.BaseUser.Login); BaseOnlineUser.MainBase.UsersInGroups.Remove(usrGrp); foreach (var ites in BaseOnlineUser.Sessions) { ites.Callback.RLeaveGroup(new RGroup(grp)); } UserInGroup tomp; foreach (var item in BaseOnlineUser.OnlineUsers) { tomp = grp.UsersInGroups.FirstOrDefault((s) => s.User.ID == item.BaseUser.ID); if (tomp != null) { foreach (var res in item.Sessions) { res.Callback.RLeaveUserInGroup(new RGroup(grp), new RUser(usr, true)); } } } } BaseOnlineUser.MainBase.SaveChanges(); } else { Callback.RLeaveGroup(new RGroup(new Group { ID = ID })); } }
public async Task CreateOrUpdate(UserInGroup userInGroup) { var group = await GetAsync(userInGroup.UserId, userInGroup.GroupId); if (group == null) { await CreateAsync(userInGroup); } else { Update(userInGroup); } }
private async Task AddAdminAsync(int groupId, string adminId) { var admin = new UserInGroup() { GroupId = groupId, UserId = adminId, Admin = true }; await this._data.UsersInGroups.AddAsync(admin); await this._data.SaveChangesAsync(); }
/// <summary> /// Creates new UserInGroup entity and save it to the db /// </summary> /// <param name="groupId"></param> /// <param name="currentUserId"></param> /// <returns></returns> public async Task JoinGroupAsync(int groupId, string currentUserId) { if (!await IsCurrentUserMember(currentUserId, groupId)) { var userInGroup = new UserInGroup { GroupId = groupId, UserId = currentUserId }; this._data.UsersInGroups.Add(userInGroup); await this._data.SaveChangesAsync(); } }
// // GET: /Admin/AdminUsers/Details/5 public ActionResult Details(int id) { if (!Request.IsAuthenticated || !repository.canAccessData(User.Identity.Name, "QuanTriNguoiDung")) { TempData["message"] = "Bạn không có quyền truy cập vào trang xem thông tin người dùng"; TempData["messageType"] = "error"; return(RedirectToAction("Index", "AdminHome")); } Users user = null; user = repository.Users.Where(u => u.id == id).FirstOrDefault(); if (user != null) { List <SelectListItem> list; list = new List <SelectListItem>() { new SelectListItem() { Text = "Phân nhóm cho người dùng ", Value = "UserInGroup" }, new SelectListItem() { Text = "Phân quyền cho nhóm người dùng", Value = "GroupRole" }, new SelectListItem() { Text = "Quản lý nhóm người dùng", Value = "GroupUser" }, new SelectListItem() { Text = "Quản lý người dùng", Value = "Users" } }; ViewBag.ListData = list; UserInGroup ug = userInGroupRepository.UserInGroups.Where(u => u.UserID == user.id).FirstOrDefault(); if (ug != null) { ViewBag.GroupRole = from gr in groupRoleRepository.GroupRoles.Where(g => g.GroupID == ug.GroupID) select gr; } return(View(user)); } else { TempData["message"] = "Người dùng này không tồn tại"; TempData["messageType"] = "error"; return(RedirectToAction("Index")); } }
public async Task <int> UpdateAsync(UserInGroup user) { var result = 0; try { result = await _connectionFactory.Connection.ExecuteAsync(@"update [dbo].[USER_IN_GROUP] set [USER_ID]=@uid,[GROUP_ID]=@gid,[LAST_EDITED_BY]=@editedby,[LAST_EDITED_ON]=@editedon where [USER_ID]=@uid", new { uid = user.USER_ID, gid = user.GROUP_ID, editedby = user.LAST_EDITED_BY, editedon = user.LAST_EDITED_ON } ); } catch (Exception Ex) { throw new System.InvalidOperationException(Ex.Message); } return(Int32.Parse(result.ToString())); }
/* * Add Role */ public async Task <int> AddAsync(UserInGroup user) { var result = 0; try { result = await _connectionFactory.Connection.ExecuteAsync(@"insert into [dbo].[USER_IN_GROUP]([USER_ID],[GROUP_ID],[CREATED_BY],[CREATED_ON],[LAST_EDITED_BY],[LAST_EDITED_ON]) values (@userid,@groupid,@created_by,@created_on,@editedby,@editedon)", new { userid = user.USER_ID, groupid = user.GROUP_ID, created_by = user.CREATED_BY, created_on = user.CREATED_ON, editedby = user.LAST_EDITED_BY, editedon = user.LAST_EDITED_ON } ); } catch (Exception Ex) { throw new System.InvalidOperationException(Ex.Message); } return(Int32.Parse(result.ToString())); }
public async Task <IActionResult> Create([FromForm] GroupViewModel viewModel) { if (viewModel.Group == null) { return(NotFound()); } else { ViewModel.Group = viewModel.Group; } //Unique title if (await this._context.Groups.AnyAsync(i => i.Title == ViewModel.Group.Title)) { ModelState.AddModelError("Title", $"Title {ViewModel.Group.Title} already exists. Title must be unique!"); return(View(ViewModel)); } if (ModelState.IsValid) { //Gets the current user ViewModel.CurrentUser = await this._userManager.GetUserAsync(User); //Create new row in the UsersInGroups table where the current user is admin var adminGroup = new UserInGroup() { UserId = ViewModel.CurrentUser.Id, User = ViewModel.CurrentUser, GroupId = ViewModel.Group.GroupId, Group = ViewModel.Group, Admin = true }; await this._context.UsersInGroups.AddAsync(adminGroup); await this._context.Groups.AddAsync(ViewModel.Group); await _context.SaveChangesAsync(); ViewModel = new GroupViewModel(); return(RedirectToAction(nameof(MyGroups))); } return(View()); }
public ActionResult CreateGroup(string GroupName, string Theme) { if (GroupName == null) { return(View()); } Group g = new Group { GroupName = GroupName, Theme = Theme }; db.Groups.Add(g); db.SaveChanges(); UserInGroup ug = new UserInGroup { UserName = User.Identity.Name, GroupId = g.GroupId }; db.UserInGroups.Add(ug); db.SaveChanges(); return(View("Finish")); }
public IActionResult AddGroup(GroupModel group) { if (!ModelState.IsValid) { return(BadRequest()); } if (ChatStore.UsersByGroups.Find(x => x.GroupName == group.Group) == null) { var newGroup = new UserInGroup() { GroupName = group.Group }; ChatStore.UsersByGroups.Add(newGroup); var currentUser = ChatStore.UsersOnline.Find(x => x.Username == User.Identity.Name); if (currentUser != null) { _chatHubContext.Clients.AllExcept(currentUser.ConnectionId).SendAsync("NewGroup", group); } } return(Ok()); }
public SelectUsersInGroupViewModel(Group group) : this() { var Db = new ApplicationDbContext(); this.GroupId = group.Id; this.GroupName = group.Name; // user in group var userInGroup = Db.Users.Where(u => u.Groups.Any(g => g.GroupId == group.Id)); foreach (var u in userInGroup) { var editorViewModel = new SelectUserEditorViewModel() { UserId = u.Id, UserName = u.UserName, FirstName = u.FirstName, LastName = u.LastName, Email = u.Email }; UserInGroup.Add(editorViewModel); } }
//public async static Task<List<Group>> getAllUsersInGroup(string pass) //{ // var userInGroup = await conectDB.getUserOfGroup(pass); // return ; //} public async static Task <bool> AgreeToAddGroup(string code, string phone) { try { UserProfile user = await conectDB.getUser(phone); List <Group> all = await conectDB.getAllGroup(); Group gr = all.FirstOrDefault(p => p.Code == code); if (gr != null && gr.ListManagment.Where(p => p.PhoneManagment == phone).ToList().Count == 0 && gr.Users.Where(p => p.UserPhoneGroup == phone).ToList().Count == 0) { UserInGroup users = new UserInGroup(); users.UserPhoneGroup = user.Phone; gr.Users.Add(users); gr.OkUsers.Add(users); await conectDB.UpdateGroup(gr); foreach (var item in gr.ListManagment) { var manager = await conectDB.getUser(item.PhoneManagment); manager.UserMessageNeedGet.Add(new MessageUser() { UserName = manager.FirstName + " " + manager.LastName, Group = gr, Message = gr.ErrorMessage.Find(p => p.CodeError == 9) }); await conectDB.UpdateUserMeesage(user); } return(true); } return(false); } catch (Exception ex) { throw; } }
public ActionResult CreateUpdate(UserGroup data, List <AccessDetail> AccessDetail) { try { using (var dbConn = Helpers.OrmliteConnection.openConn()) { if (data.id > 0) { if (data.id != 1 && data.name != "guest") { if (accessDetail != null && (accessDetail.access["all"] || accessDetail.access["update"])) { var existGroup = dbConn.SingleOrDefault <UserGroup>("name={0} and id <> {1}", data.name, data.id); if (existGroup != null) { return(Json(new { success = false, error = "Group name already existed" })); } var exist = dbConn.SingleOrDefault <UserGroup>("id={0}", data.id); data.updatedAt = DateTime.Now; data.updatedBy = currentUser.name; dbConn.UpdateOnly(data, onlyFields: p => new { p.name, p.description, p.active, p.updatedAt, p.updatedBy }, where : p => p.id == data.id); } else { return(Json(new { success = false, error = "Don't have permission to update" })); } } } else { if (accessDetail != null && (accessDetail.access["all"] || accessDetail.access["create"])) { var existGroup = dbConn.SingleOrDefault <UserGroup>("name={0}", data.name); if (existGroup != null) { return(Json(new { success = false, error = "Group name already existed" })); } data.createdAt = DateTime.Now; data.createdBy = currentUser.name; dbConn.Insert(data); int Id = (int)dbConn.GetLastInsertId(); data.id = Id; } else { return(Json(new { success = false, error = "Don't have permission to create" })); } } if (accessDetail != null && (accessDetail.access["all"] || accessDetail.access["grant access"])) { if (data.id != 1) { if (AccessDetail != null && AccessDetail.Count > 0) { foreach (var item in AccessDetail) { var existAccess = dbConn.SingleOrDefault <AccessRight>("controllerName={0}", item.controllerName); if (existAccess != null) { var newAccess = new Dictionary <string, bool>(); foreach (var a in existAccess.access) { newAccess.Add(a, item.access != null && item.access.ContainsKey(a) ? true : false); } var exist = dbConn.SingleOrDefault <AccessDetail>("groupId={0} AND controllerName={1}", item.groupId, item.controllerName); if (exist != null) { exist.access = newAccess; exist.updatedAt = DateTime.Now; exist.updatedBy = currentUser.name; dbConn.UpdateOnly(exist, onlyFields: p => new { p.access, p.updatedAt, p.updatedBy }, where : p => p.id == exist.id); } else { item.access = newAccess; item.createdAt = DateTime.Now; item.createdBy = currentUser.name; dbConn.Insert(item); } } } } } if (data.users != null && data.users.Count > 0) { foreach (var item in data.users) { var exist = dbConn.SingleOrDefault <UserInGroup>("userId={0} AND groupId={1}", item, data.id); if (exist == null) { var userInGroup = new UserInGroup(); userInGroup.userId = item; userInGroup.groupId = data.id; userInGroup.createdAt = DateTime.Now; userInGroup.createdBy = currentUser.name; dbConn.Insert(userInGroup); } } dbConn.Delete <UserInGroup>("groupId={0} AND userId NOT IN (" + String.Join(",", data.users.Select(s => s)) + ")", data.id); } } } return(Json(new { success = true, data = data })); } catch (Exception e) { return(Json(new { success = false, error = e.Message })); } }
public void AddUserInGroup(int id, string name) { UserInGroup u = new UserInGroup { GroupId = id, UserName = name }; this.UserInGroups.Add(u); this.SaveChanges(); }
public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return(RedirectToAction("Manage")); } if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await AuthenticationManager.GetExternalLoginInfoAsync(); if (info == null) { return(View("ExternalLoginFailure")); } using (var dbConn = Helpers.OrmliteConnection.openConn()) { var exist = dbConn.SingleOrDefault <Users>("email={0}", model.Email); if (exist == null) { var user = new ApplicationUser() { UserName = Helpers.RemoveVietNameChar.Remove(model.UserName).ToLower(), PhoneNumber = model.PhoneNumber, Email = model.Email }; var result = await UserManager.CreateAsync(user); if (result.Succeeded) { var newUser = new Users(); newUser.name = Helpers.RemoveVietNameChar.Remove(model.UserName).ToLower(); newUser.email = model.Email; newUser.phone = model.PhoneNumber; newUser.fullName = model.FullName; newUser.registerAt = DateTime.Now; newUser.active = true; newUser.vendorAuth = info.Login.LoginProvider; newUser.userKey = user.Id; newUser.createdAt = DateTime.Now; newUser.createdBy = "administrator"; dbConn.Insert(newUser); Int64 userId = (Int64)dbConn.GetLastInsertId(); var groupId = dbConn.Scalar <Int64>("select id from UserGroup where name = 'guest'"); if (groupId > 0) { var userInGroup = new UserInGroup(); userInGroup.userId = userId; userInGroup.groupId = groupId; userInGroup.createdAt = DateTime.Now; userInGroup.createdBy = "administrator"; dbConn.Insert(userInGroup); } result = await UserManager.AddLoginAsync(user.Id, info.Login); if (result.Succeeded) { string body = string.Empty; using (StreamReader reader = new StreamReader(System.Web.Hosting.HostingEnvironment.MapPath("~/EmailTemplate/newUserTemplate.html"))) { body = reader.ReadToEnd(); } body = body.Replace("{username}", Helpers.RemoveVietNameChar.Remove(model.UserName).ToLower()); body = body.Replace("{fullname}", model.FullName); body = body.Replace("{phone}", model.PhoneNumber); body = body.Replace("{email}", model.Email); await SignInAsync(user, isPersistent : false); return(RedirectToLocal(returnUrl)); } } AddErrors(result); } else { ModelState.AddModelError("", "Email is existed"); } } } ViewBag.ReturnUrl = returnUrl; return(View(model)); }
public ActionResult GroupPage(string Wade, int GroupId) { if (Wade == "-1") { UserInGroup u = new UserInGroup(); foreach(var g in db.UserInGroups.ToList()) { if (g.UserName == User.Identity.Name && g.GroupId == GroupId) u = g; } db.UserInGroups.Remove(u); db.SaveChanges(); } else if (Wade == "-2") { db.AddUserInGroup(GroupId, User.Identity.Name); db.SaveChanges(); } else { Article a = db.Articles.Find(Convert.ToInt32(Wade)); a.GroupId = 0; db.SaveChanges(); } Group m = db.Groups.Find(GroupId); m.Articles = db.ArticleByGroup(GroupId); m.Users = db.UsersByGroup(GroupId); return View("GroupPage", m); }
public ActionResult CreateGroup(string GroupName, string Theme) { if (GroupName == null) return View(); Group g = new Group {GroupName = GroupName, Theme = Theme}; db.Groups.Add(g); db.SaveChanges(); UserInGroup ug = new UserInGroup {UserName = User.Identity.Name, GroupId = g.GroupId}; db.UserInGroups.Add(ug); db.SaveChanges(); return View("Finish"); }
// // GET: /Admin/AdminUserInGroup/Create public ActionResult Create(int UserID) { if (!Request.IsAuthenticated || !userRepository.canAccessData(User.Identity.Name, "QuanTriNguoiDung")) { TempData["message"] = "Bạn không có quyền truy cập vào trang gán nhóm cho người dùng"; TempData["messageType"] = "error"; return(RedirectToAction("Index", "AdminHome")); } Users user = null; user = userRepository.Users.Where(u => u.id == UserID).FirstOrDefault(); if (user == null) { TempData["message"] = "Người dùng này không tồn tại"; TempData["messageType"] = "error"; return(RedirectToAction("Index", "AdminUsers")); } userInfor userEdit = userRepository.getInfor(user.username); userInfor userCanEdit = userRepository.getInfor(User.Identity.Name); if (userEdit.GroupID != null && userCanEdit.groupParent == userEdit.GroupID) { string message = "Rất lấy làm tiếc " + userCanEdit.NameDisplay + " ! <br/> "; message += "Tài khoản : " + userEdit.username + " là một " + userEdit.groupName + " <br/>"; message += "Tài khoản này có quyền cao hơn bạn trong hệ thống . Bạn không có quyền chỉnh sửa tài khoản này"; TempData["message"] = message; TempData["messageType"] = "error"; return(RedirectToAction("Index", "AdminUsers")); } if (userEdit.GroupID != null && userCanEdit.GroupID == userEdit.GroupID && userCanEdit.username != userEdit.username && userCanEdit.id != userEdit.id) { string message = "Rất lấy làm tiếc " + userCanEdit.NameDisplay + " ! <br/> "; message += "Tài khoản : " + userEdit.username + " là một " + userEdit.groupName + " <br/>"; message += "Tài khoản này có quyền ngang hàng với bạn trong hệ thống . Bạn không có quyền chỉnh sửa tài khoản này"; TempData["message"] = message; TempData["messageType"] = "error"; return(RedirectToAction("Index", "AdminUsers")); } UserInGroup userGroup = repository.UserInGroups.Where(ug => ug.UserID == UserID).FirstOrDefault(); if (userGroup != null) { return(RedirectToAction("Edit", "AdminUserInGroup", new { UserID = UserID })); } else { ViewBag.UserID = new SelectList(userRepository.Users.Where(u => u.id == UserID), "id", "username", UserID); if (userCanEdit.groupParent == null) { ViewBag.GroupID = new SelectList(groupUserRepository.GroupUsers.Where(g => g.status == true), "id", "name"); } else { ViewBag.GroupID = new SelectList(groupUserRepository.GroupUsers.Where(g => g.status == true && g.id != userCanEdit.GroupID && g.id != userCanEdit.groupParent), "id", "name"); } return(View()); } }
public ActionResult Edit(int id, UserInGroup collection) { if (!Request.IsAuthenticated || !userRepository.canAccessData(User.Identity.Name, "QuanTriNguoiDung")) { TempData["message"] = "Bạn không có quyền truy cập vào trang gán nhóm cho người dùng"; TempData["messageType"] = "error"; return(RedirectToAction("Index", "AdminHome")); } Users user = null; user = userRepository.Users.Where(u => u.id == collection.UserID).FirstOrDefault(); if (user == null) { TempData["message"] = "Người dùng này không tồn tại"; TempData["messageType"] = "error"; return(RedirectToAction("Index", "AdminUsers")); } userInfor userEdit = userRepository.getInfor(user.username); userInfor userCanEdit = userRepository.getInfor(User.Identity.Name); if (userEdit.GroupID != null && userCanEdit.groupParent == userEdit.GroupID) { string message = "Rất lấy làm tiếc " + userCanEdit.NameDisplay + " ! <br/> "; message += "Tài khoản : " + userEdit.username + " là một " + userEdit.groupName + " <br/>"; message += "Tài khoản này có quyền cao hơn bạn trong hệ thống . Bạn không có quyền chỉnh sửa tài khoản này"; TempData["message"] = message; TempData["messageType"] = "error"; return(RedirectToAction("Index", "AdminUsers")); } if (userEdit.GroupID != null && userCanEdit.GroupID == userEdit.GroupID && userCanEdit.username != userEdit.username && userCanEdit.id != userEdit.id) { string message = "Rất lấy làm tiếc " + userCanEdit.NameDisplay + " ! <br/> "; message += "Tài khoản : " + userEdit.username + " là một " + userEdit.groupName + " <br/>"; message += "Tài khoản này có quyền ngang hàng với bạn trong hệ thống . Bạn không có quyền chỉnh sửa tài khoản này"; TempData["message"] = message; TempData["messageType"] = "error"; return(RedirectToAction("Index", "AdminUsers")); } try { // TODO: Add update logic here if (ModelState.IsValid) { repository.saveUserInGroup(collection); TempData["message"] = "Đã gán quyền cho người dùng trong hệ thống"; TempData["messageType"] = "inf"; return(RedirectToAction("Index", "AdminUsers")); } else { ViewBag.UserID = new SelectList(userRepository.Users.Where(u => u.id == collection.UserID), "id", "username", collection.UserID); if (userCanEdit.groupParent == null) { ViewBag.GroupID = new SelectList(groupUserRepository.GroupUsers.Where(g => g.status == true), "id", "name", collection.GroupID); } else { ViewBag.GroupID = new SelectList(groupUserRepository.GroupUsers.Where(g => g.status == true && g.id != userCanEdit.GroupID && g.id != userCanEdit.groupParent), "id", "name"); } TempData["message"] = "Dữ liệu bạn nhập vào không hợp lệ."; TempData["messageType"] = "error"; return(View(collection)); } } catch (Exception ex) { ViewBag.UserID = new SelectList(userRepository.Users.Where(u => u.id == collection.UserID), "id", "username", collection.UserID); if (userCanEdit.groupParent == null) { ViewBag.GroupID = new SelectList(groupUserRepository.GroupUsers.Where(g => g.status == true), "id", "name", collection.GroupID); } else { ViewBag.GroupID = new SelectList(groupUserRepository.GroupUsers.Where(g => g.status == true && g.id != userCanEdit.GroupID && g.id != userCanEdit.groupParent), "id", "name"); } TempData["message"] = "Có lỗi hệ thống " + ex.Message; TempData["messageType"] = "error"; return(View(collection)); } }
public ResponseModel SaveUserManageModel(UserManageModel model, HttpPostedFileBase avatar) { ResponseModel response; var user = GetById(model.Id); #region Edit User if (user != null) { user.FirstName = model.FirstName; user.LastName = model.LastName; user.Email = model.Email; user.Status = model.Status; user.Phone = model.Phone; user.Gender = model.Gender; user.About = model.About; user.Address = model.Address; user.IdentityNumber = model.IdentityNumber; user.LastLogin = model.LastLogin; user.Facebook = model.Facebook; user.Twitter = model.Twitter; user.Google = model.Google; user.AvatarFileName = model.AvatarFileName; user.BirthDay = model.BirthDay; user.Password = model.Password; var currentGroups = user.UserInGroups.Select(nc => nc.UserGroupId).ToList(); foreach (var id in model.UserGroupIds) { if (!model.UserGroupIds.Contains(id)) { _userInGroupRepository.Delete(id); } } foreach (var groupId in model.UserGroupIds) { if (currentGroups.All(n => n != groupId)) { var userInGroup = new UserInGroup { UserId = user.Id, UserGroupId = groupId }; _userInGroupRepository.Insert(userInGroup); } } //Get page record order response = Update(user); if (response.Success && avatar != null) { UploadAvatar(user.Id, avatar); } return(response.SetMessage(response.Success ? _localizedResourceServices.T("AdminModule:::Users:::Messages:::UpdateSuccessfully:::Update user successfully.") : _localizedResourceServices.T("AdminModule:::Users:::Messages:::UpdateFailure:::Update user failed. Please try again later."))); } #endregion user = new User { Id = model.Id, FirstName = model.FirstName, LastName = model.LastName, Email = model.Email, Password = model.Password, Status = model.Status, Phone = model.Phone, Gender = model.Gender, About = model.About, Address = model.Address, IdentityNumber = model.IdentityNumber, LastLogin = model.LastLogin, Facebook = model.Facebook, Twitter = model.Twitter, Google = model.Google, AvatarFileName = model.AvatarFileName, BirthDay = model.BirthDay, Created = model.Created, CreatedBy = model.CreatedBy, Updated = model.Updated, UpdatedBy = model.UpdatedBy, }; response = Insert(user); foreach (var groupId in model.UserGroupIds) { var userInGroup = new UserInGroup { UserId = user.Id, UserGroupId = groupId }; _userInGroupRepository.Insert(userInGroup); } if (response.Success && avatar != null) { UploadAvatar(user.Id, avatar); } return(response.SetMessage(response.Success ? _localizedResourceServices.T("AdminModule:::Users:::Messages:::CreateSuccessfully:::Create user successfully.") : _localizedResourceServices.T("AdminModule:::Users:::Messages:::CreateFailure:::Create user failed. Please try again later."))); }
// GET // public List <UserInGroup> Get() { UserInGroup newUserInGroup = new UserInGroup(); return(newUserInGroup.getUserInGroupList()); }
public List <UserInGroup> Get(int GroupID) { UserInGroup group = new UserInGroup(); return(group.getUsersByGID(GroupID)); }
public List <UserInGroup> Get(int GroupID, int IndecisionID) { UserInGroup group = new UserInGroup(); return(group.getUsersInGroup(GroupID, IndecisionID)); }
//POST// public void Post([FromBody] UserInGroup userInGroup) { userInGroup.InsertUserInGroup(); }