关于级联(树形权限)的基本实现思路


本文介绍Portal里实现级联权限的思路。其实windows 文件夹权限本身就是一个典型的级联权限,参考下图。

在windows文件夹权限里,在“安全‘里,有一项”包括可从改对象的父项集成的权限“。默认是选中的。

这样的好处是,假如我们有一个”人事部“文件夹,设置只有人事部的人员可以访问,我们可以在人事部里建立无限个子文件夹,这些文件夹默认也都是只能是人事部人员可以访问,不需要管理员单独赋予权限。

在我们Portal系统里,也采用了类似简化的权限设置

下面介绍实现方式:

 很显然,我们需要有一张权限表(tabsecurity存储每一个页面的具体记录,数据库结构如下)

下面显示了填充数据后的结果,

attribute取值为group或者user,表示节点是组或者用户属性,

name为组名或者用户名。

Roletype为0是只读,为1为可写,如果为2表示可以设计。

 

接下来,还需要设计tab表,他记录页面权限是否是继承的--inherit字段,
这里inherit并没有放置到tabsecurity表里,我们仅把权限当做页面的一个属性。

如果是1表示自动继承父权限,为0表示非继承。

有了上面的结构,即可在用户访问页面时,获取其权限,下面就是实现这个功能核心的SQL语句。

当用户访问页面时,会建立一个临时表#a, 其中 while @parentid>0 and @inherit>0 表示如果如果当前节点是支持继承的,而且他还有父节点 就继续循环父节点的权限,然后给此节点 系统执行完毕后,会得到当前节点实际权限列表

   public static DataView GetTabSecurityRolesTree(int tabid, string sectype)
{
string sql = @"
declare @parentid int
declare @id int
declare @inherit int

if object_id('tempdb..#a') is not null
Begin
drop table #a
End

create table #a(id int, parentid int)
set @id=
"+tabid+ @"
select @parentid=parentid, @id=id ,@inherit=inherit from portal_pages where id=@id

insert into #a(id,parentid) values(@id,@id)
while @parentid>0 and @inherit>0
begin select @parentid=parentid, @id=id, @inherit=inherit from portal_pages where id=@parentid
insert into #a(id,parentid) values(@id,@parentid)
set @id=@parentid
end

select * from portal_tabsecurity inner join #a on #a.id=tabid


";

DataView dv = new DataView( DBHelper.Instance.ExeDataSet(sql).Tables[0] );
dv.RowFilter = " sectype='" + sectype + "' ";
return dv;
}

有上面得到页面的权限,然后在获取当前用户已有的权限,一比较,就能够确认用户是否可以访问

 

然后检查他是否有权限。



private bool CheckAuthenticatedPermission(string[] PageRoles, string[] myroles)

{

if (Array.IndexOf(PageRoles, "everyone") != -1)

return true;


if (Array.IndexOf(PageRoles, "authenticated") != -1)

return true;



foreach (string myrole in myroles)

{

if (!string.IsNullOrEmpty(myrole))

{

foreach (string searchrole in PageRoles)

{

if (myrole == searchrole)

{
return true;

}

}
}





}





return false;

}

原文地址:https://www.cnblogs.com/mqingqing123/p/2431057.html