.net5 core Razor項目實戰系列之十:權限設置功能的實現(EFCore的批量刪除與批量新增)


權限設置可以針對部門和用戶這兩個層級,如果設置了部門的權限,

該部門下的所有用戶將自動獲得部門的權限,如果部門和用戶都設置了權限則只取用戶部分,忽略部門的權限。

操作流程是這樣的:進入權限設置頁---> 頁面左邊顯示所有部門--->點部門超鏈接的時候顯示該部門下的員工;

頁面右邊顯示權限點,可以針對部門和員工設置權限,點保存按鈕的時候存儲到數據庫,具體如下:

場景一、用戶點【權限設置】時看到的效果如下:

此時提示用戶去選擇部門或用戶,而且保存按鈕是不可見的。

場景二、點左邊的部門的時候,顯示部門下的用戶,同時右邊顯示部門名稱和保存按鈕,如下:

場景三、點左邊部門下的用戶的時候,右邊顯示用戶名稱,同時顯示保存按鈕,如下:

代碼如下:

在 _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) ,

當用戶在點擊相關按鈕時候判斷是否有操作權限 , 這里就不展開了。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM