实现菜单角色授权功能,完善菜单查询功能

This commit is contained in:
sunnian 2016-10-28 11:12:25 +08:00
parent bb70090a00
commit 2e30c81245
7 changed files with 180 additions and 2 deletions

View File

@ -231,6 +231,22 @@
Role.getRolesByGroupId = function (groupId) {
};
//查询菜单对应角色
Role.getRolesByMenuId = function (menuId, callback) {
$.ajax({
url: '../api/Roles/' + menuId,
data: { "": "menu" },
type: 'POST',
success: function (result) {
callback(result);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
callback();
}
});
};
Role.saveRolesByUserId = function (userId, roleIds, callback) {
$.ajax({
url: '../api/Roles/' + userId,
@ -245,6 +261,21 @@
});
}
//保存菜单对应角色
Role.saveRolesByMenuId = function (menuId, roleIds, callback) {
$.ajax({
url: '../api/Roles/' + menuId,
data: { "roleIds": roleIds, "type": "menu" },
type: 'PUT',
success: function (result) {
callback(result);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
callback();
}
});
};
Group = {};
Group.getGroupsByUserId = function (userId) {

View File

@ -30,6 +30,10 @@ namespace Bootstrap.Admin.Controllers
{
return RoleHelper.RetrieveRolesByUserId(id.ToString());
}
else if(value == "menu")
{
return RoleHelper.RetrieveRolesByMenuId(id.ToString());
}
else
{
return null;
@ -47,6 +51,8 @@ namespace Bootstrap.Admin.Controllers
string roleIds = json.roleIds;
if (json.type == "user")
return RoleHelper.SaveRolesByUserId(id, roleIds);
if (json.type == "menu")
return RoleHelper.SavaRolesByMenuId(id,roleIds);
return false;
}
/// <summary>

View File

@ -25,6 +25,10 @@ namespace Bootstrap.Admin.Models
{
data = data.Where(t => t.Name.Contains(Name));
}
if (!string.IsNullOrEmpty(Category))
{
data = data.Where(t => t.Category.ToString().Equals(Category));
}
var ret = new QueryData<Menu>();
ret.total = data.Count();
// TODO: 通过option.Sort属性判断对那列进行排序现在统一对名称列排序

View File

@ -11,7 +11,42 @@
Url: "url",
Category: "category"
}
})
}),
click: {
assign: [{
id: 'btn_assignRole',
click: function (row) {
Role.getRolesByMenuId(row.ID, function (roles) {
$("#dialogRole .modal-title").text($.format('{0}-角色授权窗口', row.Name));
var data = $.map(roles, function (element, index) {
if (element.IsSelect == 1) {
return $.format('<div class="checkbox"><label><input type="checkbox" value="{0}" checked="checked">{1}</label></div>', element.ID, element.RoleName);
} else if (element.IsSelect == 0) {
return $.format('<div class="checkbox"><label><input type="checkbox" value="{0}">{1}</label></div>', element.ID, element.RoleName);
}
}).join('');
$('#dialogRole form').html(data);
$('#dialogRole').modal('show');
});
}
}, {
id: 'btnSubmitUserRole',
click: function (row) {
var menuId = row.ID;
var roleIds = $('#dialogRole :checked').map(function (index, element) {
return $(element).val();
}).toArray().join(',');
Role.saveRolesByMenuId(menuId, roleIds, function (result) {
if (result) {
$('#dialogRole').modal("hide");
swal("成功", "修改角色", "success");
} else {
swal("失败", "修改角色", "error");
}
});
}
}]
}
});
$('table').smartTable({

View File

@ -27,6 +27,11 @@
</div>
</form>
}
@section toolbar {
<button id="btn_assignRole" type="button" class="btn btn-info">
<span class="fa fa-sitemap" aria-hidden="true"></span>指派角色
</button>
}
@section modal {
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
@ -62,3 +67,6 @@
</form>
</div>
}
@section customModal {
@Html.Partial("RoleConfig")
}

View File

@ -29,6 +29,7 @@
<add key="UserData-CodeUserHelper-" interval="600" desc="用户信息缓存" />
<add key="RoleData-CodeRoleHelper" interval="600" desc="角色信息缓存" />
<add key="RoleData-CodeRoleHelper-" interval="600" desc="角色信息缓存" />
<add key="RoleData-CodeRoleHelper-Navigation" interval="600" desc="菜单角色信息缓存"/>
<add key="MenuData-CodeMenuHelper" interval="600" desc="菜单信息缓存" />
</cacheManager>

View File

@ -17,6 +17,7 @@ namespace Bootstrap.DataAccess
{
private const string RoleDataKey = "RoleData-CodeRoleHelper";
private const string RoleUserIDDataKey = "RoleData-CodeRoleHelper-";
private const string RoleNavigationIDDataKey = "RoleData-CodeRoleHelper-Navigation";
/// <summary>
/// 查询所有角色
/// </summary>
@ -196,6 +197,98 @@ namespace Bootstrap.DataAccess
return ret;
}
/// <summary>
/// 查询某个菜单所拥有的角色
/// </summary>
/// <param name="menuId"></param>
/// <returns></returns>
public static IEnumerable<Role> RetrieveRolesByMenuId(string menuId)
{
string sql = "select *,case when (ID in( select RoleID from NavigationRole where NavigationID=@NavigationID)) then 1 else 0 end as IsSelect from Roles";
string k = string.Format("{0}{1}", RoleNavigationIDDataKey, menuId);
var ret = CacheManager.GetOrAdd(k, CacheSection.RetrieveIntervalByKey(RoleNavigationIDDataKey), key =>
{
List<Role> Roles = new List<Role>();
DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.Text, sql);
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@NavigationID", menuId, ParameterDirection.Input));
try
{
using (DbDataReader reader = DBAccessManager.SqlDBAccess.ExecuteReader(cmd))
{
while (reader.Read())
{
Roles.Add(new Role()
{
ID = (int)reader[0],
RoleName = (string)reader[1],
Description = (string)reader[2],
IsSelect = (int)reader[3]
});
}
}
}
catch (Exception ex) { ExceptionManager.Publish(ex); }
return Roles;
}, CacheSection.RetrieveDescByKey(RoleNavigationIDDataKey));
return ret;
}
/// <summary>
/// 保存菜单角色关系
/// </summary>
/// <param name="id"></param>
/// <param name="value"></param>
/// <returns></returns>
public static bool SavaRolesByMenuId(int id, string value)
{
DataTable dt = new DataTable();
dt.Columns.Add("NavigationID", typeof(int));
dt.Columns.Add("RoleID", typeof(int));
//判断用户是否选定角色
if (!string.IsNullOrEmpty(value))
{
string[] roleIDs = value.Split(',');
foreach (string roleID in roleIDs)
{
DataRow row = dt.NewRow();
row["NavigationID"] = id;
row["RoleID"] = roleID;
dt.Rows.Add(row);
}
}
string sql = "delete from NavigationRole where NavigationID=@NavigationID;";
using (DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.Text, sql))
{
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@NavigationID", id, ParameterDirection.Input));
using (TransactionPackage transaction = DBAccessManager.SqlDBAccess.BeginTransaction())
{
using (SqlBulkCopy bulk = new SqlBulkCopy((SqlConnection)transaction.Transaction.Connection, SqlBulkCopyOptions.Default, (SqlTransaction)transaction.Transaction))
{
bulk.BatchSize = 1000;
bulk.DestinationTableName = "NavigationRole";
bulk.ColumnMappings.Add("NavigationID", "NavigationID");
bulk.ColumnMappings.Add("RoleID", "RoleID");
bool ret = true;
try
{
DBAccessManager.SqlDBAccess.ExecuteNonQuery(cmd, transaction);
bulk.WriteToServer(dt);
transaction.CommitTransaction();
ClearCache();
}
catch (Exception ex)
{
ret = false;
transaction.RollbackTransaction();
}
return ret;
}
}
}
}
// 更新缓存
private static void ClearCache()
{