Example #1
0
        //private AssignedPermissionDTO GetAssignedPermissions(MyProjectEntities context, IQueryable<OrganizationPost> posts, SecurityObject securityObject, bool withChildObjects, List<SecurityAction> parentActions = null)
        //{
        //    AssignedPermissionDTO result = new AssignedPermissionDTO();
        //    var permissions = GetPersmissionByPosts(context, posts, securityObject, (parentActions == null));
        //    result.SecurityObjectID = securityObject.ID;
        //    if (permissions != null && permissions.Count > 0)
        //    {
        //        foreach (var permission in permissions)
        //        {
        //            result.GrantedActions.Add(permission);
        //        }
        //    }
        //    if (parentActions != null && parentActions.Count > 0)
        //    {
        //        foreach (var parentAction in parentActions)
        //        {
        //            bool add = false;
        //            if (parentAction == SecurityAction.NoAccess)
        //            {
        //                if (!result.GrantedActions.Any(x => x != SecurityAction.NoAccess))
        //                {
        //                    add = true;
        //                }
        //            }
        //            else if (parentAction == SecurityAction.ReadOnly)
        //            {
        //                if (!result.GrantedActions.Any(x => x != SecurityAction.ReadOnly))
        //                {
        //                    add = true;
        //                }
        //            }
        //            else
        //            {
        //                if (!result.GrantedActions.Any(x => x == SecurityAction.NoAccess
        //                || x == SecurityAction.ReadOnly))
        //                {
        //                    add = true;
        //                }
        //            }
        //            if (add)
        //            {
        //                if (!result.GrantedActions.Any(x => x == parentAction))
        //                    result.GrantedActions.Add(parentAction);
        //            }
        //        }
        //    }

        //    if (!withChildObjects)
        //    {
        //        return result;
        //    }
        //    else
        //    {


        //    }



        //    return result;

        //}
        private List <SecurityObject> GetChildObjects(SecurityObject securityObject)
        {
            List <SecurityObject>  result = null;
            DatabaseObjectCategory type   = (DatabaseObjectCategory)securityObject.Type;

            if (type == DatabaseObjectCategory.Database)
            {
                result = securityObject.DatabaseInformation.DBSchema.Select(x => x.SecurityObject).ToList();
            }
            else if (type == DatabaseObjectCategory.Schema)
            {
                result = securityObject.DatabaseInformation.DBSchema.Select(x => x.SecurityObject).ToList();
            }
            else if (type == DatabaseObjectCategory.Entity)
            {//گزارش و ستون چی؟
                if (securityObject.TableDrivedEntity.TableDrivedEntity_Columns.Any())
                {
                    result = securityObject.TableDrivedEntity.TableDrivedEntity_Columns.Select(x => x.Column.SecurityObject).ToList();
                }
                else
                {
                    result = securityObject.TableDrivedEntity.Table.Column.Select(x => x.SecurityObject).ToList();
                }

                result.AddRange(securityObject.TableDrivedEntity.Relationship.Select(x => x.SecurityObject).ToList());
            }
            return(result);
        }
Example #2
0
        //private bool? UserHasPermission(MyProjectEntities context, int userID, string ActionName, Object dbObject)
        //{
        //    var user = context.Users.First(x => x.ID == userID);
        //    foreach (var role in user.Roles)
        //    {

        //        var bFound = (role.Role_Action_Object.Any(
        //                      p => (ActionName == "any" || p.Action.ActionName == ActionName) && p.ObjectID == dbObject.ID));
        //        if (bFound)
        //            return true;
        //        else
        //        {
        //            if (dbObject.NeedsExplicitPermission == true)
        //                return false;
        //            else
        //            {
        //                if (dbObject.ParentID != null)
        //                    return UserHasPermission(context, userID, ActionName, dbObject.Object2);
        //                else
        //                    return false;
        //            }
        //        }
        //    }
        //    return false;
        //}

        //////public bool UserHasRole(int userID, string roleName)
        //////{
        //////    var context = new MyProjectEntities();
        //////    var user = context.Users.First(x => x.ID == userID);
        //////    return user.Roles.Any(p => p.RoleName == roleName);
        //////}

        //public bool? PermissionGranted(List<int> roleIds, string actionName, string objectIdentity, string objectCategory)
        //{


        //}
        public List <ImposePermissionResult> ObjectsHaveSpecificPermissions(DR_Requester requester, List <int> securityObjectIDs, List <SecurityAction> actionNames)
        {
            List <ImposePermissionResult> result = new List <ImposePermissionResult>();

            using (var context = new MyProjectEntities())
            {
                //var user = context.Users.First(x => x.ID == requester.Identity);
                IQueryable <OrganizationPost> organizationPosts = GetDBOrganizationPosts(context, requester);



                foreach (var securityObjectID in securityObjectIDs)
                {
                    SecurityObject securityObject = context.SecurityObject.First(x => x.ID == securityObjectID);

                    var permissoins             = GetPersmissionByPosts(context, organizationPosts, securityObject);
                    ImposePermissionResult item = new ImposePermissionResult();
                    item.Permitted        = permissoins.Any(x => actionNames.Contains(x));
                    item.ObjectSecurityID = securityObjectID;
                    result.Add(item);
                    //if (actionName == SecurityAction.Any)
                    //    item.Permitted = permissoins.Any();
                    //else
                    //    item.Permitted = permissoins.Any(x => x.Action == actionName);
                }
                //    if (dbObject != null)
                //        return UserHasPermission(context, requester.Identity, ActionName, dbObject);
                //    else
                //        return null;
            }
            return(result);
        }
        /// <summary>
        ///     The get identity.
        /// </summary>
        /// <param name="username">
        ///     The username.
        /// </param>
        /// <returns>
        ///     The <see cref="UserIdentity" />.
        /// </returns>
        internal static UserIdentity GetIdentity(string username)
        {
            using (var context = new OnlineFilesEntities())
            {
                username = Principal.GetLogin(username);
                var userIdentity = new UserIdentity();

                // Get the SecurityObject being requested.
                SecurityObject userProfile = context.GetUserValidation(username, ConfigurationManager.AppSettings["LDAP_SETTING"]).FirstOrDefault();
                if (userProfile == null)
                {
                    throw new Exception("User Not Found");
                }
                userProfile._MySecurityGroups = context.GetSecurityTokens(userProfile.SecurityObjectId).ToList();
                context.SaveChanges();
                if (userProfile.HomeFolder == null)
                {
                    Folder homeFolder = Folder.Create(userProfile.FullName, new Guid(), userProfile, true, true);
                    userProfile.HomeFolder = homeFolder.pk_FolderId;
                    context.SaveChanges();
                }
                // Ensure that the SecurityObject's Permissions are loaded.
                context.Entry(userProfile).Collection(so => so.SecurityObjectPermissions).Query().Include(sop => sop.Permission).Load();
                userIdentity.LoadUser(userProfile);
                return(userIdentity);
            }
        }
Example #4
0
        /// <summary>
        /// 保存用户信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSaveRoleInfo_Click(object sender, EventArgs e)
        {
            string roleName = this.txtRoleName.Text.Trim().Replace("'", "''");
            string roleDesc = this.txtRoleDescri.Text.Trim().Replace("'", "''");

            ArrayList secObjs = new ArrayList(20);

            foreach (DataListItem item in this.functionList.Items)
            {
                CheckBox chk = item.FindControl("roleChk") as CheckBox;

                if (chk.Checked)
                {
                    Guid            funid  = new Guid(this.functionList.DataKeys[item.ItemIndex].ToString());
                    ISecurityObject secObj = new SecurityObject(funid, SecurityObjectType.Function);
                    secObjs.Add(secObj);
                }
            }

            //New Role
            if (this.hiRoleId.Value == string.Empty)
            {
                IRole role = Role.NewRole(CurrentGroupId,
                                          roleName,
                                          roleDesc,
                                          (SecurityObject[])secObjs.ToArray(typeof(SecurityObject)),
                                          OperatorMethod.Access);

                if (role != null)
                {
                    rolePan.Visible = false;
                    BindRoleList();
                    ShowMessage("新建角色成功");
                }
                else
                {
                    ShowMessage("新建角色失败");
                }
            }
            else//Modify Role
            {
                if (Role.ModifyRole(roleName,
                                    roleDesc,
                                    new Guid(this.hiRoleId.Value),
                                    (SecurityObject[])secObjs.ToArray(typeof(SecurityObject)),
                                    OperatorMethod.Access))
                {
                    rolePan.Visible = false;
                    BindRoleList();
                    ShowMessage("修改用户角色成功");
                }
                else
                {
                    ShowMessage("修改用户角色失败");
                }
            }
        }
Example #5
0
 public static void setPassword(string pwd)
 {
     using (var db = new LiteDatabase(dbSec))
     {
         var rec = db.GetCollection <SecurityObject>(SecurityObject.CollectionName);
         // rec.DeleteAll();
         SecurityObject dmy = new SecurityObject();
         dmy.setPassword(pwd);
         rec.Insert(dmy);
     }
 }
Example #6
0
        protected void Page_Load(object sender, EventArgs e)
        {
            PageBar1.PageSize = NowPageCount(); // UIBiz.CommonInfo.PageCount;
            PageBar2.PageSize = NowPageCount(); //UIBiz.CommonInfo.PageCount;

            isChangePageSize = this.Search_ReSetPageSize1.isChangePageSize;

            string showCata = Request.QueryString["showCata"] == null ? "" : Request.QueryString["showCata"];

            this.catalogID = Request.QueryString["CatalogID"] == null ? "00000000-0000-0000-0000-000000000000" : Request.QueryString["CatalogID"].ToString();



            //分类检索
            if (showCata == "1")
            {
                List <ObjectRule> rules       = new List <ObjectRule>(1);
                ISecurityObject   securityObj = new SecurityObject(new Guid(this.catalogID), SecurityObjectType.Items);
                ObjectRule        or          = new ObjectRule(securityObj, new User(CurrentUser.UserId), OperatorMethod.Deny);
                rules.Add(or);
                ObjectRule.CheckRules(rules);

                // if (!Catalog.GetCataRight(CurrentUser.UserId, new Guid(this.catalogID)))
                if (rules[0].IsValidate)
                {
                    ShowMessage("您没有权限浏览此分类!");
                    Response.Redirect(FormsAuthentication.DefaultUrl, true);
                }

                //    this.cataNav.Visible = true;

                this.BindCataNav();
            }
            //关键字或高级搜索
            else
            {
                this.keyword   = Request.QueryString["keyword"] == null ? "" : Request.QueryString["keyword"].ToString();
                this.keyword   = Server.UrlDecode(this.keyword);
                this.beginDate = Request.QueryString["BeginDate"].ToString(); //上传时间起始日期
                this.endDate   = Request.QueryString["EndDate"].ToString();   //上传时间结束日期
                //     this.cataNav.Visible = false; ;
            }

            if (isChangePageSize == "1")
            {
                this.Search_ReSetPageSize1.isChangePageSize = string.Empty;
                _curpage = 0;
            }
            if (!Page.IsPostBack || isChangePageSize == "1")
            {
                BindData(PageBar1.PageSize, _curpage);
            }
        }
Example #7
0
        protected void btnSearchUser_Click(object sender, EventArgs e)
        {
            QJVRMS.Business.Group userGroup = new QJVRMS.Business.Group(CurrentGroupId);
            DataTable             dt        = userGroup.SelectUsers(this.txtloginName.Text.Trim(), this.txtUserName.Text.Trim());



            Hashtable userRules = new Hashtable();
            Dictionary <int, string> methodDict = WebUI.UIBiz.CommonInfo.GetMethodDict();

            foreach (DataRow row in dt.Rows)
            {
                ISecurityObject   securityObj = new SecurityObject(new Guid(this.hiCurrentCataId.Value), SecurityObjectType.Items);
                List <ObjectRule> rules       = new List <ObjectRule>();
                User user = new User(new Guid(row["userId"].ToString()));

                foreach (KeyValuePair <int, string> methodEntry in methodDict)
                {
                    OperatorMethod method = (OperatorMethod)((int)methodEntry.Key);
                    ObjectRule     rule   = new ObjectRule(securityObj, user, method);

                    rules.Add(rule);
                }

                userRules.Add(user, rules);

                ObjectRule.CheckRules(rules);
            }


            foreach (KeyValuePair <int, string> methodEntry in methodDict)
            {
                string mIndex = methodEntry.Key.ToString();
                dt.Columns.Add(mIndex, typeof(bool));
            }

            foreach (DictionaryEntry entry in userRules)
            {
                User user = entry.Key as User;
                List <ObjectRule> rules = entry.Value as List <ObjectRule>;

                DataRow[] users = dt.Select("userId='" + user.UserId.ToString() + "'");

                foreach (IRule rule in rules)
                {
                    string methodKey = ((int)rule.Method).ToString();
                    users[0][methodKey] = rule.IsValidate;
                }
            }

            this.userList.DataSource = dt;
            this.userList.DataBind();
        }
Example #8
0
        protected void rptCategoryTop_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                Repeater rptCatalogChild = (Repeater)e.Item.FindControl("rptCategoryChild");


                DataRowView rowv = (DataRowView)e.Item.DataItem;
                //提取分类ID
                string CategorieId = Convert.ToString(rowv["CatalogID"]);
                //根据分类ID查询该分类下的产品,并绑定产品Repeater
                rptCatalogChild.DataSource = Catalog.GetCatalogTableByParentId(new Guid(CategorieId));
                rptCatalogChild.DataBind();

                HiddenField hf = (HiddenField)e.Item.FindControl("topCatId");
                hf.Value = CategorieId;



                Role role = new Role(new Guid(this.hiRoleId.Value));

                Guid            catId       = new Guid(CategorieId);
                ISecurityObject securityObj = new SecurityObject(catId, SecurityObjectType.Items);

                CheckBox       chb    = (CheckBox)e.Item.FindControl("funTopReadChk");
                OperatorMethod method = OperatorMethod.Deny;
                ObjectRule     rule   = new ObjectRule(securityObj, role, method);
                rule.CheckValidate();
                chb.Checked = rule.IsValidate;

                chb    = (CheckBox)e.Item.FindControl("funTopUpChk");
                method = OperatorMethod.Write;
                rule   = new ObjectRule(securityObj, role, method);
                rule.CheckValidate();
                chb.Checked = rule.IsValidate;

                chb    = (CheckBox)e.Item.FindControl("funTopEditChk");
                method = OperatorMethod.Modify;
                rule   = new ObjectRule(securityObj, role, method);
                rule.CheckValidate();
                chb.Checked = rule.IsValidate;

                chb    = (CheckBox)e.Item.FindControl("funTopDownChk");
                method = OperatorMethod.Download;
                rule   = new ObjectRule(securityObj, role, method);
                rule.CheckValidate();
                chb.Checked = rule.IsValidate;
            }
        }
Example #9
0
 private static void DownloadAdsGroups()
 {
     using (var context = new OnlineFilesEntities())
         using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
             using (var groupPrincipal = new GroupPrincipalEx(ctx))
                 using (PrincipalSearcher search = new PrincipalSearcher(groupPrincipal))
                 {
                     int max = search.FindAll().Count();
                     int c   = 0;
                     foreach (var gp in search.FindAll().Select(found => found as GroupPrincipalEx))
                     {
                         Console.WriteLine("Processing " + c + " of " + max);
                         c++;
                         if (gp != null)
                         {
                             if (gp.IsSecurityGroup != true && gp.GroupScope == GroupScope.Local)
                             {
                                 continue;
                             }
                             var so = context.SecurityObjects.FirstOrDefault(d => d.ActiveDirectoryId == gp.Guid);
                             if (so == null)
                             {
                                 so = new SecurityObject
                                 {
                                     ActiveDirectoryId = gp.Guid,
                                     FullName          = gp.Name,
                                     Username          = gp.SamAccountName,
                                     EmailAddress      = gp.EmailAddress ?? "",
                                     IsGroup           = true,
                                     LastLogInOn       = DateTime.Now,
                                     IsActive          = true,
                                     HomeFolder        = null
                                 };
                                 context.SecurityObjects.Add(so);
                             }
                             else
                             {
                                 so.IsGroup      = true;
                                 so.FullName     = gp.Name;
                                 so.Username     = gp.SamAccountName;
                                 so.EmailAddress = gp.EmailAddress ?? "";
                             }
                         }
                         context.SaveChanges();
                     }
                 }
 }
Example #10
0
        public BusinessMessageResponse AddSecurityObjectList(SaveListRequest<SecurityObjectInfo> SecurityObjectInfo)
        {
            var response = new BusinessMessageResponse();

            try {

                List<SecurityObject> allSecurityObjects = GetAllSecurityObjectList(true).List;

                SaveListRequest<SecurityObject> saveRq = new SaveListRequest<SecurityObject>();
                saveRq.List = new List<SecurityObject>();

                foreach (SecurityObjectInfo pti in SecurityObjectInfo.List) {

                    Predicate<SecurityObject> find = new Predicate<SecurityObject>(
                        delegate(SecurityObject match) {
                            return match.DisplayName == pti.Name;
                        });

                    SecurityObject found = allSecurityObjects.Find(find);

                    if (found == null) {
                        // this Security Object doesn't exist, add it

                        SecurityObject newObject = new SecurityObject();

                        newObject.DisplayName = pti.Name;
                        newObject.ParentID = findSecurityObjectParentId(pti.Parent, ref allSecurityObjects);

                        saveRq.List.Add(newObject);
                    }
                    else {
                        // this Security Object does exist
                    }
                }

                response = SaveSecurityObjectList(saveRq);
            }
            catch (Exception ex) {
                return ErrorHandler.Handle(ex);
            }

            return response;
        }
Example #11
0
        private List <Tuple <int, SecurityAction> > GetPersmissionByPost(MyProjectEntities context, SecuritySubject securitySubject, SecurityObject securityObject, int level, bool goUpward = true, List <Tuple <int, SecurityAction> > distantactions = null)
        {
            if (distantactions == null)
            {
                distantactions = new List <Tuple <int, SecurityAction> >();
            }
            //کش شود cache
            //if(cachedItem!=null)


            var actions = GetAssignedPermissions(context, securityObject, securitySubject);

            foreach (var action in actions)
            {
                distantactions.Add(new Tuple <int, SecurityAction>(level, action));
            }

            if (goUpward == true)
            {
                SecurityObject parentSecurityObject = null;
                var            type = (DatabaseObjectCategory)securityObject.Type;
                if (type == DatabaseObjectCategory.Schema)
                {
                    parentSecurityObject = securityObject.DBSchema.DatabaseInformation.SecurityObject;
                }
                else if (type == DatabaseObjectCategory.Entity)
                {
                    parentSecurityObject = securityObject.TableDrivedEntity.Table.DBSchema.SecurityObject;
                }
                //else if (securityObject.ColumnID != null)
                //    parentSecurityObject = securityObject.Column..Table.DBSchema.SecurityObject.First();
                if (parentSecurityObject != null)
                {
                    GetPersmissionByPost(context, securitySubject, parentSecurityObject, level + 1, goUpward, distantactions);
                }
                //else
                //     return new List<ActionDTO>();
            }



            return(distantactions);
        }
 /// <summary>
 ///     The load user.
 /// </summary>
 /// <param name="data">
 ///     The data.
 /// </param>
 private void LoadUser(SecurityObject data)
 {
     if (data != null)
     {
         UserId             = data.SecurityObjectId;
         Name               = data.Username;
         IsAuthenticated    = true;
         AuthenticationType = "Membership";
         Permissions.AddRange(data.SecurityObjectPermissions.Select(sop => sop.Permission).ToList());
         UserProfile = data;
     }
     else
     {
         Name               = string.Empty;
         IsAuthenticated    = false;
         AuthenticationType = string.Empty;
         Permissions        = new List <Permission>();
         UserProfile        = new SecurityObject();
     }
 }
Example #13
0
        /// <summary>
        /// 判断某个用户对某个资源是否具有某个操作权限
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="resourceId"></param>
        /// <returns></returns>
        public bool IsUserResource(Guid userId, Guid resourceId, int method)
        {
            bool              _b     = false;
            DataSet           ds     = this.GetResourceCatalogByItemId(resourceId.ToString());
            int               icount = ds.Tables[0].Rows.Count;
            List <ObjectRule> rules  = new List <ObjectRule>(icount);

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                ISecurityObject securityObj = new SecurityObject(new Guid(dr["CatalogId"].ToString()), SecurityObjectType.Items);
                ObjectRule      or          = new ObjectRule(securityObj, new User(userId), (OperatorMethod)method);
                rules.Add(or);
            }
            ObjectRule.CheckRules(rules);
            foreach (ObjectRule obj in rules)
            {
                _b = _b || obj.IsValidate;
            }
            return(_b);
        }
Example #14
0
        //private IQueryable<ConditionalPermission> GetConditionalPermissions(MyProjectEntities context, int entityID, int securitySubjectID)
        //{
        //    return
        //}

        public AssignedPermissionDTO GetAssignedPermissions(DR_Requester requester, int securityObjectID, bool withChildObjects)
        {
            AssignedPermissionDTO result = new AssignedPermissionDTO();

            //var cachedItem = CacheManager.GetCacheManager().GetCachedItem(CacheItemType.Permission, requester.Identity.ToString(), securityObjectID.ToString(), withChildObjects.ToString());
            //if (cachedItem != null)
            //    return (cachedItem as AssignedPermissionDTO);
            using (var context = new MyProjectEntities())
            {
                SecurityObject securityObject = context.SecurityObject.First(x => x.ID == securityObjectID);

                var organizationPosts = GetDBOrganizationPosts(context, requester);
                //if (organizationPosts.Any(x => x.OrganizationType_RoleType.RoleType.IsSuperAdmin == true))
                //    requester.SkipSecurity = true;
                if (requester.SkipSecurity == true)
                {
                    result.GrantedActions.Add(SecurityAction.ArchiveEdit);
                    result.GrantedActions.Add(SecurityAction.LetterEdit);
                    //result.GrantedActions.Add(SecurityAction.ArchiveMenuAccess);
                    result.GrantedActions.Add(SecurityAction.EditAndDelete);
                    //result.GrantedActions.Add(SecurityAction.MenuAccess);
                }
                else
                {
                    var allowedActions = GetPersmissionByPosts(context, organizationPosts, securityObject, true);
                    result.GrantedActions   = allowedActions;
                    result.SecurityObjectID = securityObjectID;
                }
                if (withChildObjects)
                {
                    var childObjects = GetChildObjects(securityObject);
                    if (childObjects != null)
                    {
                        SetChildPermissions(requester, context, result, childObjects, organizationPosts);
                    }
                }
                // result = GetAssignedPermissions(context, organizationPosts, securityObject, withChildObjects);
            }
            CacheManager.GetCacheManager().AddCacheItem(result, CacheItemType.Permission, requester.Identity.ToString(), securityObjectID.ToString(), withChildObjects.ToString());
            return(result);
        }
Example #15
0
        protected void rptCategoryChild_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                DataRowView rowv        = (DataRowView)e.Item.DataItem;
                string      CategorieId = Convert.ToString(rowv["CatalogID"]);
                Role        role        = new Role(new Guid(this.hiRoleId.Value));

                HiddenField hf = (HiddenField)e.Item.FindControl("childCatId");
                hf.Value = CategorieId;

                Guid            catId       = new Guid(CategorieId);
                ISecurityObject securityObj = new SecurityObject(catId, SecurityObjectType.Items);

                CheckBox       chb    = (CheckBox)e.Item.FindControl("funChildReadChk");
                OperatorMethod method = OperatorMethod.Deny;
                ObjectRule     rule   = new ObjectRule(securityObj, role, method);
                rule.CheckValidate();
                chb.Checked = rule.IsValidate;

                chb    = (CheckBox)e.Item.FindControl("funChildUpChk");
                method = OperatorMethod.Write;
                rule   = new ObjectRule(securityObj, role, method);
                rule.CheckValidate();
                chb.Checked = rule.IsValidate;

                chb    = (CheckBox)e.Item.FindControl("funChildEditChk");
                method = OperatorMethod.Modify;
                rule   = new ObjectRule(securityObj, role, method);
                rule.CheckValidate();
                chb.Checked = rule.IsValidate;

                chb    = (CheckBox)e.Item.FindControl("funChildDownChk");
                method = OperatorMethod.Download;
                rule   = new ObjectRule(securityObj, role, method);
                rule.CheckValidate();
                chb.Checked = rule.IsValidate;
            }
        }
Example #16
0
        public AssignedPermissionDTO GetSubSystemAssignedPermissions(DR_Requester requester, string objectName)
        {
            AssignedPermissionDTO result = new AssignedPermissionDTO();
            var cachedItem = CacheManager.GetCacheManager().GetCachedItem(CacheItemType.Permission, requester.Identity.ToString(), objectName);

            if (cachedItem != null)
            {
                return(cachedItem as AssignedPermissionDTO);
            }
            using (var context = new MyProjectEntities())
            {
                var            organizationPosts = GetDBOrganizationPosts(context, requester);
                SecurityObject securityObject    = context.SubSystems.FirstOrDefault(x => x.Name == objectName)?.SecurityObject;
                if (securityObject != null)
                {
                    var allowedActions = GetPersmissionByPosts(context, organizationPosts, securityObject, true);
                    result.GrantedActions   = allowedActions;
                    result.SecurityObjectID = securityObject.ID;
                }
            }
            CacheManager.GetCacheManager().AddCacheItem(result, CacheItemType.Permission, requester.Identity.ToString(), objectName);
            return(result);
        }
Example #17
0
        private SecurityObjectDTO ToSecurityObjectDTO(SecurityObject item)
        {
            SecurityObjectDTO result = new SecurityObjectDTO();

            result.ID   = item.ID;
            result.Type = (DatabaseObjectCategory)item.Type;
            if (result.Type == DatabaseObjectCategory.Database)
            {
                result.Name = item.DatabaseInformation.Name;
            }
            else if (result.Type == DatabaseObjectCategory.Schema)
            {
                result.Name = item.DBSchema.Name;
            }
            else if (result.Type == DatabaseObjectCategory.Relationship)
            {
                result.Name = item.Relationship.Name;
            }
            else if (result.Type == DatabaseObjectCategory.Entity)
            {
                result.Name = item.TableDrivedEntity.Name;
            }
            else if (result.Type == DatabaseObjectCategory.Column)
            {
                result.Name = item.Column.Name;
            }
            else if (result.Type == DatabaseObjectCategory.Report)
            {
                result.Name = item.EntityReport.Title;
            }
            else if (result.Type == DatabaseObjectCategory.Command)
            {
                result.Name = item.EntityCommand.Title;
            }
            return(result);
        }
Example #18
0
        private void RenderPrivileges(SecurityObject secObject, RadTabItem tabItem)
        {
            int rowHeight = 20;
            int rowIndex = 0;
            tabItem.Style = (Style)Application.Current.Resources["InnerTabItem"];

            ScrollViewer sv = new ScrollViewer();
            sv.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
            sv.HorizontalScrollBarVisibility = ScrollBarVisibility.Hidden;
            //sv.Margin = new Thickness(3);
            sv.Background = (SolidColorBrush)Application.Current.Resources["PanelDarkBackground"];
            sv.BorderBrush = (SolidColorBrush)Application.Current.Resources["PanelDarkBackground"];

            Grid grid = new Grid();

            grid.Background = (SolidColorBrush)Application.Current.Resources["PanelDarkBackground"];
            sv.Content = grid;

            tabItem.Content = sv;
            foreach (var privilege in mPrivileges)
            {

                grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(rowHeight) });
                CheckBox checkBox = new CheckBox();
                grid.Children.Add(checkBox);

                checkBox.Content = privilege.Name;
                Grid.SetRow(checkBox, rowIndex);
                Grid.SetColumn(checkBox, 0);
                rowIndex++;

                RolePrivilegeViewModel rolePrivilegeViewModel;

                //Check set privileges
                var rolePrivilege = mRole.RolePrivileges.FirstOrDefault(x => x.SecObjectId == secObject.Id && x.PrivilegeId == privilege.Id);

                if (rolePrivilege != null)
                {
                    rolePrivilegeViewModel = new RolePrivilegeViewModel(rolePrivilege);
                    rolePrivilegeViewModel.HasAccess = true;
                }
                else
                {
                    rolePrivilege = new RolePrivilege();
                    rolePrivilege.RoleId = mRoleId;
                    rolePrivilege.SecObjectId = secObject.Id;
                    rolePrivilege.PrivilegeId = privilege.Id;

                    rolePrivilegeViewModel = new RolePrivilegeViewModel(rolePrivilege);
                    rolePrivilegeViewModel.HasAccess = false;
                }

                mRolePrivilegesViewModel.Add(rolePrivilegeViewModel);

                //Bind
                System.Windows.Data.Binding checkBoxBinding = new System.Windows.Data.Binding("HasAccess");
                checkBoxBinding.Mode = System.Windows.Data.BindingMode.TwoWay;
                checkBoxBinding.Source = rolePrivilegeViewModel;
                checkBox.SetBinding(CheckBox.IsCheckedProperty, checkBoxBinding);
            }
        }
Example #19
0
    public bool SetRules(string rulesStr, string secObjStr, string opersStr)
    {
        SerializeObjectFactory sof = new SerializeObjectFactory();

        List <ObjectRule> rules  = (List <ObjectRule>)sof.DesializeFromBase64(rulesStr);
        SecurityObject    secObj = (SecurityObject)sof.DesializeFromBase64(secObjStr);
        ArrayList         opers  = (ArrayList)sof.DesializeFromBase64(opersStr);


        string sqlRuleFormat = "insert into AccessControlLIst (ObjectId,ObjectType,OperatorId,OperatorMethod)"
                               + " values ('{0}',{1},'{2}',{3});";
        StringBuilder sqlBuilder = new StringBuilder();

        sqlBuilder.Append("Begin Tran Begin try {0}");


        string        sqlRuleDelFormat = "Delete from AccessControlLIst Where ObjectId='{0}' and OperatorId='{1}' and OperatorMethod={2};";
        StringBuilder sqlDelBuilder    = new StringBuilder();


        //  if (rules.Count != 0)
        //  {
        foreach (ObjectRule rule in rules)
        {
            string sqlTemp = string.Empty;

            string objId   = rule.SecurityObject.ObjectId.ToString();
            string objType = ((int)rule.SecurityObject.ObjectType).ToString();

            string operId = rule.Operator.OperatorId.ToString();
            string method = ((int)rule.Method).ToString();

            if (rule.IsValidate)
            {
                sqlTemp = string.Format(sqlRuleFormat, objId, objType, operId, method);
                sqlBuilder.Append(sqlTemp);


                sqlTemp = string.Format(sqlRuleDelFormat, objId, operId, method);
                sqlDelBuilder.Append(sqlTemp);
            }
            else
            {
                sqlTemp = string.Format(sqlRuleDelFormat, objId, operId, method);
                sqlDelBuilder.Append(sqlTemp);
            }
        }
        // }
        //else
        //{
        //    foreach (IOperator oper in opers)
        //    {
        //        sqlDelBuilder.Append(string.Format(sqlRuleDelFormat, secObj.ObjectId.ToString(), oper.OperatorId.ToString()));
        //    }

        //}


        sqlBuilder.Append(" Commit End Try Begin Catch  IF @@TRANCOUNT > 0 Rollback DECLARE @ErrMsg nvarchar(4000), @ErrSeverity int"
                          + " SELECT @ErrMsg = ERROR_MESSAGE(),"
                          + " @ErrSeverity = ERROR_SEVERITY()"
                          + " RAISERROR(@ErrMsg, @ErrSeverity, 1)"
                          + " End Catch");

        string finalSql = sqlBuilder.ToString();

        finalSql = string.Format(finalSql, sqlDelBuilder.ToString());

        try
        {
            SqlHelper.ExecuteNonQuery(CommonInfo.ConQJVRMS, CommandType.Text, finalSql);
            return(true);
        }
        catch (Exception ex)
        {
            LogWriter.WriteExceptionLog(ex);
            return(false);
        }
    }
        public object CreateRealObject(IModel model, ISecurityObjectRepository securityObjectRepository)
        {
            Type targetType = SecurityObject.GetType();

            RealObject = Activator.CreateInstance(SecurityObject.GetType());
            IEntityType entityType = model.FindEntityType(targetType);
            IEnumerable <PropertyInfo> properiesInfo = targetType.GetRuntimeProperties();
            IEnumerable <INavigation>  navigations   = entityType.GetNavigations();

            IReadOnlyList <IProperty> primaryKeyProperties = entityType.FindPrimaryKey().Properties;

            foreach (PropertyInfo propertyInfo in properiesInfo)
            {
                object defaultValue = propertyInfo.GetValue(RealObject);
                defaultValueDictionary[propertyInfo.Name] = defaultValue;
                if (navigations.Any(p => p.Name == propertyInfo.Name))
                {
                    INavigation navigation = navigations.First(p => p.Name == propertyInfo.Name);
                    if (navigation.IsCollection())
                    {
                        IClrCollectionAccessor collectionAccessor              = navigation.GetCollectionAccessor();
                        IEnumerable            realObjectListPropertyValue     = (IEnumerable)propertyInfo.GetValue(RealObject);
                        IEnumerable            securityObjectListPropertyValue = (IEnumerable)propertyInfo.GetValue(SecurityObject);
                        if (securityObjectListPropertyValue != null && realObjectListPropertyValue != null)
                        {
                            foreach (object objectInListProperty in securityObjectListPropertyValue)
                            {
                                SecurityObjectBuilder metadata = securityObjectRepository.GetObjectMetaData(objectInListProperty);
                                if (metadata == null)
                                {
                                    metadata = new SecurityObjectBuilder();
                                    securityObjectRepository.RegisterBuilder(metadata);
                                    metadata.SecurityObject = objectInListProperty;
                                    metadata.CreateRealObject(model, securityObjectRepository);
                                }
                                collectionAccessor.Add(RealObject, metadata.RealObject);
                            }
                        }
                    }
                    else
                    {
                        object realValue = propertyInfo.GetValue(SecurityObject);
                        if (!Equals(realValue, null))
                        {
                            SecurityObjectBuilder metadata = securityObjectRepository.GetObjectMetaData(realValue);
                            if (metadata == null)
                            {
                                metadata = new SecurityObjectBuilder();
                                securityObjectRepository.RegisterBuilder(metadata);
                                metadata.SecurityObject = realValue;

                                metadata.CreateRealObject(model, securityObjectRepository);
                            }
                            if (propertyInfo.SetMethod != null)
                            {
                                propertyInfo.SetValue(RealObject, metadata.RealObject);
                            }
                        }
                    }
                }
                else
                {
                    bool isGeneratedPrimaryKey = false;
                    foreach (IProperty primaryKeyProperty in primaryKeyProperties)
                    {
                        if ((propertyInfo.Name == primaryKeyProperty.Name) && primaryKeyProperty.RequiresValueGenerator)
                        {
                            isGeneratedPrimaryKey = true;
                        }
                    }
                    if (propertyInfo.SetMethod != null && !isGeneratedPrimaryKey)
                    {
                        object securityValue = propertyInfo.GetValue(SecurityObject);
                        propertyInfo.SetValue(RealObject, securityValue);
                    }
                }
            }
            return(RealObject);
        }
 public WebDavSqlStoreItemLockInstance(SecurityObject so, string path, WebDavLockScope lockscope, WebDavLockType locktype, string owner, double?requestedlocktimeout, Guid?token, XmlDocument requestdocument, int depth, IWebDavStoreItemLock lockSystem, DateTime?createdate = null)
     : base(path, lockscope, locktype, owner, requestedlocktimeout, token, requestdocument, depth, lockSystem, createdate)
 {
     SoOwner = so;
 }
 private static void DownloadAdsGroups()
 {
     using (var context = new OnlineFilesEntities())
     using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
     using (var groupPrincipal = new GroupPrincipalEx(ctx))
     using (PrincipalSearcher search = new PrincipalSearcher(groupPrincipal))
     {
         int max = search.FindAll().Count();
         int c = 0;
         foreach (var gp in search.FindAll().Select(found => found as GroupPrincipalEx))
         {
             Console.WriteLine("Processing " + c + " of " + max);
             c++;
             if (gp != null)
             {
                 if (gp.IsSecurityGroup != true && gp.GroupScope == GroupScope.Local)
                     continue;
                 var so = context.SecurityObjects.FirstOrDefault(d => d.ActiveDirectoryId == gp.Guid);
                 if (so == null)
                 {
                     so = new SecurityObject
                     {
                         ActiveDirectoryId = gp.Guid,
                         FullName = gp.Name,
                         Username = gp.SamAccountName,
                         EmailAddress = gp.EmailAddress ?? "",
                         IsGroup = true,
                         LastLogInOn = DateTime.Now,
                         IsActive = true,
                         HomeFolder = null
                     };
                     context.SecurityObjects.Add(so);
                 }
                 else
                 {
                     so.IsGroup = true;
                     so.FullName = gp.Name;
                     so.Username = gp.SamAccountName;
                     so.EmailAddress = gp.EmailAddress ?? "";
                 }
             }
             context.SaveChanges();
         }
     }
 }
Example #23
0
        private List <SecurityAction> GetAssignedPermissions(MyProjectEntities context, SecurityObject securityObject, SecuritySubject securitySubject)
        {
            //var cachedItem = CacheManager.GetCacheManager().GetCachedItem(CacheItemType.Permission, securitySubject.ID + "_" + securityObject.ID);
            //if (cachedItem != null)
            //    return cachedItem as List<SecurityAction>;
            List <SecurityAction> result = new List <SecurityAction>();
            //RoleType roleType = null;
            //if (securitySubject.OrganizationType_RoleType != null)
            //    roleType = securitySubject.OrganizationType_RoleType.RoleType;
            //else if (securitySubject.RoleType != null)
            //    roleType = securitySubject.RoleType;
            //else if (securitySubject.OrganizationPost != null)
            //    roleType = securitySubject.OrganizationPost.OrganizationType_RoleType.RoleType;

            //if (roleType!=null &&roleType.IsSuperAdmin == true)
            //    {
            //        result.Add(SecurityAction.ArchiveEdit);
            //        result.Add(SecurityAction.ArchiveMenuAccess);
            //        result.Add(SecurityAction.ArchiveView);
            //        result.Add(SecurityAction.EditAndDelete);
            //        result.Add(SecurityAction.MenuAccess);


            //    }
            //    else
            //    {
            var dbPermission = (securitySubject.Permission.FirstOrDefault(p => p.SecurityObjectID == securityObject.ID));

            if (dbPermission != null)
            {
                foreach (var dbAction in dbPermission.Permission_Action)
                {
                    var dbActionType = (SecurityAction)Enum.Parse(typeof(SecurityAction), dbAction.Action);
                    result.Add(dbActionType);
                }
            }
            //}
            CacheManager.GetCacheManager().AddCacheItem(result, CacheItemType.Permission, securitySubject.ID + "_" + securityObject.ID);
            return(result);
        }
Example #24
0
        private List <SecurityAction> GetPersmissionByPosts(MyProjectEntities context, IQueryable <OrganizationPost> posts, SecurityObject securityObject, bool goUpward = true)
        {
            var actions = new List <SecurityAction>();

            //بهتر است راه حل کلی برای ذخیره دسترسی های کلی تر مانند نوع سازمان و یا آبجکتهای بالاتر مانن دیتابیس پیاده شود که هر دفعه خوانده نشوند
            var objectCategory     = (DatabaseObjectCategory)securityObject.Type;
            var possibleActionTree = GetActionsByCategory(objectCategory);
            //////////////////////////////// فعلا برای سرعت بیشتر
            //return GetAllActions();

            List <List <SecurityAction> > AllPostAccess = new List <List <SecurityAction> >();

            foreach (var post in posts)
            {
                List <SecurityAction> postAccess;
                var postActions      = GetPersmissionByPost(context, post.SecuritySubject, securityObject, 0, goUpward);
                var finalPostActions = GetPossibleActions(postActions, GetActionsByCategory(objectCategory));

                //اولویت دسترسی های تعریف شده برای پست بالاتر از همه است
                if (finalPostActions.Any())
                {
                    postAccess = finalPostActions;
                }
                else
                {
                    var orgTypeRoleTypeActions      = GetPersmissionByPost(context, post.OrganizationType_RoleType.SecuritySubject, securityObject, 0, goUpward);
                    var organizationActions         = GetPersmissionByPost(context, post.Organization.SecuritySubject, securityObject, 0, goUpward);
                    var finalOrgTypeRoleTypeActions = GetPossibleActions(orgTypeRoleTypeActions, GetActionsByCategory(objectCategory));
                    var finalOrganizationActions    = GetPossibleActions(organizationActions, GetActionsByCategory(objectCategory));
                    if (finalOrgTypeRoleTypeActions.Any())
                    {
                        //جمع سازمان و نوع نقش/نوع سازمان که همسطح هستند
                        postAccess = Combination(new List <List <SecurityAction> >()
                        {
                            finalOrgTypeRoleTypeActions, finalOrganizationActions
                        }, possibleActionTree);
                    }
                    else
                    {
                        var roleTypeActions      = GetPersmissionByPost(context, post.OrganizationType_RoleType.RoleType.SecuritySubject, securityObject, 0, goUpward);
                        var finalRoleTypeActions = GetPossibleActions(roleTypeActions, GetActionsByCategory(objectCategory));
                        if (finalOrganizationActions.Any())
                        {
                            //ادغام سازمان و نوع نقش
                            //اداغام دسترسی ها موازی برای موضوعات موازی
                            postAccess = Combination(new List <List <SecurityAction> >()
                            {
                                finalOrganizationActions, finalRoleTypeActions
                            }, possibleActionTree);
                        }
                        else
                        {
                            //ادغام نوع سازمان و نوع نقش

                            var organizationTypeActions      = GetPersmissionByPost(context, post.OrganizationType_RoleType.OrganizationType.SecuritySubject, securityObject, 0, goUpward);
                            var finalOrganizationTypeActions = GetPossibleActions(organizationTypeActions, GetActionsByCategory(objectCategory));
                            postAccess = Combination(new List <List <SecurityAction> >()
                            {
                                finalRoleTypeActions, finalOrganizationTypeActions
                            }, possibleActionTree);
                        }
                    }
                }
                AllPostAccess.Add(postAccess);
            }
            return(Combination(AllPostAccess, possibleActionTree));
        }
Example #25
0
        //设定权限
        protected void btnSetRoleFun_Click(object sender, EventArgs e)
        {
            List <ObjectRule> rules = new List <ObjectRule>(100);
            Role           role     = null;
            SecurityObject secObj   = null;

            Guid objId = new Guid(this.hiCurrentCataId.Value);

            secObj = new SecurityObject(objId, SecurityObjectType.Items);
            ArrayList opers = new ArrayList(100);

            foreach (GridViewRow row in roleGroupList.Rows)
            {
                Guid roleId = new Guid(roleGroupList.DataKeys[row.RowIndex].Value.ToString());
                role        = new Role();
                role.RoleId = roleId;
                opers.Add(role);

                ObjectRule newRule;

                CheckBox chkRead = row.FindControl("funReadChk") as CheckBox;
                newRule = new ObjectRule(secObj, role, OperatorMethod.Deny);
                rules.Add(newRule);
                newRule.IsValidate = chkRead.Checked;



                CheckBox chkWrite = row.FindControl("funUpChk") as CheckBox;
                newRule = new ObjectRule(secObj, role, OperatorMethod.Write);
                rules.Add(newRule);
                newRule.IsValidate = chkWrite.Checked;


                CheckBox chkEdit = row.FindControl("funEditChk") as CheckBox;
                newRule = new ObjectRule(secObj, role, OperatorMethod.Modify);
                rules.Add(newRule);
                newRule.IsValidate = chkEdit.Checked;

                CheckBox chkDownload = row.FindControl("funDownChk") as CheckBox;
                newRule = new ObjectRule(secObj, role, OperatorMethod.Download);
                rules.Add(newRule);
                newRule.IsValidate = chkDownload.Checked;

                //针对当前类的子类设置权限(子类应自动继承父类权限)
                DataTable childCatalog = Catalog.GetCatalogTableByParentId(objId);
                foreach (DataRow cata in childCatalog.Rows)
                {
                    SecurityObject cSecObj = new SecurityObject(new Guid(cata["catalogId"].ToString()),
                                                                SecurityObjectType.Items);

                    ObjectRule cOrRead = new ObjectRule(cSecObj, role, OperatorMethod.Deny);
                    cOrRead.IsValidate = chkRead.Checked;
                    ObjectRule cOrWrite = new ObjectRule(cSecObj, role, OperatorMethod.Write);
                    cOrWrite.IsValidate = chkWrite.Checked;
                    ObjectRule cOrEdit = new ObjectRule(cSecObj, role, OperatorMethod.Modify);
                    cOrEdit.IsValidate = chkEdit.Checked;
                    ObjectRule cOrDown = new ObjectRule(cSecObj, role, OperatorMethod.Download);
                    cOrDown.IsValidate = chkDownload.Checked;

                    rules.Add(cOrRead);
                    rules.Add(cOrWrite);
                    rules.Add(cOrEdit);
                    rules.Add(cOrDown);
                }
            }

            if (ObjectRule.SetRules(rules, secObj, opers))
            {
                ShowMessage("角色权限设置成功");
            }
            else
            {
                ShowMessage("角色权限设置失败");
            }
        }
Example #26
0
        private static void DownloadAdsUsers()
        {
            using (var context = new OnlineFilesEntities())
                using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
                    using (var filter = new UserPrincipal(ctx))
                    {
                        using (PrincipalSearcher search = new PrincipalSearcher(filter))
                        {
                            int max = search.FindAll().Count();
                            int c   = 0;
                            foreach (var principal in search.FindAll())
                            {
                                Console.WriteLine("Processing " + c + " of " + max);
                                c++;
                                var user = principal as UserPrincipal;
                                if (user == null)
                                {
                                    continue;
                                }
                                if (user.StructuralObjectClass == "group" && user.Enabled != true)
                                {
                                    continue;
                                }


                                var so = context.SecurityObjects
                                         .FirstOrDefault(d => d.ActiveDirectoryId == user.Guid);
                                if (so == null)
                                {
                                    so = new SecurityObject
                                    {
                                        ActiveDirectoryId = user.Guid,
                                        FullName          = user.Name,
                                        Username          = user.SamAccountName,
                                        EmailAddress      = user.EmailAddress ?? "",
                                        IsGroup           = false,
                                        LastLogInOn       = DateTime.Now,
                                        IsActive          = true,
                                        HomeFolder        = null
                                    };
                                    context.SecurityObjects.Add(so);
                                }
                                else
                                {
                                    so.IsGroup      = false;
                                    so.FullName     = user.Name;
                                    so.Username     = user.SamAccountName;
                                    so.EmailAddress = user.EmailAddress ?? "";
                                }

                                context.SaveChanges();

                                context.SecurityObjectMemberships.RemoveRange(context.SecurityObjectMemberships.Where(d => d.SecurityObjectId == so.SecurityObjectId));
                                context.SaveChanges();

                                try
                                {
                                    foreach (Principal grp in user.GetGroups())
                                    {
                                        var og = context.SecurityObjects.FirstOrDefault(d => d.ActiveDirectoryId == grp.Guid);
                                        if (og != null)
                                        {
                                            context.SecurityObjectMemberships.Add(new SecurityObjectMembership {
                                                OwnerSecurityObject = so, GroupSecurityObjectId = og.SecurityObjectId
                                            });
                                        }
                                    }
                                }
                                catch (Exception)
                                {
                                }


                                context.SaveChanges();
                            }
                        }
                    }
        }
Example #27
0
        protected void btnSetUserFun_Click(object sender, EventArgs e)
        {
            List <ObjectRule> rules = new List <ObjectRule>(100);
            User           user     = null;
            SecurityObject secObj   = null;

            Guid objId = new Guid(this.hiCurrentCataId.Value);

            secObj = new SecurityObject(objId, SecurityObjectType.Items);
            ArrayList opers = new ArrayList(100);

            foreach (GridViewRow row in userList.Rows)
            {
                Guid userId = new Guid(userList.DataKeys[row.RowIndex].Value.ToString());
                user = new User(userId);
                opers.Add(user);

                ObjectRule newRule;


                CheckBox chk = row.FindControl("funUpChk") as CheckBox;
                newRule = new ObjectRule(secObj, user, OperatorMethod.Write);
                rules.Add(newRule);
                if (chk.Checked)
                {
                    newRule.IsValidate = true;
                }
                else
                {
                    newRule.IsValidate = false;
                }

                CheckBox echk = row.FindControl("funEditChk") as CheckBox;
                newRule = new ObjectRule(secObj, user, OperatorMethod.Modify);
                rules.Add(newRule);
                if (echk.Checked)
                {
                    newRule.IsValidate = true;
                }
                else
                {
                    newRule.IsValidate = false;
                }

                CheckBox dchk = row.FindControl("funReadChk") as CheckBox;
                newRule = new ObjectRule(secObj, user, OperatorMethod.Deny);
                rules.Add(newRule);
                if (dchk.Checked)
                {
                    newRule.IsValidate = true;
                }
                else
                {
                    newRule.IsValidate = false;
                }

                CheckBox downChk = row.FindControl("funDownChk") as CheckBox;
                newRule = new ObjectRule(secObj, user, OperatorMethod.Download);
                rules.Add(newRule);
                newRule.IsValidate = downChk.Checked;

                //针对当前类的子类设置权限(子类应自动继承父类权限)
                DataTable childCatalog = Catalog.GetCatalogTableByParentId(objId);
                foreach (DataRow cata in childCatalog.Rows)
                {
                    SecurityObject cSecObj = new SecurityObject(new Guid(cata["catalogId"].ToString()),
                                                                SecurityObjectType.Items);

                    ObjectRule cOrUp = new ObjectRule(cSecObj, user, OperatorMethod.Write);
                    cOrUp.IsValidate = chk.Checked;


                    rules.Add(cOrUp);

                    ObjectRule cOrEdit = new ObjectRule(cSecObj, user, OperatorMethod.Modify);
                    cOrEdit.IsValidate = echk.Checked;

                    rules.Add(cOrEdit);


                    ObjectRule cOrDeny = new ObjectRule(cSecObj, user, OperatorMethod.Deny);
                    cOrDeny.IsValidate = dchk.Checked;
                    rules.Add(cOrDeny);


                    ObjectRule cOrDown = new ObjectRule(cSecObj, user, OperatorMethod.Download);
                    cOrDown.IsValidate = downChk.Checked;
                    rules.Add(cOrDown);
                }
            }

            if (ObjectRule.SetRules(rules, secObj, opers))
            {
                ShowMessage("用户权限设置成功");
            }
            else
            {
                ShowMessage("用户权限设置失败");
            }
        }
        private static void DownloadAdsUsers()
        {
            using (var context = new OnlineFilesEntities())
            using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
            using (var filter = new UserPrincipal(ctx))
            {
                using (PrincipalSearcher search = new PrincipalSearcher(filter))
                {
                    int max = search.FindAll().Count();
                    int c = 0;
                    foreach (var principal in search.FindAll())
                    {
                        Console.WriteLine("Processing " + c + " of " + max);
                        c++;
                        var user = principal as UserPrincipal;
                        if (user == null)
                            continue;
                        if (user.StructuralObjectClass == "group" && user.Enabled != true)
                            continue;


                        var so = context.SecurityObjects
                            .FirstOrDefault(d => d.ActiveDirectoryId == user.Guid);
                        if (so == null)
                        {
                            so = new SecurityObject
                            {
                                ActiveDirectoryId = user.Guid,
                                FullName = user.Name,
                                Username = user.SamAccountName,
                                EmailAddress = user.EmailAddress ?? "",
                                IsGroup = false,
                                LastLogInOn = DateTime.Now,
                                IsActive = true,
                                HomeFolder = null
                            };
                            context.SecurityObjects.Add(so);
                        }
                        else
                        {
                            so.IsGroup = false;
                            so.FullName = user.Name;
                            so.Username = user.SamAccountName;
                            so.EmailAddress = user.EmailAddress ?? "";
                        }

                        context.SaveChanges();

                        context.SecurityObjectMemberships.RemoveRange(context.SecurityObjectMemberships.Where(d => d.SecurityObjectId == so.SecurityObjectId));
                        context.SaveChanges();

                        try
                        {
                            foreach (Principal grp in user.GetGroups())
                            {
                                var og = context.SecurityObjects.FirstOrDefault(d => d.ActiveDirectoryId == grp.Guid);
                                if (og != null)
                                    context.SecurityObjectMemberships.Add(new SecurityObjectMembership {OwnerSecurityObject = so, GroupSecurityObjectId = og.SecurityObjectId});
                            }
                        }
                        catch (Exception)
                        {
                        }


                        context.SaveChanges();
                    }
                }
            }
        }
Example #29
0
        /// <summary>
        /// 绑定用户组定义功能
        /// </summary>
        void BindRoleControlList()
        {
            Dictionary <int, string> methodDict = WebUI.UIBiz.CommonInfo.GetMethodDict();
            //注意修改 当为superadmin时
            RoleCollection roles = Role.GetRoleCollection(CurrentGroupId);


            Hashtable roleRules = new Hashtable();

            foreach (Role role in roles)
            {
                ISecurityObject   securityObj = new SecurityObject(new Guid(this.hiCurrentCataId.Value), SecurityObjectType.Items);
                List <ObjectRule> rules       = new List <ObjectRule>();

                foreach (KeyValuePair <int, string> methodEntry in methodDict)
                {
                    OperatorMethod method = (OperatorMethod)((int)methodEntry.Key);
                    ObjectRule     rule   = new ObjectRule(securityObj, role, method);

                    rules.Add(rule);
                }

                roleRules.Add(role, rules);

                ObjectRule.CheckRules(rules);
            }

            DataTable roleMethod = new DataTable();

            DataColumn dc = new DataColumn("roleName");

            roleMethod.Columns.Add(dc);

            dc = new DataColumn("roleId");
            roleMethod.Columns.Add(dc);

            foreach (KeyValuePair <int, string> methodEntry in methodDict)
            {
                string mIndex = methodEntry.Key.ToString();
                roleMethod.Columns.Add(mIndex, typeof(bool));
            }


            //foreach (KeyValuePair<int, string> methodEntry in methodDict)
            //{
            //   TemplateField field = new TemplateField();
            //  //  CheckBoxField field = new CheckBoxField();
            //    WebUI.UIBiz.GridViewTempla template = new WebUI.UIBiz.GridViewTempla(ListItemType.Item, string.Empty);

            //    field.HeaderText = methodEntry.Value.ToString();
            //   // field.DataField = methodEntry.Key.ToString();
            //   // field.ReadOnly = false;

            //   field.ItemTemplate = template;
            //    roleGroupList.Columns.Add(field);

            //    DataColumn methodDc = new DataColumn(methodEntry.Key.ToString());
            //    roleMethod.Columns.Add(methodDc);
            //}



            foreach (DictionaryEntry entry in roleRules)
            {
                Role role = entry.Key as Role;
                List <ObjectRule> rules = entry.Value as List <ObjectRule>;

                DataRow dr = roleMethod.NewRow();
                dr["roleName"] = role.RoleName;
                dr["roleId"]   = role.RoleId.ToString();

                foreach (IRule rule in rules)
                {
                    string methodKey = ((int)rule.Method).ToString();
                    dr[methodKey] = rule.IsValidate;
                }

                roleMethod.Rows.Add(dr);
            }

            DataView dv = roleMethod.DefaultView;

            dv.Sort = "RoleName";
            roleGroupList.DataSource = dv;
            roleGroupList.DataBind();



            //   TemplateColumn roleColumn = new TemplateColumn();
        }
Example #30
0
        protected void btnSetRoles_Click(object sender, EventArgs e)
        {
            List <ObjectRule> rules = new List <ObjectRule>();
            Role           role     = null;
            SecurityObject secObj   = null;
            ObjectRule     newRule;



            //设置大分类的角色权限
            foreach (RepeaterItem item in rptCategoryTop.Items)
            {
                if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
                {
                    HiddenField hf          = (HiddenField)item.FindControl("topCatId");
                    string      CategorieId = hf.Value;

                    Guid objId = new Guid(CategorieId);
                    secObj = new SecurityObject(objId, SecurityObjectType.Items);


                    role = new Role(new Guid(this.hiRoleId.Value));

                    CheckBox chkRead = item.FindControl("funTopReadChk") as CheckBox;
                    newRule            = new ObjectRule(secObj, role, OperatorMethod.Deny);
                    newRule.IsValidate = chkRead.Checked;
                    rules.Add(newRule);

                    CheckBox chkUp = item.FindControl("funTopUpChk") as CheckBox;
                    newRule            = new ObjectRule(secObj, role, OperatorMethod.Write);
                    newRule.IsValidate = chkUp.Checked;
                    rules.Add(newRule);


                    CheckBox chkEdit = item.FindControl("funTopEditChk") as CheckBox;
                    newRule            = new ObjectRule(secObj, role, OperatorMethod.Modify);
                    newRule.IsValidate = chkEdit.Checked;
                    rules.Add(newRule);


                    CheckBox chkDown = item.FindControl("funTopDownChk") as CheckBox;
                    newRule            = new ObjectRule(secObj, role, OperatorMethod.Download);
                    newRule.IsValidate = chkDown.Checked;
                    rules.Add(newRule);


                    //寻找小类

                    Repeater rptCatalogChild = (Repeater)item.FindControl("rptCategoryChild");
                    foreach (RepeaterItem itemChild in rptCatalogChild.Items)
                    {
                        HiddenField hfChild          = (HiddenField)itemChild.FindControl("childCatId");
                        string      childCategorieId = hfChild.Value;

                        Guid objChildId = new Guid(childCategorieId);
                        secObj = new SecurityObject(objChildId, SecurityObjectType.Items);


                        CheckBox chkReadChild = itemChild.FindControl("funChildReadChk") as CheckBox;
                        newRule            = new ObjectRule(secObj, role, OperatorMethod.Deny);
                        newRule.IsValidate = chkReadChild.Checked;
                        rules.Add(newRule);

                        CheckBox chkUpChild = itemChild.FindControl("funChildUpChk") as CheckBox;
                        newRule            = new ObjectRule(secObj, role, OperatorMethod.Write);
                        newRule.IsValidate = chkUpChild.Checked;
                        rules.Add(newRule);


                        CheckBox chkEditChild = itemChild.FindControl("funChildEditChk") as CheckBox;
                        newRule            = new ObjectRule(secObj, role, OperatorMethod.Modify);
                        newRule.IsValidate = chkEditChild.Checked;
                        rules.Add(newRule);


                        CheckBox chkDownChild = itemChild.FindControl("funChildDownChk") as CheckBox;
                        newRule            = new ObjectRule(secObj, role, OperatorMethod.Download);
                        newRule.IsValidate = chkDownChild.Checked;
                        rules.Add(newRule);
                    }
                }
            }



            ArrayList opers = new ArrayList(100);

            if (ObjectRule.SetRules(rules, secObj, opers))
            {
                ShowMessage("角色权限设置成功");
            }
            else
            {
                ShowMessage("角色权限设置失败");
            }
        }