简单的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来玩玩的,但是自己只会普通的绑定,对指令这些不是很熟悉,所以就基 ...
随机推荐
- 在服务器上执行hbase的jar包
hadoop命令执行hbase应用jar包时的环境变量加载问题 Apache HBase ™ Reference Guide HBase, MapReduce, and the CLASSPATH
- 模拟赛01 T3 盖房子
题面 http://zhengruioi.com/problem/248 题解 三重容斥(说是两重也行吧) 我们来看题目的约束 ①有k个位置不能放(k≤8) ②每行每列至少一个 ③正负对角线至少一个 ...
- Educational Codeforces Round 24 D
Alice and Bob got very bored during a long car trip so they decided to play a game. From the window ...
- [已读]编写高质量代码 改善JavaScript程序的188个建议
吐槽一万遍,买的最后悔的一本,没有之一,大量篇幅抄袭<高性能javascript>,我记得还有部分抄袭<javascript精粹>,<javascript模式>有没 ...
- PKU_campus_2018_A Wife
思路: 题目链接http://poj.openjudge.cn/practice/C18A/ 先说一个结论,每一天要么7要么0,由此提供一种状态压缩dp的解法. 实现: #include <bi ...
- poj2677 Tour
题意: 双调欧几里得旅行商问题. 思路: dp.定义dp[i][j](i <= j)为从点j从右向左严格按照x坐标递减顺序走到点1,之后再从点1从左向右严格按照x坐标递增的顺序走到点i,并且在此 ...
- Android studio 时间选择器
相当简单加载 gradle文件然后做一个textview即可. 1.首先我们要在build.gradle中写上这一行代码: compile 'com.feezu.liuli:timeselector: ...
- Android单独继承View类来实现自定义控件
一个单独继承view类来实现自定义控件,在该方法中,需要重写ondraw方法来绘制自己所需要的控件,下面也以一个简单的例子来说明如何实现自定义控件.该方法可以实现所需要的所有的自定义控件. 属性文件中 ...
- UI常用字体定义和继承的实例,ResearchKitCode
#import <UIKit/UIKit.h> @interface UIFont (APCAppearance) + (UIFont*) appRegularFontWithSize: ...
- VBA 连接sql server的用法
cnnstr = "Provider=sqloledb;Data Source=192.211.21.8;Initial Catalog=pub;UID=账号;PWD=密码" VB ...