首页 > 代码库 > 简单的MVC 权限管理
简单的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 = http://www.mamicode.com/Singleton.CreateInstance.SingletonSession.Query().Where (whereLambda); total = tempData.Count(); //排序获取当前页的数据 if (isAsc) { tempData = tempData.OrderBy<T, S>(orderByLambda). Skip<T>(pageSize * (pageIndex - 1)). Take<T>(pageSize).ToList(); } else { tempData = tempData.OrderByDescending<T, S>(orderByLambda). Skip<T>(pageSize * (pageIndex - 1)). 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 < 0) throw new ArgumentException("当前页数不能小于0", "pageIndex"); if (pagsinfo.pageSize <= 0) throw new ArgumentException("每页记录数不能小于0", "pageCount"); int skip, take; skip = pagsinfo.pageSize*(pagsinfo.pageIndex - 1) ; 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 < 0) throw new ArgumentException("当前页数不能小于0", "pageIndex"); if (pagsinfo.pageSize <= 0) 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 + 1) * (pagsinfo.pageIndex - 1); 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 权限管理
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。