增加群组设置角色的功能

This commit is contained in:
liuchun_0206@163.com 2016-10-27 17:56:00 +08:00
parent db535b6e31
commit 96093f8d34
7 changed files with 179 additions and 36 deletions

View File

@ -247,7 +247,7 @@
Role.getRolesByUserId = function (userId, callback) {
processRolesData({ Id: userId, callback: callback, data: { type: "user" } });
};
Role.getRolesByGroupId = function (groupId) {
Role.getRolesByGroupId = function (groupId, callback) {
processRolesData({ Id: groupId, callback: callback, data: { type: "group" } });
};
Role.getRolesByMenuId = function (menuId, callback) {
@ -256,6 +256,9 @@
Role.saveRolesByUserId = function (userId, roleIds, callback) {
processRolesData({ Id: userId, callback: callback, method: "PUT", data: { type: "user", roleIds: roleIds } });
}
Role.saveRolesByGroupId = function (groupId, roleIds, callback) {
processRolesData({ Id: groupId, callback: callback, method: "PUT", data: { type: "group", roleIds: roleIds } });
}
Role.saveRolesByMenuId = function (menuId, roleIds, callback) {
processRolesData({ Id: menuId, callback: callback, method: "PUT", data: { type: "menu", roleIds: roleIds } });
};
@ -333,10 +336,10 @@
Group.saveGroupsByUserId = function (userId, groupIds, callback) {
processGroupsData({ Id: userId, callback: callback, method: "PUT", data: { type: "user", groupIds: groupIds } });
};
Group.getGroupsByRoleId = function (roleId,callback) {
Group.getGroupsByRoleId = function (roleId, callback) {
processGroupsData({ Id: roleId, callback: callback, data: { type: "role" } });
};
Group.saveGroupsByRoleId = function (roleId,groupIds,callback) {
Group.saveGroupsByRoleId = function (roleId, groupIds, callback) {
processGroupsData({ Id: roleId, callback: callback, method: "PUT", data: { type: "role", groupIds: groupIds } });
};
})(jQuery);

View File

@ -2,8 +2,10 @@
using Bootstrap.DataAccess;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using Newtonsoft.Json.Linq;
using System.Linq;
namespace Bootstrap.Admin.Controllers
{
@ -45,11 +47,10 @@ namespace Bootstrap.Admin.Controllers
}
return ret;
}
/// <summary>
///
/// <summary>根据GroupID获取
/// </summary>
/// <param name="id"></param>
/// <param name="value"></param>
/// <returns></returns>
[HttpPut]
public bool Put(int id, [FromBody]JObject value)
{

View File

@ -7,8 +7,48 @@
GroupName: "groupName",
Description: "groupDesc"
}
})
}),
click: {
assign: [{
id: 'btn_assignRole',
click: function (row) {
Role.getRolesByGroupId(row.ID, function (data) {
$("#dialogRole .modal-title").text($.format('{0}-角色授权窗口', row.GroupName));
$('#dialogRole form').html(data);
$('#dialogRole').modal('show');
});
}
}, {
id: 'btn_assignGroup',
click: function (row) {
var userId = row.ID;
}
}, {
id: 'btnSubmitUserRole',
click: function (row) {
var userId = row.ID;
var roleIds = $('#dialogRole :checked').map(function (index, element) {
return $(element).val();
}).toArray().join(',');
Role.saveRolesByGroupId(userId, roleIds, function (result) {
if (result) {
$('#dialogRole').modal("hide");
swal("成功", "修改角色", "success");
} else {
swal("失败", "修改角色", "error");
}
});
}
}]
},
success: function (src, data) {
if (src === 'save' && data.ID === $('#userId').val()) {
$('.username').text(data.DisplayName);
}
}
});
$('table').smartTable({
url: '../api/Groups', //请求后台的URL*

View File

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

View File

@ -3,6 +3,7 @@ using Longbow.Caching;
using Longbow.Caching.Configuration;
using Longbow.Data;
using Longbow.ExceptionManagement;
using Longbow.Data;
using System;
using System.Collections.Generic;
using System.Data;
@ -10,6 +11,7 @@ using System.Data.Common;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Data.SqlClient;
namespace Bootstrap.DataAccess
{
@ -19,8 +21,9 @@ namespace Bootstrap.DataAccess
public class RoleHelper
{
private const string RoleDataKey = "RoleData-CodeRoleHelper";
private const string RolebyGroupDataKey = "RoleData-CodeRoleHelper-";
private const string RoleUserIDDataKey = "RoleData-CodeRoleHelper-";
private const string RoleNavigationIDDataKey = "RoleData-CodeRoleHelper-Navigation-";
private const string RoleNavigationIDDataKey = "RoleData-CodeRoleHelper-Navigation";
/// <summary>
/// 查询所有角色
/// </summary>
@ -108,6 +111,8 @@ namespace Bootstrap.DataAccess
return ret;
}
/// <summary>
/// 查询某个用户所拥有的角色
/// </summary>
@ -206,15 +211,15 @@ namespace Bootstrap.DataAccess
/// <returns></returns>
public static IEnumerable<Role> RetrieveRolesByMenuId(int menuId)
{
string sql = "select r.ID, r.RoleName, r.[Description], case ur.RoleID when r.ID then 'checked' else '' end [status] from Roles r left join NavigationRole ur on r.ID = ur.RoleID and NavigationID = @NavigationID";
string k = string.Format("{0}{1}", RoleNavigationIDDataKey, menuId);
return CacheManager.GetOrAdd(k, CacheSection.RetrieveIntervalByKey(RoleUserIDDataKey), key =>
var ret = CacheManager.GetOrAdd(k, CacheSection.RetrieveIntervalByKey(RoleNavigationIDDataKey), key =>
{
List<Role> Roles = new List<Role>();
string sql = "select r.ID, r.RoleName, r.[Description], case ur.RoleID when r.ID then 'checked' else '' end [status] from Roles r left join NavigationRole ur on r.ID = ur.RoleID and NavigationID = @NavigationID";
try
{
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())
@ -231,15 +236,9 @@ namespace Bootstrap.DataAccess
}
catch (Exception ex) { ExceptionManager.Publish(ex); }
return Roles;
}, CacheSection.RetrieveDescByKey(RoleUserIDDataKey));
}, 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();
@ -281,6 +280,7 @@ namespace Bootstrap.DataAccess
}
catch (Exception ex)
{
ExceptionManager.Publish(ex);
ret = false;
transaction.RollbackTransaction();
}
@ -289,30 +289,102 @@ namespace Bootstrap.DataAccess
}
}
}
// 更新缓存
private static void ClearCache(string cacheKey = null)
{
CacheManager.Clear(key => string.IsNullOrEmpty(cacheKey) || key == cacheKey);
}
/// <summary>
/// 查询某个部门所拥有的角色
/// </summary>
/// <param name="menuId"></param>
/// 根据GroupId查询和该Group有关的所有Roles
/// author:liuchun
/// <param name="tId"></param>
/// <returns></returns>
public static IEnumerable<Role> RetrieveRolesByGroupId(int groupId)
public static IEnumerable<Role> RetrieveRolesByGroupId(int groupID)
{
return null;
string key = string.Format("{0}{1}", RolebyGroupDataKey, groupID);
return CacheManager.GetOrAdd(key, CacheSection.RetrieveIntervalByKey(RolebyGroupDataKey), k =>
{
List<Role> Roles = new List<Role>();
string sql= "select r.ID, r.RoleName, r.[Description], case ur.RoleID when r.ID then 'checked' else '' end [status] from Roles r left join RoleGroup ur on r.ID = ur.RoleID and GroupID = @GroupID";
DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.Text, sql);
try
{
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@GroupID", groupID, ParameterDirection.Input));
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],
Checked = (string)reader[3]
});
}
}
}
catch (Exception ex) { ExceptionManager.Publish(ex); }
return Roles;
}, CacheSection.RetrieveDescByKey(RolebyGroupDataKey));
}
/// <summary>
/// 保存部门角色关系
/// 根据GroupId更新Roles信息删除旧的Roles信息插入新的Roles信息
/// </summary>
/// <param name="id"></param>
/// <param name="value"></param>
/// <param name="p"></param>
/// <returns></returns>
public static bool SaveRolesByGroupId(int id, string value)
public static bool SaveRolesByGroupId(int gid, string value)
{
//构造表格
DataTable dt = new DataTable();
dt.Columns.Add("RoleID", typeof(int));
dt.Columns.Add("GroupID", typeof(int));
if (!string.IsNullOrEmpty(value))
{
string[] roles = value.Split(',');
foreach (string role in roles)
{
DataRow r = dt.NewRow();
r["RoleID"] = role;
r["GroupID"] = gid;
dt.Rows.Add(r);
}
}
var trans = DBAccessManager.SqlDBAccess.BeginTransaction();
try
{
using (DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.Text, string.Empty))
{
// 执行第一个sql
cmd.CommandText = "delete from RoleGroup where GroupID=@GroupID";
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@GroupID", gid, ParameterDirection.Input));
DBAccessManager.SqlDBAccess.ExecuteNonQuery(cmd, trans);
}
using (SqlBulkCopy bulk = new SqlBulkCopy((SqlConnection)trans.Transaction.Connection, SqlBulkCopyOptions.Default, (SqlTransaction)trans.Transaction))
{
bulk.BatchSize = 1000;
bulk.DestinationTableName = "RoleGroup";
bulk.ColumnMappings.Add("RoleID", "RoleID");
bulk.ColumnMappings.Add("GroupID", "GroupID");
bulk.WriteToServer(dt);
}
trans.CommitTransaction();
ClearCache();
return true;
}
catch (Exception ex)
{
ExceptionManager.Publish(ex);
trans.RollbackTransaction();
return false;
}
}
}
}

View File

@ -57,5 +57,21 @@ namespace Bootstrap.DataAccess.Tests
var result = RoleHelper.SaveRolesByUserId(1,"3");
Assert.IsTrue(result == true, "保存用户角色关系失败");
}
[TestMethod()]
public void RetrieveRoleByGroupIDTest()
{
var result = RoleHelper.RetrieveRolesByGroupId(1);
Assert.IsTrue((result.Count() == 8), "RetrieveRoleByGroupID测试失败");
}
[TestMethod()]
public void SaveRoleByGroupIDTest()
{
var result = RoleHelper.SaveRolesByGroupId(1,"1,2,3,4");
Assert.IsTrue(result, "SaveRoleByGroupID测试失败");
}
}
}