Skip to content

角色授权

角色管理显示授权

1、授权事件

javascript

table.on("tool(role-table)", function (obj) {
    if (obj.event === "role-tool-edit") {
        // ...
    } else if (obj.event === "role-tool-del") {
        // ...
    } else if (obj.event === "role-tool-detail") {

        // 打开授权表单
        layer.open({
            type: 1,
            title: "授权",
            shade: false,
            area: ["500px", "500px"],
            content: $("#role-rights-form"),
        });
    }
});

2、授权表单

tree 组件占位

html
<!--授权表单-->
<form
        class="layui-form"
        action=""
        style="display: none"
        id="role-rights-form"
        lay-filter="role-rights-form"
>
    <div class="row" style="margin: 10px 5px">
        <ul id="role_rights" class="dtree" data-id="0"></ul>
    </div>
    <div class="bottom">
        <div class="button-container">
            <button
                    type="submit"
                    class="layui-btn layui-btn-primary layui-btn-sm"
                    lay-submit
                    lay-filter="role-rights-save"
            >
                <i class="layui-icon layui-icon-ok"></i>
                提交
            </button>
            <button type="reset" class="layui-btn layui-btn-sm">
                <i class="layui-icon layui-icon-refresh"></i>
                重置
            </button>
        </div>
    </div>
</form>

3、加载授权数据

javascript
let role_id = -1;

table.on("tool(role-table)", function (obj) {
    if (obj.event === "role-tool-edit") {
        // ...
    } else if (obj.event === "role-tool-del") {
        // ...
    } else if (obj.event === "role-tool-detail") {
        //  角色授权 role-tool-detail
        role_id = obj.data["id"];
        $.ajax({
            url: "/api/v1/rights/tree",
            type: "get",
            success: function (ret) {
                // 渲染组件数据
                tree.render({
                    elem: "#role_rights",
                    id: "role_rights",
                    data: ret.data,
                    showCheckbox: true,
                });

                // 获取需要授权角色的权限数据
                $.ajax({
                    url: `/api/v1/role/role_rights/${role_id}`,
                    type: "get",
                    success: function (ret) {
                        tree.setChecked("role_rights", ret.data);
                    },
                });
            },
        });

        // 打开授权表单
        layer.open({
            type: 1,
            title: "授权",
            shade: false,
            area: ["500px", "500px"],
            content: $("#role-rights-form"),
        });
    }
});

4、后端返回 tree 权限数据

python
@rights_api.get("/rights/tree")
@jwt_required()
def rights_list():
    # 1. 获取所有的权限
    rights_all = db.session.execute(db.select(RightsORM)).scalars()
    rights_list = [
        {"id": r.id, "pid": r.pid, "title": r.name, "sort": r.sort}
        for r in rights_all
    ]
    # 2. 获取已有权限 id 集合
    # 3. 列表转属性组件
    rights_list.sort(key=lambda item: (item["pid"], item["id"]), reverse=True)
    tree_dict = {}
    for rights_dict in rights_list:  # 遍历子节点
        # 2. 如果当前阶段已经存在于树状表格字典,则是父节点
        if rights_dict["id"] in tree_dict.keys():
            # 将之前的节点添加到父节点之下
            rights_dict["children"] = deepcopy(tree_dict[rights_dict["id"]])
            rights_dict["children"].sort(key=lambda item: item["sort"])
            del tree_dict[rights_dict["id"]]

        # 1. 如果父节点未出现在树状字典里面,就新增子节点列表,否则就追加
        if rights_dict["pid"] not in tree_dict.keys():
            tree_dict[rights_dict["pid"]] = [rights_dict]
        else:
            tree_dict[rights_dict["pid"]].append(rights_dict)

    return {"code": 0, "data": tree_dict.get(0)}

5、后端返回角色权限数据

python
@role_api.get("/role/role_rights/<int:rid>")
def role_rights(rid):
    role: RoleORM = db.session.execute(
        db.select(RoleORM).where(RoleORM.id == rid)
    ).scalar()
    own_rights_list = [r.id for r in role.rights_list]

    return {
        "code": 0,
        "msg": "返回角色权限数据成功",
        "data": own_rights_list,
    }

6、前端提交修改

javascript
function get_id(list_tree_data) {
    if (Array.isArray(list_tree_data)) {
        let ret = [];
        $.each(list_tree_data, function (index, item) {
            if (item?.children) {
                ret.push(...get_id(item.children));
            }
            ret.push(...get_id(item));
        });
        return ret;
    } else {
        return [list_tree_data.id];
    }
}
javascript
form.on("submit(role-rights-save)", function (data) {
    let param = tree.getChecked("role_rights"); // 获取选中节点的数据
    let rights_ids = get_id(param).join();
    $.ajax({
        url: `/api/v1/role/role_rights/${role_id}`,
        data: JSON.stringify({rights_ids: rights_ids}),
        dataType: "json",
        contentType: "application/json",
        type: "put",
        success: function (result) {
            if (result.code === 0) {
                layer.msg(result.msg, {icon: 1, time: 1000}, function () {
                    layer.closeAll();
                });
            } else {
                layer.msg(result.msg, {icon: 2, time: 1000});
            }
        },
    });
    return false;
});

7、后端完成修改

python
@role_api.put("/role/role_rights/<int:rid>")
def change_role_rights(rid):
    rights_ids = request.json.get("rights_ids", "")

    rights_list = rights_ids.split(",")
    role: RoleORM = db.session.execute(
        db.select(RoleORM).where(RoleORM.id == rid)
    ).scalar()
    rights_obj_list = db.session.execute(
        db.select(RightsORM).where(RightsORM.id.in_(rights_list))
    ).all()
    role.rights_list = [r[0] for r in rights_obj_list]
    role.save()
    return {"code": 0, "msg": "授权成功"}