mvc 权限控制续——使用存储过程判断

以前的随笔没有给出数据库,这里给出具体的数据库以及怎么使用存储过程来判断

 下面是数据库:

/****** Object:  Table [dbo].[Resource]    Script Date: 03/16/2012 10:43:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Resource](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Name] [nvarchar](max) NOT NULL,
	[ControllName] [nvarchar](max) NOT NULL,
	[IsController] [bit] NOT NULL,
	[IsAllowedNoneRoles] [bit] NOT NULL,
	[IsAllowedAllRoles] [bit] NOT NULL,
	[CreateTime] [datetime] NOT NULL,
	[IsShow] [bit] NOT NULL,
	[Title] [nvarchar](max) NULL,
	[IsHeader] [bit] NOT NULL,
 CONSTRAINT [PK_Resource] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Role]    Script Date: 03/16/2012 10:43:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Role](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[RoleName] [nvarchar](max) NOT NULL,
	[Description] [nvarchar](max) NOT NULL,
	[CreateTime] [datetime] NOT NULL,
 CONSTRAINT [PK_Role] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[User]    Script Date: 03/16/2012 10:43:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[User](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Email] [nvarchar](max) NOT NULL,
	[Name] [nvarchar](max) NOT NULL,
	[Password] [nvarchar](max) NOT NULL,
	[CreateTime] [datetime] NOT NULL,
	[UpdateTime] [datetime] NOT NULL
 CONSTRAINT [PK_User] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[RoleUser]    Script Date: 03/16/2012 10:43:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[RoleUser](
	[RolesInternal_ID] [int] NOT NULL,
	[UserInternal_ID] [int] NOT NULL,
 CONSTRAINT [PK_RoleUser] PRIMARY KEY NONCLUSTERED 
(
	[RolesInternal_ID] ASC,
	[UserInternal_ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[ResourceRole]    Script Date: 03/16/2012 10:43:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ResourceRole](
	[ResourceInternal_ID] [int] NOT NULL,
	[RolesInternal_ID] [int] NOT NULL,
 CONSTRAINT [PK_ResourceRole] PRIMARY KEY NONCLUSTERED 
(
	[ResourceInternal_ID] ASC,
	[RolesInternal_ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

/****** Object:  Default [DF_User_CurrentScore]    Script Date: 03/16/2012 10:43:39 ******/
ALTER TABLE [dbo].[User] ADD  CONSTRAINT [DF_User_CurrentScore]  DEFAULT ((0)) FOR [CurrentScore]
GO
/****** Object:  ForeignKey [FK_RoleUser_Role]    Script Date: 03/16/2012 10:43:39 ******/
ALTER TABLE [dbo].[RoleUser]  WITH CHECK ADD  CONSTRAINT [FK_RoleUser_Role] FOREIGN KEY([RolesInternal_ID])
REFERENCES [dbo].[Role] ([ID])
GO
ALTER TABLE [dbo].[RoleUser] CHECK CONSTRAINT [FK_RoleUser_Role]
GO
/****** Object:  ForeignKey [FK_RoleUser_User]    Script Date: 03/16/2012 10:43:39 ******/
ALTER TABLE [dbo].[RoleUser]  WITH CHECK ADD  CONSTRAINT [FK_RoleUser_User] FOREIGN KEY([UserInternal_ID])
REFERENCES [dbo].[User] ([ID])
GO
ALTER TABLE [dbo].[RoleUser] CHECK CONSTRAINT [FK_RoleUser_User]
GO
/****** Object:  ForeignKey [FK_ResourceRole_Resource]    Script Date: 03/16/2012 10:43:39 ******/
ALTER TABLE [dbo].[ResourceRole]  WITH CHECK ADD  CONSTRAINT [FK_ResourceRole_Resource] FOREIGN KEY([ResourceInternal_ID])
REFERENCES [dbo].[Resource] ([ID])
GO
ALTER TABLE [dbo].[ResourceRole] CHECK CONSTRAINT [FK_ResourceRole_Resource]
GO
/****** Object:  ForeignKey [FK_ResourceRole_Role]    Script Date: 03/16/2012 10:43:39 ******/
ALTER TABLE [dbo].[ResourceRole]  WITH CHECK ADD  CONSTRAINT [FK_ResourceRole_Role] FOREIGN KEY([RolesInternal_ID])
REFERENCES [dbo].[Role] ([ID])
GO
ALTER TABLE [dbo].[ResourceRole] CHECK CONSTRAINT [FK_ResourceRole_Role]
GO

 判断权限的存储过程如下,判断方法同前面的c#,效率有所提升:

/****** Object:  StoredProcedure [dbo].[CheckUserAuthorization]    Script Date: 03/16/2012 10:43:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		
-- Create date: <2012/2/28>
-- Description:	<-- 判断用户是否有权限访问>
-- =============================================
CREATE PROCEDURE [dbo].[CheckUserAuthorization]
	@ControllerName nvarchar(100) = 'Task',
	@ActionName nvarchar(100) = 'Index',
	@UserID INT = 1 --用户编号 匿名用户传入0
AS
BEGIN
DECLARE @ISAllowed bit = 0
DECLARE @IsAllowedNoneRoles INT = -1
DECLARE @IsAllowedAllRoles INT = -1
DECLARE @ID INT = -1
DECLARE @ResourceCount INT = 0

-- 查找有木有记录 先查找Action
SELECT @ID=ID,@IsAllowedNoneRoles=IsAllowedNoneRoles, @IsAllowedAllRoles=IsAllowedAllRoles FROM
dbo.Resource
WHERE ControllName = @ControllerName AND Name= @ActionName

IF @ID =-1
	BEGIN
		-- 木有Action 选择 Controll
		SELECT @ID=ID,@IsAllowedNoneRoles=IsAllowedNoneRoles, @IsAllowedAllRoles=IsAllowedAllRoles FROM
		dbo.Resource
		WHERE ControllName = @ControllerName
		
		-- 木有记录,均允许访问
		IF @ID =-1
			GOTO ALLOWED;
	END

-- 如果允许匿名访问或者允许所有人访问
IF @IsAllowedNoneRoles = 1 
	GOTO ALLOWED;
	
-- 未登录用户,不允许访问
IF @UserID = 0
	GOTO NOTALLOWED;
	
-- 允许所有登录用户访问
IF @IsAllowedAllRoles = 1
	GOTO ALLOWED;

--查找用户的角色是否允许访问该资源
SELECT @ResourceCount = COUNT(*) FROM dbo.ResourceRole
WHERE RolesInternal_ID IN(
SELECT RolesInternal_ID FROM dbo.RoleUser WHERE dbo.RoleUser.UserInternal_ID = @UserID)
AND ResourceInternal_ID = @ID
	
-- 有结果,允许访问
IF(@ResourceCount>0)
	GOTO ALLOWED;;

-- 没有结果,不允许访问
	GOTO NOTALLOWED;
	
ALLOWED:
	SELECT 1 AS RESULT;
	GOTO THEEND;
	
NOTALLOWED:
	SELECT 0 AS RESULT;	
	GOTO THEEND;
THEEND:
END
GO

判断是否有访问权限需要执行CheckUserAuthorization存储过程,只需要传入控制器和Action名称以及用户ID即可,EF可以使用下面的方法调用:

public bool CheckUserAuth(string controllerName, string actionName, int userId)
        {
            EntityCommand cmd = ((EntityConnection)this.Connection).CreateCommand();
            if (cmd.Connection.State != System.Data.ConnectionState.Open)
                cmd.Connection.Open();
            cmd.CommandText = this.DefaultContainerName + ".CheckUserAuthorization";
            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Parameters.AddWithValue("ControllerName", controllerName);
            cmd.Parameters.AddWithValue("ActionName", actionName);
            cmd.Parameters.AddWithValue("UserID", userId);

            EntityParameter ret = new EntityParameter("ReturnValue", DbType.Int32);
            ret.Direction = ParameterDirection.ReturnValue;
            ret.Value = -1;
            cmd.Parameters.Add(ret);
            var obj = (int)cmd.ExecuteScalar();
            cmd.Connection.Close();
            return (obj > 0);
        }

为了减少服务器压力,你可以在执行验证后将结果缓存起来,缓存时间自己设定

var controller = filterContext.RouteData.Values["controller"].ToString();
            var action = filterContext.RouteData.Values["action"].ToString();

            var isAllowed = this.IsAllowed(user, controller, action);

            if (!isAllowed)
            {
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Home", action = "LogOn", ReturnUrl = filterContext.HttpContext.Request.Url }));
            }
public bool IsAllowed(UserModel user, string controller, string action)
        {
            string key = (user != null ? user.UserId.ToString() : "null") + controller + action;
            var result = false;

            if (Cache.TryGet(key, out result))
            {
                return result;
            }

            result = IoC.Resolve().CheckUserAuthorization(controller, action, user != null ? user.UserId : 0);

            // 设置缓存  60分钟
            Cache.Set(key, result, TimeSpan.FromMinutes(60));

            // 默认禁止访问
            return result;
        }

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏技术之路

使用Linq to Sql 创建数据库和表

1.建一个类Article 1 using System.Data.Linq.Mapping; 2 3 4 5 [Table(Name =...

1957
来自专栏乐沙弥的世界

dbms_xplan之display_cursor函数的使用

        DBMS_XPLAN包中display_cursor函数不同于display函数,display_curso...

1443
来自专栏数据之美

Hive 基础(2):库、表、字段、交互式查询的基本操作

1、命令行操作 (1)打印查询头,需要显示设置: set hive.cli.print.header=true; (2)加"--",其后的都被认为是注释...

54410
来自专栏哲学驱动设计

Rafy 中的 Linq 查询支持(根据聚合子条件查询聚合父)

为了提高开发者的易用性,Rafy 领域实体框架在很早开始就已经支持使用 Linq 语法来查询实体了。但是只支持了一些简单的、常用的条件查询,支持的力度很有限。特...

1717
来自专栏ASP.NET MVC5 后台权限管理系统

ASP.NET MVC5+EF6+EasyUI 后台管理系统(41)-组织架构

本节开始我们要实现工作流,此工作流可以和之前的所有章节脱离关系,也可以紧密合并。 我们当初设计的项目解决方案就是可伸缩可以拆离,可共享的项目解决方案。所以我们同...

2017
来自专栏kwcode

SQL语句帮助大全

--删除约束 Status:字段名 alter table Table_1 drop constraint Status; --添加约束 --Status :字...

34611
来自专栏ASP.NET MVC5 后台权限管理系统

ASP.NET MVC5+EF6+EasyUI 后台管理系统(35)-文章发布系统②-构建项目

注:阅读本文,需要阅读本系列的之前文章 代码生成器下载地址(文章开头处)  接下来我们建立数据库的表和各层的代码 我们只需要两张表,文章列表(MIS_Artic...

2269
来自专栏沃趣科技

语句效率统计视图 | 全方位认识 sys 系统库

在上一篇《统计信息查询视图|全方位认识 sys 系统库》中,我们介绍了利用sys 系统库的查询统计信息的快捷视图,本期将为大家介绍语句查询效率语句统计信息相关的...

1955
来自专栏杨建荣的学习笔记

通过shell脚本得到数据字典的信息 (r2笔记72天)

在平时的工作中,可能需要查询一些数据字典的信息,比如数据字典对应的基表信息,可以得到更多数据库内部的一些详细信息。 比如user_objects这个数据字典视图...

2847
来自专栏乐沙弥的世界

oracle imp导入时出现skipping table

    最近有同事在使用传统的imp工具导入数据时,总是提示收到skipping table的提示,也就是表被跳过,而不是被重建。即使是将目标数据库上的表对象删...

1021

扫码关注云+社区