简单的MVC 权限管理
花了3天时间研究了下对于 NHibernate+MVC4+bootstrap+Redis(这个是选配只做了登陆测试)+T4 这些都是第一次使用。用着有些生硬权当鼓励下自己,记录下来有空就继续完善。
思路是:扩展AuthorizeAttribute,在Controller里面标识类或方法,来获取档期url地址 判断是否合法访问
首选是框架的结构:
一个简单的三层 ,Libs里面放了nhibernate 和redis的dll
Model 、IDTO、DTO、 IBusiness、Business这几个层都是用T4模板生成
NHibernate.CMS.Framework放了些工具方法
NHibernate.CMS.MVC是 相当于UI展现
结构就大概这样了,主要的几个访问方法IDO文件
/// <summary>
/// 基仓储实现的方法
/// </summary>
/// <typeparam name="T"></typeparam>
public interface IBaseRepository<T> where T : class,new()
{
//添加
object AddEntities(T entity); object AddEntities(string entityName, object obj); //修改
bool UpdateEntities(T entity); //修改
bool UpdateEntities(string entityName, object obj); //删除
bool DeleteEntities(T entity);
//删除
bool DeleteEntities(string entityName, object obj);
bool DeleteEntities(string query);
bool DeleteEntities(string query, object[] values, Type.IType[] types); //查询
IList<T> LoadEntities(Func<T, bool> wherelambda);
IList<T> LoadEntities(string queryString); //分页
IList<T> LoadPagerEntities<S>(int pageSize, int pageIndex,
out int total, Func<T, bool> whereLambda, bool isAsc, Func<T, S> orderByLambda); IList<T> LoadPagerEntities<S>(PageResult pagsinfo, out int total, Func<T, bool> whereLambda, bool isAsc, System.Linq.Expressions.Expression<Func<T, object>> orderByLambda); IList<T> LoadPagerEntities<S>(PageResult pagsinfo, out int total, string whereLambda, string orderByLambda); System.Data.DataTable LoadPagerEntities(PageResult pagsinfo, out int total, string whereLambda, string orderByLambda); System.Collections.IList ExecuteSQL(string queryString); //获取实体
T GetSingleModel(T entity,object id);
T GetSingleModel(Func<T, bool> wherelambda);
}
DTO是实现IDTO的接口
//连接-单例模式 用法2
public class Singleton
{
private static Singleton _instance = null;
private static readonly object lockHelper = new object(); protected ISession m_Session;
public ISession SingletonSession
{
get { return m_Session; }
} protected ISessionFactory Singleton_SessionFactory;
private Singleton() {
string path = NHibernate.CMS.Framework.Utility.AppSettingsHelper.GetString("hibernatecfgxml") + "Config/hibernate.cfg.xml";
//HttpContextBase.GetServerPath("Config/hibernate.cfg.xml");
var config = new Configuration().Configure(path);
Singleton_SessionFactory = config.BuildSessionFactory();
m_Session = Singleton_SessionFactory.OpenSession();
}
public static Singleton CreateInstance
{
get
{
if (_instance == null)
{
lock (lockHelper)
{
if (_instance == null)
_instance = new Singleton();
}
}
return _instance;
}
} }
public partial class BaseRepository<T> where T : class
{ //添加
public object AddEntities(T entity)
{ try
{ var id = Singleton.CreateInstance.SingletonSession.Save(entity);
Singleton.CreateInstance.SingletonSession.Flush();
return id;
}
catch (Exception ex) { Console.WriteLine(ex.Message); }
return null; }
//添加
public object AddEntities(string entityName, object obj)
{
try
{ var id = Singleton.CreateInstance.SingletonSession.Save(entityName, obj);
Singleton.CreateInstance.SingletonSession.Flush();
return id;
}
catch (Exception ex) { Console.WriteLine(ex.Message); }
return null; } //修改
public bool UpdateEntities(T entity)
{
try
{
Singleton.CreateInstance.SingletonSession.Update(entity);
Singleton.CreateInstance.SingletonSession.Flush();
return true;
}
catch (Exception ex) { Console.WriteLine(ex.Message); } return false;
}
//修改
public bool UpdateEntities(string entityName, object obj)
{
try
{
Singleton.CreateInstance.SingletonSession.Update(entityName, obj);
Singleton.CreateInstance.SingletonSession.Flush();
return true;
}
catch (Exception ex) { Console.WriteLine(ex.Message); } return false;
}
//删除
public bool DeleteEntities(T entity)
{
try
{
Singleton.CreateInstance.SingletonSession.Delete(entity);
Singleton.CreateInstance.SingletonSession.Flush();
return true;
}
catch (Exception ex) { Console.WriteLine(ex.Message); } return false;
}
//删除
public bool DeleteEntities(string entityName, object obj)
{
try
{
Singleton.CreateInstance.SingletonSession.Delete(entityName, obj);
Singleton.CreateInstance.SingletonSession.Flush();
return true;
}
catch (Exception ex) { Console.WriteLine(ex.Message); }
return false;
}
//删除
public bool DeleteEntities(string query)
{
try
{
Singleton.CreateInstance.SingletonSession.Delete(query); Singleton.CreateInstance.SingletonSession.Flush();
return true;
}
catch (Exception ex) { Console.WriteLine(ex.Message); }
return false;
}
//删除
public bool DeleteEntities(string query, object[] values, Type.IType[] types)
{
try
{
Singleton.CreateInstance.SingletonSession.Delete(query, values, types);
Singleton.CreateInstance.SingletonSession.Flush();
return true;
}
catch (Exception ex) { Console.WriteLine(ex.Message); }
return false;
} //查询
public IList<T> LoadEntities(Func<T, bool> wherelambda)
{
return Singleton.CreateInstance.SingletonSession.Query<T>() .Where(wherelambda).ToList<T>(); }
//查询
public IList<T> LoadEntities(string queryString)
{
IQuery query = Singleton.CreateInstance.SingletonSession.CreateQuery(queryString);
return query.List<T>();
}
//分页
public IList<T> LoadPagerEntities<S>(int pageSize, int pageIndex, out int total,
Func<T, bool> whereLambda, bool isAsc, Func<T, S> orderByLambda)
{
var tempData = Singleton.CreateInstance.SingletonSession.Query<T>().Where<T>(whereLambda); total = tempData.Count();
//排序获取当前页的数据
if (isAsc)
{
tempData = tempData.OrderBy<T, S>(orderByLambda).
Skip<T>(pageSize * (pageIndex - )).
Take<T>(pageSize).ToList();
}
else
{
tempData = tempData.OrderByDescending<T, S>(orderByLambda).
Skip<T>(pageSize * (pageIndex - )).
Take<T>(pageSize).ToList();
}
return tempData.ToList();
}
////分页 System.Linq.Expressions.Expression<Func<T, bool>>
public IList<T> LoadPagerEntities<S>(PageResult pagsinfo, out int total, Func<T, bool> whereLambda, bool isAsc, System.Linq.Expressions.Expression<Func<T, object>> orderByLambda)
{
//检查查询变量
if (pagsinfo.pageIndex < )
throw new ArgumentException("当前页数不能小于0", "pageIndex"); if (pagsinfo.pageSize <= )
throw new ArgumentException("每页记录数不能小于0", "pageCount"); int skip, take; skip = pagsinfo.pageSize*(pagsinfo.pageIndex - ) ;
take = pagsinfo.pageSize; var queryOver = Singleton.CreateInstance.SingletonSession.Query<T>().Where(whereLambda);
var Ovorder = Singleton.CreateInstance.SingletonSession.Query<T>().Where(whereLambda);
total = Ovorder.ToList().Count;
if (isAsc) return queryOver.AsQueryable().OrderBy(orderByLambda).Skip(skip).Take(take).ToList(); else
return queryOver.AsQueryable().OrderByDescending(orderByLambda).Skip(skip).Take(take).ToList(); } /// <summary>
/// 执行sql分页
/// </summary>
public DataTable LoadPagerEntities(PageResult pagsinfo, out int total, string whereLambda, string orderByLambda)
{
if (pagsinfo.pageIndex < )
throw new ArgumentException("当前页数不能小于0", "pageIndex"); if (pagsinfo.pageSize <= )
throw new ArgumentException("每页记录数不能小于0", "pageCount"); if (string.IsNullOrWhiteSpace(whereLambda))
whereLambda = " 1=1 "; int skip, take;
//(@pageIndex-1)*@pageSize+1 AND @pageIndex*@pageSize
skip = (pagsinfo.pageSize + ) * (pagsinfo.pageIndex - );
take = (pagsinfo.pageSize * pagsinfo.pageIndex);
string queryString1 = string.Format("select ROW_NUMBER() OVER( ORDER BY {0}) AS RowNumber,* from {1} where {2} ", orderByLambda, typeof(T).Name, whereLambda);
string queryString = string.Format(@"select *
from(
{0}
) T where RowNumber BETWEEN {1} and {2} ", queryString1, skip, take); ISQLQuery query1 = Singleton.CreateInstance.SingletonSession.CreateSQLQuery(queryString1);
total = query1.List().Count;
using (IDbCommand command = Singleton.CreateInstance.SingletonSession.Connection.CreateCommand())
{
command.CommandText = queryString; IDataReader reader = command.ExecuteReader();
DataTable result = new DataTable();
result.Load(reader);
return result;
// return reader.GetSchemaTable();
}
} public IList ExecuteSQL(string queryString)
{ ISQLQuery query = Singleton.CreateInstance.SingletonSession.CreateSQLQuery(queryString);
return query.List(); }
//获取单条
public T GetSingleModel(T entity, object id)
{
System.Type types = typeof(T);
object obj= Singleton.CreateInstance.SingletonSession.Get(types.Name, id);
if (obj == null) return null;
return obj as T;
}
//获取单条
public T GetSingleModel(Func<T, bool> wherelambda)
{
System.Type types = typeof(T);
var obj = Singleton.CreateInstance.SingletonSession.Query<T>().Where(wherelambda).ToList<T>().FirstOrDefault();
if (obj == null) return null;
return obj as T;
}
}
前端调用验证部分:
[Permission]--标示为权限验证
public class AdminControllerBase : Controller--其他Controller继承此类
Permission继承AuthorizeAttribute
/// <summary>
/// 权限拦截
/// </summary>
public class PermissionAttribute : AuthorizeAttribute
{
/// <summary>
/// 登陆页面
/// </summary>
public class PageUrl
{
public string Controller { get; set; }
public string Action { get; set; }
public string Url
{
get { return string.Format("{0}/{1}", Controller, Action); }
}
}
private PageUrl url; //重写Authorization
public override void OnAuthorization(AuthorizationContext filterContext)
{ if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
} //获取当前页面地址
url = new PageUrl();
url.Controller = filterContext.RouteData.Values["controller"] as string;
url.Action = filterContext.RouteData.Values["action"] as string; //判断用户是否登录
// string Token=Caching.Get("adminLogin-key").ToString();//缓存
Model.adminlogin loginModel = HttpContext.Current.Session[CMSKeys.SESSION_ADMIN_INFO] as Model.adminlogin;
//NHibernate.CMS.RedisFramework.RedisHelper.Single_Get_Itme<Model.adminlogin>(RedisKeys.REDIS_KEY_ADMINLOGIN + Token); if (loginModel==null)
{
// 未登录,跳转至登录页面
filterContext.Result = new RedirectResult("/Home/Login");
return;
}
else
{ if (!AuthorizeCore(filterContext.HttpContext))
{
filterContext.Result = new RedirectResult("/Home/Error/premission");
//filterContext.HttpContext.Response.Write("");
}
//redirect to login page
}
} /// <summary>
/// 重写AuthorizeAttribute的AuthorizeCore方法
/// </summary>
/// <param name="httpContext"></param>
/// <returns></returns>
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
bool result = false;
//string Token = Caching.Get("adminLogin-key").ToString();//缓存
Model.adminlogin loginModel = HttpContext.Current.Session[CMSKeys.SESSION_ADMIN_INFO] as Model.adminlogin;
//NHibernate.CMS.RedisFramework.RedisHelper.Single_Get_Itme<Model.adminlogin>(RedisKeys.REDIS_KEY_ADMINLOGIN + Token); //获取登陆标示
if (loginModel != null)
{ //进行权限校验 string action = url.Action;
string controller = url.Controller;
//如果是admin 拥有所有权限
if (loginModel.UserName == "admin") return true; Isys_actionService action_bll = new sys_actionService();//模块功能信息表
Isys_acl_userService acl_user_bll = new sys_acl_userService();//用户权限控制信息表
Isys_acl_groupService acl_group_bll = new sys_acl_groupService();//分组权限控制信息表
Isys_group_userService group_user_bll = new sys_group_userService();//用户与用户组信息表 var actionModel = action_bll.GetSingleModel(o => o.actionKey == action && o.moduleKey == controller);
if (actionModel == null) return false;//表示没找到 action var acl_userModel = acl_user_bll.GetSingleModel(w => w.actionID == actionModel.actionID && w.userID == loginModel.UserID);
if (acl_userModel != null) return true;//表示有该权限
var group_userModel = group_user_bll.GetSingleModel(k => k.userID == loginModel.UserID); var acl_groupModel = acl_group_bll.GetSingleModel(o => o.groupID == group_userModel.groupID && o.actionID == actionModel.actionID);
if (acl_groupModel != null)
result = acl_groupModel.access; }
return result;
} }
到此 验证机制主要部分已经写完就剩下在表里面添加数据测试了。
登陆测试
以上admind登陆的
测试a
简单的MVC 权限管理的更多相关文章
- mvc 权限管理 demo
http://blog.csdn.net/zht666/article/details/8529646 new http://www.cnblogs.com/fengxing/archive/2012 ...
- 开篇ASP.NET MVC 权限管理系列
开篇 [快乐编程系列之ASP.NET MVC 权限管理系列]一.开篇 用了好长一段时间的ASP.NET MVC,感觉MVC真的是很好用,最近一年左右做了两个中小型项目,觉得还是很多地方不是很熟悉的 ...
- ci中简单实用的权限管理
实用的权限管理 对多数网站来说,使用完整的rbac权限管理杀鸡用牛刀绝对的吃力不讨好,因为我们只是简单分角色然后对角色进行管理行使其相对于的角色赋予的权限; 在实际的开发中用位运算来对权限进行验证是十 ...
- Yii2系列教程五:简单的用户权限管理
上一篇文章讲了用户的注册,验证和登录,这一篇文章按照约定来说说Yii2之中的用户和权限控制. 你可以直接到Github下载源码,以便可以跟上进度,你也可以重头开始,一步一步按照这个教程来做. 鉴于本教 ...
- easyUI+mvc权限管理后台
通过按钮和菜单,组合成基本的功能,菜单的功能可以编码修改,但浏览功能是菜单基本的入口,只有角色赋予了浏览功能,才能访问. 基本按钮表 菜单模块 菜单分配按钮 角色授权 下面是对一张表的基本操作 模型 ...
- 利用反射及ActionFilterAttribute实现MVC权限管理
1.利用反射获取当前程序集下的所有控制器和方法,拼接后写入到数据库. public void GetRightInfo() { ; var controllerTypes = Assembly.Get ...
- php 简单权限管理实现
权限管理介绍.与简单实现思想 权限管理 此函数为模块访问权限管理 实现思路为:根据传进来的权限值,进入不同的权限获取区间,然后根据模块名字判断是否有这个模块的访问权限 使用说明:在每一个模块开始之前调 ...
- ASP.NET权限管理
ASP.NET Web Forms权限管理: 我要将一个文件夹只能让一个用户组访问怎么办? 可否在网站根目录下的web.config里这样设置: <location path="adm ...
- Asp.Net MVC+BootStrap+EF6.0实现简单的用户角色权限管理
这是本人第一次写,写的不好的地方还忘包含.写这个的主要原因是想通过这个来学习下EF的CodeFirst模式,本来也想用AngularJs来玩玩的,但是自己只会普通的绑定,对指令这些不是很熟悉,所以就基 ...
随机推荐
- 优先队列 POJ 3253 Fence Repair
题目传送门 题意:一块木板按照某个顺序切成a[1], a[2]...a[n]的长度,每次切都会加上该两段木板的长度,问选择什么顺序切能使得累加和最小 分析:网上说这是哈夫曼树.很容易想到先切掉最长的, ...
- zabbix 安装小结
其实很简单的东西,结果折腾了好久.首先去官网 下个source,然后按照文档来 https://www.zabbix.com/documentation/3.2/manual/installation ...
- 18.3.1获得Class对象
package d18_3_1; /** * Java中的java.lang.Class,简单理解就是为每个java对象的类型标识的类, * 虚拟机使用运行时类型信息选择正确的执行方法,用来保存这些运 ...
- Android屏幕适配-安卓切图
一.Android中的单位 1.dp(dip):density-independent pixels,这并不是一个绝对的单位,而只是一个相对的概念,代表的是屏幕写对角线上每inch上像素点的个数. 2 ...
- CentOS 6.9:MySQL Daemon failed to start.
[root@Server_1 12:02:58 ~ 25]#service mysqld start MySQL Daemon failed to start.Starting mysqld: [ro ...
- CentOS6.5下安装Redis2.8.6和phpredis2.2.4扩展
一.版本说明 CentOS版本 [plain]view plaincopyprint? [root@localhost ~]# uname Linux [root@localhost ~]# unam ...
- 动手实现 Redux(五):不要问为什么的 reducer
经过了这么多节的优化,我们有了一个很通用的 createStore: function createStore (state, stateChanger) { const listeners = [] ...
- 基于ABP的Easyui admin framework正式开放源代码
下载&反馈:http://www.webplus.org.cn v1.0 (2016/9/21) EF6+MVC5+API2+Easyui1.4.2开发 后台管理不使用iframe,全ajax ...
- CF985D Sand Fortress
思路: 很奇怪的结论题,不好想.参考了http://codeforces.com/blog/entry/59623 实现: #include <bits/stdc++.h> using n ...
- BZOJ1132: [POI2008]Tro(叉积 排序)
题意 世上最良心题目描述qwq 平面上有N个点. 求出所有以这N个点为顶点的三角形的面积和 N<=3000 Sol 直接模拟是$n^3$的. 考虑先枚举一个$i$,那么我们要算的就是$\sum_ ...