Esempio n. 1
0
        public static bool CanDo(long userId, string moduleId, string code)
        {
            //Load user for roles
            var user = BlUser.LoadSingle(userId);

            if (user == null)
            {
                throw new BusinessException("UserNotFound");
            }

            var roles = BlRole.LoadParents(userId, user.Roles.ToList());

            //Exit if full permission case of roles system administrator
            if (roles.Select(r => r.Id).Contains(Constants.FullAdminRole))
            {
                return(true);
            }

            //Load permissions for user roles
            var blPermission = new BlPermission();
            var permissions  = blPermission.LoadByModuleAndRole(user.Id, moduleId, roles.ToList(), true).ToList();

            //Return permission existance
            return(permissions.Where(p => p.Code == code).Any());
        }
Esempio n. 2
0
        public string LoadAllForTree(long userId)
        {
            var predicate = PredicateBuilder.True <Role>();

            //Exclude full admin
            predicate = predicate.And(e => e.Id != 1);

            var roleTree = LoadSearch(userId, predicate);

            //Get security permissions
            var allowView   = BlPermission.CanDo(userId, Module, "View");
            var allowAdd    = BlPermission.CanDo(userId, Module, "Add");
            var allowEdit   = BlPermission.CanDo(userId, Module, "Edit");
            var allowDelete = BlPermission.CanDo(userId, Module, "Delete");

            //Create return object
            var toRet = new List <TreeItemVm>();

            //Create root node
            var rootNode = new Role {
                Id = 0
            };

            //Add root node
            toRet.AddRange(ConstructTreeNode(userId, rootNode.SingleItemAsEnumerable(), false, allowAdd, false, false));

            //Add menus
            toRet.AddRange(ConstructTreeNode(userId, roleTree.ToList(), allowView, allowAdd, allowEdit, allowDelete));

            return(new JavaScriptSerializer().Serialize(toRet));
        }
Esempio n. 3
0
        private string GetRolePermissions(long userId, long roleId)
        {
            var blModule = new BlModule();
            var modules  = blModule.LoadAll(userId).ToList();

            var toRetModules = (from m in modules
                                select new TreeItemVm
            {
                id = "M_" + m.Id,
                parent = "#",
                text = m.Id,
                icon = "fa fa-folder colorMain ",
                state = "{\"opened\": \"true\"}",
                li_attr = "{\"class\" : \"form-control-label\"}",
                a_attr = "{\"class\": \"no_checkbox\"}"
            }).ToList();


            //Get all modules permissions and set is active for assigned ones
            var blPermission = new BlPermission();
            var permissions  = blPermission.LoadAll(userId).ToList();

            permissions.ForEach(p => p.IsActive = p.Roles.Where(r => r.Id == roleId).Any());

            //Get is active from parent and set them as disabled
            var parentRolesIds = LoadParents(userId, LoadSingle(userId, roleId).SingleItemAsList()).Where(role => role.Id != roleId).Select(parentRole => parentRole.Id);

            permissions.ForEach(p => p.IsActiveInherited = p.Roles.Where(r => parentRolesIds.Contains(r.Id)).Any());

            var toRetPermissions = (from p in permissions
                                    select new TreeItemVm
            {
                id = p.Id.ToString(),
                parent = "M_" + p.Module.Id,
                text = p.Code,
                icon = "fa fa-gear " + (p.IsActive ? "colorGreen" : "colorRed"),
                state = "{\"selected\": \"" + (p.IsActive || p.IsActiveInherited ? "true" : "false") + "\", \"disabled\": \"" + (p.IsActiveInherited ? "true" : "false") + "\"}",
                li_attr = "{\"class\" : \"form-control-label " + (p.IsActiveInherited ? "jstree-disabled" : "") + "\"}"
            }).ToList();

            toRetModules.AddRange(toRetPermissions);
            var toRet = new JavaScriptSerializer().Serialize(toRetModules);

            return(toRet);
        }
Esempio n. 4
0
        public IEnumerable <Role> LoadForPermission(long userId, string moduleId, string permissionCode, long?roleId = 0)
        {
            //Load all roles
            var toRet = LoadAll(userId).ToList();

            //Load all selected permission roles
            var blPermission = new BlPermission();
            var permission   = blPermission.LoadByModuleAndCode(userId, moduleId, permissionCode);

            foreach (var role in permission.Roles)
            {
                if (toRet.Where(r => r.Id == role.Id).Any())
                {
                    toRet.Where(r => r.Id == role.Id).SingleOrDefault().IsActive = true;
                }
            }
            return(toRet.ToList());
        }
Esempio n. 5
0
        public LoginVm Authenticate(LoginVm model)
        {
            var hashedPass = Cryptography.ComputeToHash(model.Password);

            if (hashedPass == null)
            {
                throw new BusinessException("InvalidLogin");
            }

            var userRepository = new UserRepository();
            var predicate      = PredicateBuilder.True <User>();

            predicate = predicate.And(u => u.UserName == model.Username);
            var users = userRepository.LoadSearch(predicate);

            //Check if any user have same password
            IStructuralEquatable eqa1 = hashedPass;
            var user = users.FirstOrDefault(u => eqa1.Equals(u.Password, StructuralComparisons.StructuralEqualityComparer));

            if (user == null)
            {
                throw new BusinessException("InvalidLogin");
            }

            //Check if user is active
            if (user.IsBlocked)
            {
                throw new BusinessException("UserInactive");
            }

            UpdateTicketValidity(user.Id);

            model.SecurityToken = Cryptography.Encrypt(JsonConvert.SerializeObject(user.Id), true);
            model.Password      = null;
            model.Language      = BlCode.LoadSingle(user.Id, "Language", user.LanguageId.ToUiString()).Value1;
            model.BranchId      = user.BranchId;
            model.BranchName    = BlBranch.GetBranchName(user.Id);
            model.CrossBranches = BlPermission.CanDo(user.Id, "BRANCH", "CrossBranches");
            model.PageSize      = user.PageSize;
            BlLog.Log(user.Id, Module, "LogIn", "UserSuccessfulLogin", new object[] { user.UserName });
            return(model);
        }
Esempio n. 6
0
        public string LoadUserMenu(long userId, bool forEdit)
        {
            var user = BlUser.LoadSingle(userId);

            //Load all active menu items per company
            var predicate = PredicateBuilder.True <Menu>();

            predicate = predicate.And(p => p.Status);

            //Query all entries without a branch or specific for a branch
            var predicate2 = PredicateBuilder.False <Menu>();

            predicate2 = predicate2.Or(p => p.BranchId == user.BranchId);
            predicate2 = predicate2.Or(p => p.BranchId == null);
            predicate  = predicate.And(predicate2);

            var lMenu = LoadSearch(userId, predicate).ToList();

            //Vaidate if all modules exist in permissions
            var lDeniedMenu = new List <Menu>();

            foreach (var menuItem in lMenu.ToList())
            {
                if (menuItem.Module != null)
                {
                    if (!BlPermission.CanDo(userId, menuItem.Module.Id, "Access"))
                    {
                        //Build the denied menu list
                        lDeniedMenu.Add(menuItem);
                    }
                }
            }

            //Remove unauthorized and broken menu items
            lMenu = (from m in lMenu
                     where !(from dm in lDeniedMenu select dm.Id).Contains(m.Id)
                     select m).ToList();

            //Iterate all sub menu items and clear broken entries
            foreach (var menuItem in lMenu.ToList())
            {
                //Remove each node that does not have a module nor children
                if (menuItem.Module == null)
                {
                    if (menuItem.Parent != null && menuItem.DescriptionCode != null)
                    {
                        if (!lMenu.Where(m => m.Id == menuItem.Parent.Id && m.Module != null && m.DescriptionCode != null).Any())
                        {
                            //Check if any children have this item as parent
                            if (!lMenu.Where(m => m.Parent != null).Where(m => m.Parent.Id == menuItem.Id && m.Module != null && m.DescriptionCode != null).Any())
                            {
                                lDeniedMenu.Add(menuItem);
                            }
                        }
                    }
                }
            }

            //Remove unauthorized and broken menu entries
            lMenu = (from m in lMenu
                     where !(from dm in lDeniedMenu select dm.Id).Contains(m.Id)
                     select m).ToList();


            //Iterate all top menu items and clear broken entries
            foreach (var menuItem in lMenu.Where(m => m.Parent == null).ToList())
            {
                if (menuItem.Module == null)
                {
                    //Remove each node that does not have a module nor children
                    if (!lMenu.Where(m => m.Parent != null).Where(m => m.Parent.Id == menuItem.Id && m.DescriptionCode != null).Any())
                    {
                        lDeniedMenu.Add(menuItem);
                    }
                }
            }

            //Remove unauthorized and broken menu items
            lMenu = (from m in lMenu
                     where !(from dm in lDeniedMenu select dm.Id).Contains(m.Id)
                     select m).ToList();

            var menu = BuildMenuChildren(user, lMenu, null, forEdit);

            return(menu);
        }
Esempio n. 7
0
        public Role Edit(long userId, Role toEdit, string roleUsers = "", string rolePermissions = "")
        {
            using (var tran = new TransactionScope())
            {
                var oldImage = LoadSingle(userId, toEdit.Id, true);
                oldImage.ParentRole = toEdit.ParentRole;
                oldImage.Code       = toEdit.Code;
                var toRet = _repository.Edit(oldImage);

                //Adjust role users
                var arRoleUsers = roleUsers.Split(',');
                var blUser      = new BlUser();
                var allUsers    = blUser.LoadAll(userId);
                foreach (var user in allUsers)
                {
                    if (user.Roles.Where(r => r.Id == toRet.Id).Any() && !arRoleUsers.Contains(user.Id.ToUiString()))
                    {
                        user.Roles.Remove(user.Roles.Where(ur => ur.Id == toRet.Id).First());
                        blUser.Edit(userId, user);
                    }

                    if (!user.Roles.Where(r => r.Id == toRet.Id).Any() && arRoleUsers.Contains(user.Id.ToUiString()))
                    {
                        user.Roles.Add(LoadSingle(userId, toRet.Id));
                        blUser.Edit(userId, user);
                    }
                }

                //Adjust role permissions
                var arRolePermissions = rolePermissions.Split(',');
                var blPermission      = new BlPermission();
                var allPermissions    = blPermission.LoadAll(userId);
                foreach (var permission in allPermissions)
                {
                    if (permission.Roles.Where(r => r.Id == toRet.Id).Any() && !arRolePermissions.Contains(permission.Id.ToUiString()))
                    {
                        permission.Roles.Remove(permission.Roles.Where(rp => rp.Id == toRet.Id).First());
                        blPermission.Edit(userId, permission);
                    }

                    if (!permission.Roles.Where(r => r.Id == toRet.Id).Any() && arRolePermissions.Contains(permission.Id.ToUiString()))
                    {
                        permission.Roles.Add(LoadSingle(userId, toRet.Id));
                        blPermission.Edit(userId, permission);
                    }
                }

                //if (toRet.Users == null)
                //{toRet.Users = new List<User>();}
                //toRet.Users = toRet.Users.ToList();

                //foreach (var permissionUser in toRet.Users)
                //{
                //    var user = BlUser.LoadSingle(Convert.ToInt64(permissionUser.Id));
                //    if (!toRet.Users.Where(u => roleUsers.Split(',').Contains(u.Id.ToUiString())).Any())
                //    {
                //        user.Roles.Remove(user.Roles.Where(ur => ur.Id == toRet.Id).First());
                //        blUser.Edit(userId, user);
                //    }
                //}
                //foreach (var roleUserId in arRoleUser)
                //{
                //    var user = BlUser.LoadSingle(Convert.ToInt64(roleUserId));
                //    if (!toRet.Users.Where(u => u.Id == userId).Any())
                //    {
                //        user.Roles.Remove(user.Roles.Where(r => r.Id == toRet.Id).First());
                //        blUser.Edit(userId, user);
                //    }
                //    else
                //    {
                //        user.Roles.Add(LoadSingle(userId, toRet.Id));
                //        blUser.Edit(userId, user);
                //    }
                //}
                //}

                BlLog.Log(userId, Module, "Edit role", "RoleModified", new object[] { toEdit.Code });
                tran.Complete();
                return(toRet);
            }
        }
Esempio n. 8
0
        public string GetSecurityString(long userId, string path)
        {
            //CLean path url
            path = path.ToUpper().Replace("../STOCK/APP/", "");
            path = path.ToUpper().Replace("/STOCK/APP/", "");

            var toRetList = new ArrayList();

            //Load the module by path
            var predicate = PredicateBuilder.True <Module>();

            predicate = predicate.And(p => p.Path == path);
            var module = LoadSearch(userId, predicate).FirstOrDefault();

            //Create module if does not exist
            if (module == null)
            {
                using (var tran = new TransactionScope())
                {
                    var systemUser = BlUser.LoadSingle(Constants.SystemUser);
                    var newModule  = new Module
                    {
                        Id          = path.Split('/')[path.Split('/').Length - 1].ToUpper().Replace(".HTML", ""),
                        Path        = path,
                        Description = "N/A",
                        Author      = Constants.SystemUser,
                        Status      = "A"
                    };
                    newModule = Create(userId, newModule);

                    //Create first access permission and assign to system admin
                    var newPermission = new Permission
                    {
                        Module = newModule,
                        Code   = "Access",
                        Status = "A",
                        Roles  =
                            BlRole.LoadSingle(userId, Constants.FullAdminRole).
                            SingleItemAsEnumerable().ToList()
                    };
                    var blPermission = new BlPermission();
                    blPermission.Create(userId, newPermission);
                    tran.Complete();
                }
            }

            //Get module permissions if exists
            if (module != null)
            {
                var blPermission = new BlPermission();
                var permissions  = blPermission.LoadByModule(userId, module.Id, true);

                //Check each permission status
                foreach (var permission in permissions)
                {
                    if (BlPermission.CanDo(userId, module.Id, permission.Code))
                    {
                        toRetList.Add(permission.Code);
                    }
                }
            }

            return(string.Join(":", toRetList.ToArray()));
        }