菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
413
0

.net5 core Razor项目实战系列之十:权限设置功能的实现(EFCore的批量删除与批量新增)

原创
05/13 14:22
阅读数 96326

权限设置可以针对部门和用户这两个层级,如果设置了部门的权限,

该部门下的所有用户将自动获得部门的权限,如果部门和用户都设置了权限则只取用户部分,忽略部门的权限。

操作流程是这样的:进入权限设置页---> 页面左边显示所有部门--->点部门超链接的时候显示该部门下的员工;

页面右边显示权限点,可以针对部门和员工设置权限,点保存按钮的时候存储到数据库,具体如下:

场景一、用户点【权限设置】时看到的效果如下:

此时提示用户去选择部门或用户,而且保存按钮是不可见的。

场景二、点左边的部门的时候,显示部门下的用户,同时右边显示部门名称和保存按钮,如下:

场景三、点左边部门下的用户的时候,右边显示用户名称,同时显示保存按钮,如下:

代码如下:

在 _Layout.cshtml中增加 【权限设置】菜单,如下:

<ul class="navbar-nav flex-grow-1">
    <li class="nav-item">
        <a class="nav-link text-dark" asp-area="" asp-page="/Index">Home</a>
    </li>

    <li class="nav-item">
        <a class="nav-link text-dark" asp-area="" asp-page="/Auth/DeptList">【部门管理】</a>
    </li>
    <li class="nav-item">
        <a class="nav-link text-dark" asp-area="" asp-page="/Auth/UserList">【用户管理】</a>
    </li>
    <li class="nav-item">
        <a class="nav-link text-dark" asp-area="" asp-page="/Auth/AuthSetting">【权限设置】</a>
    </li>

    <li class="nav-item">
        <a class="nav-link text-dark" asp-area="" asp-page="/Privacy">Privacy</a>
    </li>

    <li class="nav-item">
        @if (Context.User.Identity.IsAuthenticated)
        {
            <a class="nav-link text-dark" asp-area="" asp-page="/Auth/Signout">[登出]</a>
        }
        else
        {
            <a class="nav-link text-dark" asp-area="" asp-page="/Auth/Signin">[登录]</a>
        }
    </li>
</ul>

在/Auth文件夹下新增 AuthSetting.cshtml 文件,如下:

AuthSetting.cshtml 编码如下:

@page
@model AuthManagement.Pages.Auth.AuthSettingModel
@using AuthManagement.DbUtil.Entity;
@{
    ViewData["Title"] = "权限设置";
}
<style>
    .a1{color:#ffffff;}
    .a2{color:#000000;}
    .left  {float:left;width:200px;min-height:400px;border:solid 1px #c0c0c0;padding-top:2px;padding-bottom:4px;}
    .right {float:left;width:320px;min-height:400px;border:solid 1px #c0c0c0;padding-top:2px;padding-bottom:4px;}
    .dept  {width:180px;height:32px;background-color:#808080;margin-top:2px; text-align:center;margin-left:10px;}
    .user  {width:180px;height:32px;background-color:#F9EBE3;margin-top:2px; text-align:center;margin-left:10px;}
    .title {width:300px;height:32px; margin-left:10px;margin-top:20px; background-color:#e0e0e0; }
    .func  {margin-left:10px;margin-top:10px; }
    .target{width:300px;height:40px; text-align:center; line-height:40px; font-size:18px; font-weight:bold;}
    .send  {width:300px;margin-top:60px; text-align:center;}
</style>
<div>
    <!--左边区块显示部门及部门下的用户-->
    <div class="left">
        @foreach (TDept dept in Model.DeptList)
        {
            <div class="dept"><a class="a1" href="/Auth/AuthSetting?deptid=@dept.DeptId">@dept.DeptName</a></div>
            <!--遍历的部门==用户点击的部门就显示其下的用户-->
            if (Request.Query["deptid"] == dept.DeptId.ToString())
            {
                foreach (TUser user in Model.UserList)
                {
                <div class="user"><a class="a2" href="/Auth/AuthSetting?deptid=@user.DeptId&userid=@user.UserId">@user.UserName</a></div>
                }    
            }
        }
    </div>
    <!--右边区块显示权限点-->
    <div class="right">
        <form method="post">
            <div class="target">@Model.TargetInfo.TargetName</div>

            <div class="title">&nbsp;用户管理</div>
            <div class="func">
                @if (Model.AuthArray.Contains<string>("TUser-Add"))
                {
                    <input type="checkbox" name="funccode" value="TUser-Add" checked="checked" /><span>&nbsp;新增&nbsp;&nbsp;&nbsp;</span>
                }
                else
                {
                    <input type="checkbox" name="funccode" value="TUser-Add" /><span>&nbsp;新增 &nbsp;&nbsp;&nbsp;</span>
                }
                @if (Model.AuthArray.Contains<string>("TUser-Modify"))
                {
                    <input type="checkbox" name="funccode" value="TUser-Modify" checked="checked" /><span>&nbsp;修改&nbsp;&nbsp;&nbsp;</span>
                }
                else
                {
                    <input type="checkbox" name="funccode" value="TUser-Modify" /><span>&nbsp;修改&nbsp;&nbsp;&nbsp;</span>
                }
                @if (Model.AuthArray.Contains<string>("TUser-Lock"))
                {
                    <input type="checkbox" name="funccode" value="TUser-Lock" checked="checked" /><span>&nbsp;锁定&nbsp;&nbsp;&nbsp;</span>
                }
                else
                {
                    <input type="checkbox" name="funccode" value="TUser-Lock" /><span>&nbsp;锁定&nbsp;&nbsp;&nbsp;</span>
                }
                @if (Model.AuthArray.Contains<string>("TUser-Delete"))
                {
                    <input type="checkbox" name="funccode" value="TUser-Delete" checked="checked" /><span>&nbsp;删除&nbsp;&nbsp;&nbsp;</span>
                }
                else
                {
                    <input type="checkbox" name="funccode" value="TUser-Delete" /><span>&nbsp;删除&nbsp;&nbsp;&nbsp;</span>
                } 
            </div>
            <div class="title">&nbsp;部门管理</div>
            <div class="func">

                @if (Model.AuthArray.Contains<string>("TDept-Add"))
                {
                    <input type="checkbox" name="funccode" value="TDept-Add" checked="checked" /><span>&nbsp;新增 &nbsp; &nbsp; &nbsp;</span>
                }
                else
                {
                    <input type="checkbox" name="funccode" value="TDept-Add" /><span>&nbsp;新增 &nbsp; &nbsp; &nbsp;</span>
                }
                @if (Model.AuthArray.Contains<string>("TDept-Modify"))
                {
                    <input type="checkbox" name="funccode" value="TDept-Modify" checked="checked" /><span>&nbsp;修改 &nbsp; &nbsp; &nbsp;</span>
                }
                else
                {
                    <input type="checkbox" name="funccode" value="TDept-Modify" /><span>&nbsp;修改 &nbsp; &nbsp; &nbsp;</span>
                }
                @if (Model.AuthArray.Contains<string>("TDept-Cancel"))
                {
                    <input type="checkbox" name="funccode" value="TDept-Cancel" checked="checked" /><span>&nbsp;作废 &nbsp; &nbsp; &nbsp;</span>
                }
                else
                {
                    <input type="checkbox" name="funccode" value="TDept-Cancel" /><span>&nbsp;作废 &nbsp; &nbsp; &nbsp;</span>
                } 
            </div>

            @if (Model.TargetInfo.TargetId > 0)
            {
            <div class="send"><button type="submit">保存</button></div>
            }
        </form>
    </div>
    <div style="clear:both;"></div>
</div>

AuthSetting.cshtml.cs 编码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using AuthManagement.DbUtil.Entity;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace AuthManagement.Pages.Auth
{
    public class AuthSettingModel : PageModel
    {
        private readonly AuthDbContext _context;

        //构造函数中对 AuthDbContext 做依赖注入
        public AuthSettingModel(AuthDbContext context)
        {
            _context = context;
        }


        public List<TDept> DeptList { get; private set; }
        public List<TUser> UserList { get; private set; }
        public TargetInfo TargetInfo { get; private set; }
        public string[] AuthArray { get; private set; }

        private void InitDeptList() //初始化页面的部门列表
        {
            DeptList = _context.TDepts.Where<TDept>(dept => dept.IsValid == 1).ToList<TDept>();
        }

        private void InitUesrList() //初始化用户列表,如果没有点部门的时候为空
        {
            string deptId = Request.Query["deptid"];
            int did = Convert.ToInt32(deptId);
            UserList = _context.TUsers.Where<TUser>(x => x.DeptId == did).ToList<TUser>();
        }

        private void InitTargetInfo() //初始化权限设置对象信息
        {
            TargetInfo = new TargetInfo { TargetId = 0, TargetName = "请选择部门或用户" };
            string deptId = Request.Query["deptid"];
            string userId = Request.Query["userid"];
            if (!string.IsNullOrWhiteSpace(userId))
            {
                TUser user = _context.TUsers.Find(Convert.ToInt32(userId));
                TargetInfo.TargetId = Convert.ToInt32(userId);
                TargetInfo.TargetName = user.UserName;
            }
            else if (!string.IsNullOrWhiteSpace(deptId))
            {
                TDept dept = _context.TDepts.Find(Convert.ToInt32(deptId));
                TargetInfo.TargetId = Convert.ToInt32(deptId);
                TargetInfo.TargetName = dept.DeptName;
            }
        }

        private void InitAuthArray() //初始化权限数组,把该部门或用户的权限code都取出来(授权类型 1:部门,2:用户)
        {
            IQueryable<TAuth> authList = null;
            string deptId = Request.Query["deptid"];
            string userId = Request.Query["userid"];
            if (!string.IsNullOrWhiteSpace(userId))
            {
                authList = _context.TAuths.Where<TAuth>(x => x.TargetType == 2 && x.TargetId == Convert.ToInt32(userId));
            }
            else if (!string.IsNullOrWhiteSpace(deptId))
            {
                authList = _context.TAuths.Where<TAuth>(x => x.TargetType == 1 && x.TargetId == Convert.ToInt32(deptId));
            }
            if (authList == null || authList.Count() < 1)
            {
                AuthArray = new string[1] { "" };
            }
            else
            {
                //用LINQ把查询出来的权限集合中的funcCode找出来并转化成字符数据,
                //前端页面可以判断单个权限是否存在,决定checkbox是否要勾选。
                AuthArray = (from TAuth auth in authList select auth.FuncCode).ToArray<string>();
            }
        }


        public void OnGet() //第一次加载页面
        {
            InitDeptList();
            InitUesrList();
            InitTargetInfo();
            InitAuthArray();
        }


        public void OnPost() //点保存按钮的时候
        {
            string deptId = Request.Query["deptid"];
            string userId = Request.Query["userid"];

            string allFuncCode = Request.Form["funccode"];
            if (string.IsNullOrWhiteSpace(allFuncCode)) return;

            
            string[] arrCode = allFuncCode.Split(","); 
            if (!string.IsNullOrWhiteSpace(userId)) //优先处理用户的权限
            {
                int uid = Convert.ToInt32(userId);
                SaveUserAuth(arrCode, uid); //保存用户权限
            }
            else if (!string.IsNullOrWhiteSpace(deptId))
            {
                int did = Convert.ToInt32(deptId);
                SaveDeptAuth(arrCode, did); //保存部门权限
            }
            //初始化页面数据
            OnGet();
            Response.Redirect("/Auth/AuthSetting?deptid="+ deptId + "&userid="+ userId);
        }

        private void SaveUserAuth(string[] arrFuncCode, int userId) //保存用户权限
        { 
            //先将该用户已有的权限全部删除,然后再批量插入(授权类型 1:部门,2:用户)            
            List<TAuth> newList = new List<TAuth>();
            foreach (string str in arrFuncCode)
            {
                TAuth tauth = new TAuth
                {
                    CreateTime = DateTime.Now,
                    FuncCode = str,
                    TargetId = userId,
                    TargetType = 2
                };
                newList.Add(tauth);
            }
            IQueryable<TAuth> existList = _context.TAuths.Where<TAuth>(x => x.TargetType == 2 && x.TargetId == userId);
            _context.TAuths.RemoveRange(existList);//批量删除
            _context.TAuths.AddRange(newList);//批量增加
            _context.SaveChanges();//执行数据库操作
        }

        private void SaveDeptAuth(string[] arrFuncCode, int deptId) //保存部门权限
        {
            //先将该部门已有的权限全部删除,然后再批量插入(授权类型 1:部门,2:用户)
            List<TAuth> newList = new List<TAuth>();
            foreach (string str in arrFuncCode)
            {
                TAuth tauth = new TAuth
                {
                    CreateTime = DateTime.Now,
                    FuncCode = str,
                    TargetId = deptId,
                    TargetType = 1
                };
                newList.Add(tauth);
            }
            IQueryable<TAuth> existList = _context.TAuths.Where<TAuth>(x => x.TargetType == 1 && x.TargetId == deptId);
            _context.TAuths.RemoveRange(existList);//批量删除
            _context.TAuths.AddRange(newList);//批量增加
            _context.SaveChanges();//执行数据库操作
        } 
    }


    //为了页面处理数据方便,定义一个TargetInfo对象来记录用户选择的目标对象信息
    public class TargetInfo
    { 
        public int TargetId { get; set; } //部门或用户编号
        public string TargetName { get; set; } //部门或用户名称
    }
}

编译运行程序,分别对一个部门和一个用户设置权限,可以看到数据库已经把权限值保存下来了:

最后,在实际项目中还需要写一个API 方法,方法签名是 bool CheckAuth(string funcCode, int userId) ,

当用户在点击相关按钮时候判断是否有操作权限 , 这里就不展开了。

 

发表评论

0/200
413 点赞
0 评论
收藏
为你推荐 换一批