Skip to content

Commit

Permalink
简化Role页面接收权限设置的逻辑
Browse files Browse the repository at this point in the history
  • Loading branch information
nnhy committed Nov 6, 2024
1 parent 024280c commit b1f74ea
Show file tree
Hide file tree
Showing 5 changed files with 22 additions and 353 deletions.
140 changes: 6 additions & 134 deletions NewLife.Cube/Areas/Admin/Controllers/RoleController.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using System.ComponentModel;
using NewLife.Web;
using XCode;
using XCode.Membership;

namespace NewLife.Cube.Areas.Admin.Controllers;
Expand Down Expand Up @@ -39,28 +38,17 @@ protected override IEnumerable<Role> Search(Pager p)
return Role.Search(p["dtStart"].ToDateTime(), p["dtEnd"].ToDateTime(), p["Q"], p);
}

/// <summary>
/// 添加权限授权
/// </summary>
/// <summary>验证实体对象</summary>
/// <param name="entity"></param>
/// <param name="type"></param>
/// <param name="post"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public override async Task<ApiResponse<Role>> Insert(Role entity)
protected override Boolean Valid(Role entity, DataObjectMethodType type, Boolean post)
{
// 检测避免乱用Add/id
if (Factory.Unique.IsIdentity && entity[Factory.Unique.Name].ToInt() != 0)
throw new Exception("我们约定添加数据时路由id部分默认没有数据,以免模型绑定器错误识别!");

if (!Valid(entity, DataObjectMethodType.Insert, true)) return new ApiResponse<Role>(500, "验证失败!", null);
var rs = base.Valid(entity, type, post);

var rs = false;
var err = "";
try
if (post && type is DataObjectMethodType.Insert or DataObjectMethodType.Update)
{
entity.CreateTime = DateTime.Now;
entity.CreateIP = GetHostAddresses();
entity.Enable = true;

// 保存权限项
var menus = XCode.Membership.Menu.Root.AllChilds;
var dels = new List<Int32>();
Expand All @@ -77,7 +65,6 @@ public override async Task<ApiResponse<Role>> Insert(Role entity)
{
// 遍历所有权限子项
var any = false;

foreach (var pf in item.Permissions)
{
var has2 = GetBool("pf" + item.ID + "_" + pf.Key);
Expand All @@ -93,127 +80,12 @@ public override async Task<ApiResponse<Role>> Insert(Role entity)
if (!any & !entity.Has(item.ID)) entity.Set(item.ID);
}
}

// 删除已经被放弃权限的项
foreach (var item in dels)
{
if (entity.Has(item)) entity.Permissions.Remove(item);
}

OnInsert(entity);

//var fs = await SaveFiles(entity);
//if (fs.Count > 0) OnUpdate(entity);
if (LogOnChange) LogProvider.Provider.WriteLog("Insert", entity);

rs = true;
}
catch (ArgumentException aex)
{
err = aex.Message;
ModelState.AddModelError(aex.ParamName, aex.Message);
}
catch (Exception ex)
{
err = ex.Message;
ModelState.AddModelError("", ex.Message);
}

var msg = "";
if (!rs)
{
WriteLog("Add", false, err);

msg = SysConfig.Develop ? "添加失败!" + err : "添加失败!";
//ViewBag.StatusMessage = msg;

// 添加失败,ID清零,否则会显示保存按钮
entity[Role.Meta.Unique.Name] = 0;

return new ApiResponse<Role>(500, msg);
}

//ViewBag.StatusMessage = "添加成功!";
msg = "添加成功!";

//添加明细
rs = AddDetailed(entity);
if (!rs)
{
WriteLog("Edit", false, err);

msg = SysConfig.Develop ? "添加明细失败!" + err : "添加明细失败!";
//ViewBag.StatusMessage = msg;

// 添加失败,ID清零,否则会显示保存按钮
entity[Role.Meta.Unique.Name] = 0;

return new ApiResponse<Role>(500, msg);
}

return new ApiResponse<Role>(0, msg, entity);
}

/// <summary>保存</summary>
/// <param name="entity"></param>
/// <returns></returns>
public override async Task<ApiResponse<Role>> Update(Role entity)
{
// 保存权限项
var menus = XCode.Membership.Menu.Root.AllChilds;
//var pfs = EnumHelper.GetDescriptions<PermissionFlags>().Where(e => e.Key > PermissionFlags.None);
var dels = new List<Int32>();
// 遍历所有权限资源
foreach (var item in menus)
{
// 是否授权该项
var has = GetBool("p" + item.ID);
if (!has)
dels.Add(item.ID);
else
{
// 遍历所有权限子项
var any = false;
foreach (var pf in item.Permissions)
{
var has2 = GetBool("pf" + item.ID + "_" + pf.Key);

if (has2)
entity.Set(item.ID, (PermissionFlags)pf.Key);
else
entity.Reset(item.ID, (PermissionFlags)pf.Key);
any |= has2;
}
// 如果原来没有权限,这是首次授权,且右边没有勾选任何子项,则授权全部
if (!any & !entity.Has(item.ID)) entity.Set(item.ID);
}
}
// 删除已经被放弃权限的项
foreach (var item in dels)
if (entity.Has(item)) entity.Permissions.Remove(item);

return await base.Update(entity);
}

/// <summary>
/// 获取客户端IP地址
/// </summary>
/// <returns></returns>
protected virtual String GetHostAddresses() => HttpContext.GetUserHost();

/// <summary>添加实体主表对应的从表记录</summary>
/// <param name="entity"></param>
/// <returns></returns>
protected virtual Boolean AddDetailed(IEntity entity) => entity != null;

/// <summary>验证实体对象</summary>
/// <param name="entity"></param>
/// <param name="type"></param>
/// <param name="post"></param>
/// <returns></returns>
protected override Boolean Valid(Role entity, DataObjectMethodType type, Boolean post)
{
var rs = base.Valid(entity, type, post);

// 清空缓存
if (post) Role.Meta.Session.ClearCache($"{type}-{entity}", true);
Expand Down
36 changes: 7 additions & 29 deletions NewLife.Cube/Common/EntityController.cs
Original file line number Diff line number Diff line change
@@ -1,20 +1,15 @@
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc;
using NewLife.Cube.Entity;
using NewLife.Data;
using NewLife.Log;
using NewLife.Reflection;
using NewLife.Remoting;
using XCode;
using XCode.Membership;

namespace NewLife.Cube;

/// <summary>实体控制器基类</summary>
/// <typeparam name="TEntity">实体类型</typeparam>
/// <typeparam name="TModel">数据模型,用于接口数据传输</typeparam>
public partial class EntityController<TEntity, TModel> : ReadOnlyEntityController<TEntity> where TEntity : Entity<TEntity>, new()
public partial class EntityController<TEntity, TModel>
{
#region 默认Action
/// <summary>删除数据</summary>
Expand Down Expand Up @@ -52,7 +47,7 @@ public virtual ApiResponse<TEntity> Delete([Required] String id)
public virtual async Task<ApiResponse<TEntity>> Insert(TModel model)
{
// 实例化实体对象,然后拷贝
if (model is TEntity entity) return await Insert(entity);
if (model is TEntity entity) return await ProcessInsert(entity);

entity = Factory.Create(false) as TEntity;

Expand All @@ -61,14 +56,14 @@ public virtual async Task<ApiResponse<TEntity>> Insert(TModel model)
else
entity.Copy(model);

return await Insert(entity);
return await ProcessInsert(entity);
}

/// <summary>添加数据</summary>
/// <param name="entity"></param>
/// <returns></returns>
[NonAction]
public virtual async Task<ApiResponse<TEntity>> Insert(TEntity entity)
protected virtual async Task<ApiResponse<TEntity>> ProcessInsert(TEntity entity)
{
// 检测避免乱用Add/id
if (Factory.Unique.IsIdentity && entity[Factory.Unique.Name].ToInt() != 0)
Expand Down Expand Up @@ -114,7 +109,7 @@ public virtual async Task<ApiResponse<TEntity>> Insert(TEntity entity)
public virtual async Task<ApiResponse<TEntity>> Update(TModel model)
{
// 实例化实体对象,然后拷贝
if (model is TEntity entity) return await Update(entity);
if (model is TEntity entity) return await ProcessUpdate(entity);

var uk = Factory.Unique;
var key = model is IModel ext ? ext[uk.Name] : model.GetValue(uk.Name);
Expand All @@ -127,14 +122,14 @@ public virtual async Task<ApiResponse<TEntity>> Update(TModel model)
else
entity.Copy(model, false, uk.Name);

return await Update(entity);
return await ProcessUpdate(entity);
}

/// <summary>更新数据</summary>
/// <param name="entity"></param>
/// <returns></returns>
[NonAction]
public virtual async Task<ApiResponse<TEntity>> Update(TEntity entity)
protected virtual async Task<ApiResponse<TEntity>> ProcessUpdate(TEntity entity)
{
try
{
Expand All @@ -161,21 +156,4 @@ public virtual async Task<ApiResponse<TEntity>> Update(TEntity entity)
}
}
#endregion

#region 实体操作重载
/// <summary>添加实体对象</summary>
/// <param name="entity"></param>
/// <returns></returns>
protected virtual Int32 OnInsert(TEntity entity) => entity.Insert();

/// <summary>更新实体对象</summary>
/// <param name="entity"></param>
/// <returns></returns>
protected virtual Int32 OnUpdate(TEntity entity) => entity.Update();

/// <summary>删除实体对象</summary>
/// <param name="entity"></param>
/// <returns></returns>
protected virtual Int32 OnDelete(TEntity entity) => entity.Delete();
#endregion
}
8 changes: 0 additions & 8 deletions NewLife.Cube/Common/EntityController2.cs
Original file line number Diff line number Diff line change
@@ -1,16 +1,8 @@
using System.ComponentModel;
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using NewLife.Cube.Common;
using NewLife.Cube.Entity;
using NewLife.Cube.Extensions;
using NewLife.Cube.ViewModels;
using NewLife.Data;
using NewLife.Log;
using NewLife.Reflection;
using NewLife.Remoting;
using NewLife.Serialization;
using NewLife.Web;
using XCode;
using XCode.Configuration;
using XCode.Membership;
Expand Down
Loading

0 comments on commit b1f74ea

Please sign in to comment.