Exemple #1
0
 public ActionResult Connecter(UserForm model)
 {
     if (ModelState.IsValid && WebSecurity.Login(model.Login, model.Password, persistCookie: false))
     {
         //FormsAuthentication.SetAuthCookie(model.Login, false);
         //---set element session
         //----------------------------
         UserProfile _userAccountExcel = new UserProfile();
         int         IDCurrentUser     = WebSecurity.GetUserId(User.Identity.Name);
         using (UsersContext db = new UsersContext())
         {
             Role _role = db.Roles.Where(r => r.RoleName == Constante.roleAdminFileExcel).FirstOrDefault();
             webpages_UsersInRoles wp = db.webpages_UsersInRole.Where(w => w.RoleId == _role.RoleId).FirstOrDefault();
             if (wp != null)
             {
                 _userAccountExcel = db.UserProfiles.Where(u => u.UserId == wp.UserId).FirstOrDefault();
             }
         }
         Session["AccountFileExcel"] = _userAccountExcel;
         //----------------------
         return(RedirectToAction("Index", "Home"));
     }
     else
     {
         if (ModelState.IsValid)
         {
             ModelState.AddModelError("", "Le login ou Mot de passe est incorrect");
         }
         return(View(model));
     }
 }
        public ActionResult AddRoles(List <int> idselects, int userId, List <int> idNotSelect)
        {
            bool check = false;

            if (idselects.Count() > 0)
            {
                foreach (var i in idselects)
                {
                    webpages_UsersInRoles item = new webpages_UsersInRoles();
                    item.UserId      = userId;
                    item.RoleId      = i;
                    item.Description = authorizeService.roleResponsitory.Single(i).Description.ToString();
                    if (authorizeService.userInRolesResponsitory.GetAll().Where(k => k.RoleId == i && k.UserId == userId).ToList().Count() == 0)
                    {
                        check = authorizeService.userInRolesResponsitory.Insert(item);
                    }
                }
            }
            if (idNotSelect.Count() > 0)
            {
                foreach (var i in idNotSelect)
                {
                    var cate = authorizeService.userInRolesResponsitory.GetAll().Where(q => q.UserId == userId && q.RoleId == i).ToList();
                    if (cate.Count() > 0)
                    {
                        var a = cate.FirstOrDefault();
                        check = authorizeService.userInRolesResponsitory.Delete(a);
                    }
                }
            }
            TempData["MessageStatus"] = check;
            TempData["Message"]       = $"Chỉnh sửa quyền {(check ? "" : "không")} thành công";
            return(Json(new { Result = check }));
        }
Exemple #3
0
        // PUT /webpages_UsersInRoles/token/
        public HttpResponseMessage Put(string token, [FromBody] webpages_UsersInRoles param)
        {
            // Abre nova conexão
            using (painel_taxservices_dbContext _db = new painel_taxservices_dbContext())
            {
                tbLogAcessoUsuario log = new tbLogAcessoUsuario();
                try
                {
                    log = Bibliotecas.LogAcaoUsuario.New(token, JsonConvert.SerializeObject(param), "Put", _db);

                    HttpResponseMessage retorno = new HttpResponseMessage();
                    if (Permissoes.Autenticado(token, _db))
                    {
                        GatewayWebpagesUsersInRoles.Update(token, param, _db);
                        log.codResposta = (int)HttpStatusCode.OK;
                        Bibliotecas.LogAcaoUsuario.Save(log, _db);
                        return(Request.CreateResponse(HttpStatusCode.OK));
                    }
                    else
                    {
                        log.codResposta = (int)HttpStatusCode.Unauthorized;
                        Bibliotecas.LogAcaoUsuario.Save(log, _db);
                        return(Request.CreateResponse(HttpStatusCode.Unauthorized));
                    }
                }
                catch (Exception e)
                {
                    log.codResposta = (int)HttpStatusCode.InternalServerError;
                    log.msgErro     = e.Message;
                    Bibliotecas.LogAcaoUsuario.Save(log);
                    throw new HttpResponseException(HttpStatusCode.InternalServerError);
                }
            }
        }
Exemple #4
0
        //
        // GET: /CreateUser/Edit/5

        public ActionResult Edit(int id = 0)
        {
            UserProfile up = new UserProfile();

            try
            {
                //Check Authorization
                string roleName = System.Web.Security.Roles.GetRolesForUser().Single();
                if (roleName.ToUpper() == "USER")
                {
                    return(RedirectToAction("login", "account"));
                }

                up = db.tbl_UserProfile.Find(id);
                webpages_UsersInRoles ur = db.tbl_webpages_UsersInRoles.Find(up.UserId);
                if (up == null)
                {
                    return(HttpNotFound());
                }
                ViewBag.RoleId = new SelectList(db.tbl_webpages_Roles, "RoleId", "RoleName", ur.RoleId);
                return(View(up));
            }
            catch (Exception e)
            {
                ExceptionHandler handler = new ExceptionHandler();
                handler.HandleException(e);
            }
            return(View(up));
        }
        public ActionResult DeleteConfirmed(int id)
        {
            webpages_UsersInRoles webpages_usersinroles = db.webpages_UsersInRoles.Find(id);

            db.webpages_UsersInRoles.Remove(webpages_usersinroles);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Exemple #6
0
        public ActionResult DeleteConfirmed(int UserId = 0, int RoleId = 0)
        {
            webpages_UsersInRoles webpages_usersinroles = db.webpages_UsersInRoles.Where(usrl => usrl.UserId == UserId && usrl.RoleId == RoleId).FirstOrDefault <webpages_UsersInRoles>();

            db.webpages_UsersInRoles.Remove(webpages_usersinroles);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Exemple #7
0
 public ActionResult Edit(webpages_UsersInRoles webpages_usersinroles)
 {
     if (ModelState.IsValid)
     {
         db.Entry(webpages_usersinroles).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(webpages_usersinroles));
 }
Exemple #8
0
        public webpages_UsersInRoles CreateRole(int userID, int roleID)
        {
            webpages_UsersInRoles rec = new webpages_UsersInRoles {
                UserId = userID, RoleId = roleID
            };

            _datacontext.webpages_UsersInRoles.InsertOnSubmit(rec);
            _datacontext.SubmitChanges();
            return(rec);
        }
Exemple #9
0
        //
        // GET: /webpages_UsersInRolesAdmin/Edit/5

        public ActionResult Edit(int id = 0)
        {
            webpages_UsersInRoles webpages_usersinroles = db.webpages_UsersInRoles.Find(id);

            if (webpages_usersinroles == null)
            {
                return(HttpNotFound());
            }
            return(View(webpages_usersinroles));
        }
Exemple #10
0
        //
        // GET: /webpages_UsersInRolesAdmin/Delete/5

        public ActionResult Delete(int UserId = 0, int RoleId = 0)
        {
            //webpages_UsersInRoles webpages_usersinroles = db.webpages_UsersInRoles.Find(id);
            webpages_UsersInRoles webpages_usersinroles = db.webpages_UsersInRoles.Where(usrl => usrl.UserId == UserId && usrl.RoleId == RoleId).FirstOrDefault <webpages_UsersInRoles>();

            if (webpages_usersinroles == null)
            {
                return(HttpNotFound());
            }
            return(View(webpages_usersinroles));
        }
Exemple #11
0
        public webpages_UsersInRoles DeleteUserRole(int id)
        {
            webpages_UsersInRoles db = context.webpages_usersinroles.Find(id);

            if (db != null)
            {
                context.webpages_usersinroles.Remove(db);
                context.SaveChanges();
            }
            return(db);
        }
 public void InsertOrUpdate(webpages_UsersInRoles entity)
 {
     if (entity.UserId == default(int))
     {
         _context.SetAdd(entity);
     }
     else
     {
         _context.SetModified(entity);
     }
 }
Exemple #13
0
        public ActionResult Create(webpages_UsersInRoles webpages_usersinroles)
        {
            if (ModelState.IsValid)
            {
                db.webpages_UsersInRoles.Add(webpages_usersinroles);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(webpages_usersinroles));
        }
Exemple #14
0
 public static void InsertAdminInRole(int AdminId, int RoleId)
 {
     using (MoreHolidaysDBEntities db = new MoreHolidaysDBEntities())
     {
         webpages_UsersInRoles UserInRole = new webpages_UsersInRoles()
         {
             UserId = AdminId, RoleId = RoleId
         };
         db.webpages_UsersInRoles.Add(UserInRole);
         db.SaveChanges();
     }
 }
Exemple #15
0
        public ActionResult DelManagerRole(int Id)
        {
            webpages_UsersInRoles role  = new webpages_UsersInRoles();
            webpages_UsersInRoles role1 = db.webpages_UsersInRoles.Find(Id, 2);

            db.webpages_UsersInRoles.Remove(role1);
            role.UserId = Id;
            role.RoleId = 3;
            db.webpages_UsersInRoles.Add(role);
            db.SaveChanges();
            return(RedirectToAction("ManageUsers", "Admin"));
        }
        public ActionResult Delete(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            webpages_UsersInRoles webpages_usersinroles = db.webpages_UsersInRoles.Find(id);

            if (webpages_usersinroles == null)
            {
                return(HttpNotFound());
            }
            return(View(webpages_usersinroles));
        }
Exemple #17
0
        /// <summary>
        /// Altera webpages_UsersInRoles
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static void Update(string token, webpages_UsersInRoles param, painel_taxservices_dbContext _dbContext = null)
        {
            painel_taxservices_dbContext _db;

            if (_dbContext == null)
            {
                _db = new painel_taxservices_dbContext();
            }
            else
            {
                _db = _dbContext;
            }
            try
            {
                webpages_UsersInRoles value = _db.webpages_UsersInRoles
                                              .Where(e => e.UserId.Equals(param.UserId))
                                              .First <webpages_UsersInRoles>();

                // OBSERVAÇÂO: VERIFICAR SE EXISTE ALTERAÇÃO NO PARAMETROS


                if (param.UserId != null && param.UserId != value.UserId)
                {
                    value.UserId = param.UserId;
                }
                if (param.RoleId != null && param.RoleId != value.RoleId)
                {
                    value.RoleId = param.RoleId;
                }
                _db.SaveChanges();
            }
            catch (Exception e)
            {
                if (e is DbEntityValidationException)
                {
                    string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e);
                    throw new Exception(erro.Equals("") ? "Falha ao alterar userinroles" : erro);
                }
                throw new Exception(e.InnerException == null ? e.Message : e.InnerException.InnerException == null ? e.InnerException.Message : e.InnerException.InnerException.Message);
            }
            finally
            {
                if (_dbContext == null)
                {
                    // Fecha conexão
                    _db.Database.Connection.Close();
                    _db.Dispose();
                }
            }
        }
Exemple #18
0
        public void UpdateUserRole(webpages_UsersInRoles userRole)
        {
            var foundUserRole = context.webpages_UsersInRoles
                                .Where(r => r.UserId == userRole.UserId)
                                .Where(r => r.RoleId == userRole.RoleId)
                                .FirstOrDefault();

            if (foundUserRole == null)
            {
                return;
            }

            foundUserRole.RoleId = userRole.RoleId;
        }
 public ActionResult Edit([Bind(Include = "UserId,RoleId")] webpages_UsersInRoles webpages_usersinroles)
 {
     if (ModelState.IsValid)
     {
         db.Entry(webpages_usersinroles).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     ViewBag.UserId = new SelectList(db.UserProfiles, "UserId", "Username", webpages_usersinroles.UserId);
     ViewBag.UserId = new SelectList(db.UserProfiles, "UserId", "Username", webpages_usersinroles.UserId);
     ViewBag.UserId = new SelectList(db.UserProfiles, "UserId", "Username", webpages_usersinroles.UserId);
     ViewBag.RoleId = new SelectList(db.webpages_Roles, "RoleId", "RoleName", webpages_usersinroles.RoleId);
     ViewBag.RoleId = new SelectList(db.webpages_Roles, "RoleId", "RoleName", webpages_usersinroles.RoleId);
     ViewBag.RoleId = new SelectList(db.webpages_Roles, "RoleId", "RoleName", webpages_usersinroles.RoleId);
     return(View(webpages_usersinroles));
 }
Exemple #20
0
        public ActionResult EditUser(UserProfile_form model)
        {
            //         Admtszh admuser = repository.Admtszh.Where(p => p.AdmtszhId.Equals(WebSecurity.CurrentUserId)).SingleOrDefault();
            //         uk_profile uk = repository.uk_profile.Where(p => p.id.Equals(admuser.id_uk)).SingleOrDefault();

            webpages_UsersInRoles userrole = new webpages_UsersInRoles();

            string[] ir = Roles.GetRolesForUser(model.login);

            if (ir.Length > 0)
            {
                Roles.RemoveUserFromRoles(model.login, ir);
            }
            if (model.Role != null)
            {
                Roles.AddUserToRoles(model.login, model.Role);
            }

            UserProfile profile = new UserProfile(model);

            repository.SaveUserRole(userrole);
            if (ModelState.IsValid)
            {
                repository.SaveUser(profile);
                TempData["message"] = string.Format("Изменения странице \"{0}\" были сохранены", model.login);
            }

            IEnumerable <uk_profile> list_uk = repository.uk_profile.OrderBy(p => p.id);

            ViewData["uk_profile"] = from n in list_uk
                                     select new SelectListItem {
                Text = n.Name, Value = n.id.ToString()
            };

            IEnumerable <uk_adress> list_adr = repository.uk_adress.Where(p => p.id.Equals(model.Adress));

            ViewData["uk_adress"] = from adr in list_adr
                                    select new SelectListItem {
                Text = adr.City.ToString() + ", " + adr.Street.ToString() + ", " + adr.House, Value = adr.id.ToString()
            };

            //присвоить роль пользователю
            model.Role = Roles.GetRolesForUser(model.login);

            return(Json(model));
        }
Exemple #21
0
        public void SaveUserRole(webpages_UsersInRoles user)
        {
            webpages_UsersInRoles db = context.webpages_usersinroles.Find(user.UserId);

            if (db == null)
            {
                db        = new webpages_UsersInRoles();
                db.UserId = user.UserId;
                db.RoleId = user.RoleId;
                context.webpages_usersinroles.Add(db);
            }
            else
            {
                db.UserId = user.UserId;
                db.RoleId = user.RoleId;
            }
            context.SaveChanges();
        }
        public void PutUserRoles(webpages_UsersInRoles model)
        {
            DBContext db = new DBContext();

            try
            {
                if (ModelState.IsValid)
                {
                    db.Entry(model).State = EntityState.Modified;
                    db.SaveChanges();
                }
            }
            catch (Exception e)
            {
                ExceptionHandler handler = new ExceptionHandler();
                handler.HandleException(e);
            }
        }
Exemple #23
0
        public bool DeleteUser(int userId)
        {
            UserProfile usr = GetUser(userId);

            _datacontext.UserProfile.DeleteOnSubmit(usr);
            webpages_Membership member = GetMembership(userId);

            _datacontext.webpages_Membership.DeleteOnSubmit(member);
            webpages_UsersInRoles userRole = GetUserRole(userId);

            if (userRole != null)
            {
                _datacontext.webpages_UsersInRoles.DeleteOnSubmit(userRole);
            }
            member = GetMembership(userId);
            _datacontext.webpages_Membership.DeleteOnSubmit(member);
            _datacontext.SubmitChanges();
            return(true);
        }
        public webpages_UsersInRoles GetUsersInRolesByID(int?UserId)
        {
            webpages_UsersInRoles model = new webpages_UsersInRoles();

            try
            {
                using (var db = new DBContext())
                {
                    model = (from u in db.tbl_webpages_UsersInRoles
                             where u.UserId == UserId.Value
                             select u).ToList().FirstOrDefault();
                }
            }
            catch (Exception e)
            {
                ExceptionHandler handler = new ExceptionHandler();
                handler.HandleException(e);
            }
            return(model);
        }
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            webpages_UsersInRoles webpages_usersinroles = db.webpages_UsersInRoles.Find(id);

            if (webpages_usersinroles == null)
            {
                return(HttpNotFound());
            }
            ViewBag.UserId = new SelectList(db.UserProfiles, "UserId", "Username", webpages_usersinroles.UserId);
            ViewBag.UserId = new SelectList(db.UserProfiles, "UserId", "Username", webpages_usersinroles.UserId);
            ViewBag.UserId = new SelectList(db.UserProfiles, "UserId", "Username", webpages_usersinroles.UserId);
            ViewBag.RoleId = new SelectList(db.webpages_Roles, "RoleId", "RoleName", webpages_usersinroles.RoleId);
            ViewBag.RoleId = new SelectList(db.webpages_Roles, "RoleId", "RoleName", webpages_usersinroles.RoleId);
            ViewBag.RoleId = new SelectList(db.webpages_Roles, "RoleId", "RoleName", webpages_usersinroles.RoleId);
            return(View(webpages_usersinroles));
        }
        public ActionResult DeleteConfirmed(int id)
        {
            bool exception = false;

            try
            {
                UserProfile userprofile = db.UserProfiles.Find(id);                                                     //cri-o um userprofile atraves da buscar na bd pelo id fornecido
                //crio uma variavel que vai representar outra bd
                webpages_UsersInRoles userinroles = rdb.webpages_UsersInRoles.FirstOrDefault(r => r.UserId.Equals(id)); //Diz respeito a tabela
                //dos UserRoles ou seja aquela que faz a ligação entre os users e os roles
                //aqui crio uma relação que ira dizer respeito ao primeiro caso que ela encontrar que corresponde a
                //r => r.UserId.Equals(Id) isto é a expressao que vai procurar na bd UsersInRoles por um caso cujo UserID seja igual ao Id
                //fornecido
                rdb.webpages_UsersInRoles.Remove(userinroles); //removo da tabela UsersInRoles o tal caso
                rdb.SaveChanges();                             //guardo as alterações
                db.UserProfiles.Remove(userprofile);           //removo o userprofile da tabela UserProfiles
                db.SaveChanges();                              //guardo alterações
            }
            catch (Exception ex)
            {
                exception     = true;
                ViewBag.alert = "<div id=\"myalert\" class=\"alert alert-danger fade in alert-class\">" +
                                "<a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">&times;</a>" +
                                "<strong>Erro!</strong>Ocorreu um erro ao tentar Apagar o Utilizador" +
                                "</div>";
            }
            finally
            {
                if (exception)
                {
                    ViewBag.alert = "<div id=\"myalert\" class=\"alert alert-success fade in alert-class\">" +
                                    "<a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">&times;</a>" +
                                    "<strong>Success!</strong>O utilizador foi apagado com sucesso!" +
                                    "</div>";
                }
            }

            return(RedirectToAction("ManageUsers")); //fim
        }
Exemple #27
0
        public UserRole CreateUserRole(UserRole userRole)
        {
            webpages_UsersInRoles role = new webpages_UsersInRoles()
            {
                UserRoleId = Guid.NewGuid(),
                UserId     = userRole.UserId,
                RoleId     = userRole.RoleId
            };

            var obj = context.webpages_UsersInRoles.Add(role);

            UserRole addedUserRole = new UserRole
            {
                UserRoleId = obj.UserRoleId,
                UserId     = obj.UserId,
                RoleId     = obj.RoleId
            };



            return(addedUserRole);
        }
Exemple #28
0
        /// <summary>
        /// Adiciona nova Webpages_UsersInRoles
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static Int32 Add(string token, webpages_UsersInRoles param, painel_taxservices_dbContext _dbContext = null)
        {
            painel_taxservices_dbContext _db;

            if (_dbContext == null)
            {
                _db = new painel_taxservices_dbContext();
            }
            else
            {
                _db = _dbContext;
            }
            try
            {
                _db.webpages_UsersInRoles.Add(param);
                _db.SaveChanges();
                return(param.UserId);
            }
            catch (Exception e)
            {
                if (e is DbEntityValidationException)
                {
                    string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e);
                    throw new Exception(erro.Equals("") ? "Falha ao salvar userinrole" : erro);
                }
                throw new Exception(e.InnerException == null ? e.Message : e.InnerException.InnerException == null ? e.InnerException.Message : e.InnerException.InnerException.Message);
            }
            finally
            {
                if (_dbContext == null)
                {
                    // Fecha conexão
                    _db.Database.Connection.Close();
                    _db.Dispose();
                }
            }
        }
Exemple #29
0
        /// <summary>
        /// Apaga uma Webpages_UsersInRoles
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static void Delete(string token, webpages_UsersInRoles param, painel_taxservices_dbContext _dbContext = null)
        {
            painel_taxservices_dbContext _db;

            if (_dbContext == null)
            {
                _db = new painel_taxservices_dbContext();
            }
            else
            {
                _db = _dbContext;
            }
            try
            {
                _db.webpages_UsersInRoles.RemoveRange(_db.webpages_UsersInRoles.Where(e => e.UserId == param.UserId && e.RoleId == param.RoleId));
                _db.SaveChanges();
            }
            catch (Exception e)
            {
                if (e is DbEntityValidationException)
                {
                    string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e);
                    throw new Exception(erro.Equals("") ? "Falha ao apagar userinroles" : erro);
                }
                throw new Exception(e.InnerException == null ? e.Message : e.InnerException.InnerException == null ? e.InnerException.Message : e.InnerException.InnerException.Message);
            }
            finally
            {
                if (_dbContext == null)
                {
                    // Fecha conexão
                    _db.Database.Connection.Close();
                    _db.Dispose();
                }
            }
        }
Exemple #30
0
        /// <summary>
        /// Altera webpages_Users
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static void Update(string token, Models.Object.Usuario param, painel_taxservices_dbContext _dbContext = null)
        {
            painel_taxservices_dbContext _db;

            if (_dbContext == null)
            {
                _db = new painel_taxservices_dbContext();
            }
            else
            {
                _db = _dbContext;
            }

            try
            {
                if (param.Id_grupo != 0)
                {
                    // Altera grupo empresa do usuário logado
                    Int32          IdUser = Permissoes.GetIdUser(token);
                    webpages_Users value  = _db.webpages_Users
                                            .Where(e => e.id_users == IdUser)
                                            .FirstOrDefault <webpages_Users>();

                    if (value != null)
                    {
                        // VALIDAR PERMISSÂO PARA FUNCIONALIDADE

                        if (param.Id_grupo == -1)
                        {
                            value.id_grupo = null;
                        }
                        else
                        {
                            value.id_grupo = param.Id_grupo;
                        }

                        value.nu_cnpjEmpresa = null;
                        _db.SaveChanges();
                    }
                    else
                    {
                        throw new Exception("Usuário inválido!");
                    }
                }
                else
                {
                    if (param.Webpagesusers.id_users == 0)
                    {
                        throw new Exception("Falha ao parâmetro");
                    }

                    // Altera um usuário que não necessiariamente é o logado
                    webpages_Users value = _db.webpages_Users
                                           .Where(e => e.id_users == param.Webpagesusers.id_users)
                                           .First <webpages_Users>();

                    if (value != null)
                    {
                        if (param.Pessoa != null)
                        {
                            param.Pessoa.id_pesssoa = (int)value.id_pessoa;
                            GatewayPessoa.Update(token, param.Pessoa);
                        }

                        if (param.Webpagesusersinroles != null)
                        {
                            foreach (webpages_UsersInRoles item in param.Webpagesusersinroles)
                            {
                                if (item.UserId == -1)
                                {
                                    item.UserId = param.Webpagesusers.id_users;
                                    GatewayWebpagesUsersInRoles.Delete(token, item);
                                }
                                else
                                {
                                    item.UserId = param.Webpagesusers.id_users;
                                    webpages_UsersInRoles verificacao = _db.webpages_UsersInRoles.Where(p => p.UserId == item.UserId).Where(p => p.RoleId == item.RoleId).FirstOrDefault();
                                    if (verificacao != null)
                                    {
                                        webpages_UsersInRoles principal = _db.webpages_UsersInRoles
                                                                          .Where(p => p.UserId == item.UserId)
                                                                          .Where(p => p.RolePrincipal == true).FirstOrDefault();
                                        if (principal != null)
                                        {
                                            principal.RolePrincipal = false;
                                        }

                                        verificacao.RolePrincipal = item.RolePrincipal;
                                        _db.SaveChanges();
                                    }
                                    else
                                    {
                                        GatewayWebpagesUsersInRoles.Add(token, item);
                                    }
                                }
                            }
                        }
                        // Associa grupos empresas ao vendedor
                        if (param.Addidsgrupoempresavendedor != null)
                        {
                            foreach (var idGrupo in param.Addidsgrupoempresavendedor)
                            {
                                grupo_empresa grupo = _db.grupo_empresa.Where(g => g.id_grupo == idGrupo).FirstOrDefault();

                                if (grupo != null)
                                {
                                    grupo.id_vendedor = param.Webpagesusers.id_users;
                                    _db.SaveChanges();
                                }
                            }
                        }
                        // Desassocia grupos empresas
                        if (param.Removeidsgrupoempresavendedor != null)
                        {
                            foreach (var idGrupo in param.Removeidsgrupoempresavendedor)
                            {
                                grupo_empresa grupo = _db.grupo_empresa.Where(g => g.id_grupo == idGrupo).FirstOrDefault();

                                if (grupo != null)
                                {
                                    grupo.id_vendedor = null;
                                    _db.SaveChanges();
                                }
                            }
                        }


                        if (param.Webpagesusers.ds_login != null && param.Webpagesusers.ds_login != value.ds_login)
                        {
                            webpages_Users old = _db.webpages_Users.Where(e => e.ds_login.ToLower().Equals(param.Webpagesusers.ds_login.ToLower()))
                                                 .FirstOrDefault();
                            if (old == null || old.id_users == value.id_users)
                            {
                                value.ds_login = param.Webpagesusers.ds_login;
                            }
                        }
                        if (param.Webpagesusers.ds_email != null && param.Webpagesusers.ds_email != value.ds_email)
                        {
                            webpages_Users old = _db.webpages_Users.Where(e => e.ds_email.ToLower().Equals(param.Webpagesusers.ds_email.ToLower()))
                                                 .FirstOrDefault();
                            if (old == null || old.id_users == value.id_users)
                            {
                                value.ds_email = param.Webpagesusers.ds_email;
                            }
                        }
                        if (param.Webpagesusers.fl_ativo != value.fl_ativo)
                        {
                            value.fl_ativo = param.Webpagesusers.fl_ativo;
                        }

                        Boolean grupoEmpresaAlterado = false;
                        if (param.Webpagesusers.nu_cnpjEmpresa != null && param.Webpagesusers.nu_cnpjEmpresa != value.nu_cnpjEmpresa)
                        {
                            if (param.Webpagesusers.nu_cnpjEmpresa == "")
                            {
                                value.nu_cnpjEmpresa = null;
                            }
                            else
                            {
                                value.nu_cnpjEmpresa = param.Webpagesusers.nu_cnpjEmpresa;
                                value.id_grupo       = _db.empresas.Where(f => f.nu_cnpj.Equals(param.Webpagesusers.nu_cnpjEmpresa)).Select(f => f.id_grupo).FirstOrDefault();
                                grupoEmpresaAlterado = true; // já forçou o grupo pela filial
                            }
                        }// só pode colocar grupo empresa ao qual a filial está ou sem nenhuma filial

                        if (!grupoEmpresaAlterado && param.Webpagesusers.id_grupo != null && param.Webpagesusers.id_grupo != 0 && param.Webpagesusers.id_grupo != value.id_grupo)
                        {
                            if (param.Webpagesusers.id_grupo == -1)
                            {
                                value.id_grupo       = null;
                                value.nu_cnpjEmpresa = null; // Não pode estar associado a uma filial sem estar associado a um grupo
                            }
                            else
                            {
                                value.id_grupo = param.Webpagesusers.id_grupo;
                                // Avalia se tem empresa associado => A filial TEM QUE SER associada ao grupo
                                if (value.nu_cnpjEmpresa != null)
                                {
                                    Int32 id_grupo = _db.empresas.Where(f => f.nu_cnpj.Equals(value.nu_cnpjEmpresa)).Select(f => f.id_grupo).FirstOrDefault();
                                    if (id_grupo != value.id_grupo)
                                    {
                                        value.nu_cnpjEmpresa = null; // filial que estava associado é de um grupo diferente do grupo recém associado
                                    }
                                }
                            }
                        }

                        _db.SaveChanges();
                    }
                    else
                    {
                        throw new Exception("Usuário não cadastrado");
                    }
                }
            }
            catch (Exception e)
            {
                if (e is DbEntityValidationException)
                {
                    string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e);
                    throw new Exception(erro.Equals("") ? "Falha ao alterar usuário" : erro);
                }
                throw new Exception(e.InnerException == null ? e.Message : e.InnerException.InnerException == null ? e.InnerException.Message : e.InnerException.InnerException.Message);
            }
            finally
            {
                if (_dbContext == null)
                {
                    // Fecha conexão
                    _db.Database.Connection.Close();
                    _db.Dispose();
                }
            }
        }