[golang gin framework] 45. Gin mall project - role permission association of background Rbac microservice after microservice actual combat

The relationship between roles and permissions is explained in the previous article, see [golang gin framework] 14. Gin mall project - RBAC management role and permission association, role authorization , here the authorization operation of roles to permissions is realized through microservices , There are two functions to be implemented here, one is to enter the authorization, and the other is to authorize the submission operation. The page is as follows:

 1. Realize the background authority management Rbac's role authority association microservice server function

 Here you need to add two methods in proto/rbacRole.proto: authorization operation Auth(), and authorization operation DoAuth(). For details, refer to [golang gin framework] 14.Gin Mall Project-RBAC Management_Role Authority Management Add Authorization Method , the original code is as follows:

//授权
func (con RoleController) Auth(c *gin.Context) {
	//获取id
	id, err := models.Int(c.Query("id"))
	if err != nil {
		con.Error(c, "传入数据错误", "/admin/role")
		return
	}
	role := models.Role{Id: id}
	models.DB.Find(&role)

	//获取所有权限列表
	accessList := []models.Access{}
	models.DB.Where("module_id = ?", 0).Preload("AccessItem").Find(&accessList)

	//获取当前角色拥有的权限,并把权限id放在一个map对象中
	roleAccess := []models.RoleAccess{}
	models.DB.Where("role_id = ?", id).Find(&roleAccess)
	roleAccessMap := make(map[int]int)
	for _, v := range roleAccess {
		roleAccessMap[v.AccessId] = v.AccessId
	}

	//循环遍历所有权限数据,判断当前权限的id是否在角色权限的map对象中,如果是的话给当前数据加入checked属性
	for i := 0; i < len(accessList); i++ { //循环权限列表
		if _, ok := roleAccessMap[accessList[i].Id]; ok { // 判断当前权限是否在角色权限的map对象中
			accessList[i].Checked = true
		}
		for j := 0; j < len(accessList[i].AccessItem); j++ { // 判断当前权限的子栏位是否在角色权限的map中
			if _, ok := roleAccessMap[accessList[i].AccessItem[j].Id]; ok { // 判断当前权限是否在角色权限的map对象中
				accessList[i].AccessItem[j].Checked = true
			}
		}
	}
	c.HTML(http.StatusOK, "admin/role/auth.html", gin.H{
		"roleId":     id,
		"accessList": accessList,
	})
}

//授权提交
func (con RoleController) DoAuth(c *gin.Context) {
	//获取提交的表单数据
	roleId, err := models.Int(c.PostForm("role_id"))
	if err != nil {
		con.Error(c, "传入数据错误", "/admin/role")
		return
	}
	//获取表单提交的权限id切片
	accessIds := c.PostFormArray("access_node[]")
	//先删除当前角色对应的权限
	roleAccess := models.RoleAccess{}
	models.DB.Where("role_id = ?", roleId).Delete(&roleAccess)

	//循环遍历accessIds,增加当前角色对应的权限
	for _, v := range accessIds {
		roleAccess.RoleId = roleId
		accessId, _ := models.Int(v)
		roleAccess.AccessId = accessId
		models.DB.Create(&roleAccess)
	}

	con.Success(c, "角色授权成功", "/admin/role")
}

 1. Add Auth() and DoAuth() method related codes under proto/rbacRole.proto

Referring to the above method, add Auth() and DoAuth() related method codes to the service RbacRole in the proto of the role microservice , the code is as follows:

//角色管理
service RbacRole {
    //获取角色rpc方法: 请求参数RoleGetRequest, 响应参数RoleGetResponse
	rpc RoleGet(RoleGetRequest) returns (RoleGetResponse) {}
	//增加角色rpc方法: 请求参数RoleAddRequest, 响应参数RoleAddResponse
	rpc RoleAdd(RoleAddRequest) returns (RoleAddResponse) {}
	//编辑角色rpc方法: 请求参数RoleEditRequest, 响应参数RoleEditResponse
	rpc RoleEdit(RoleEditRequest) returns (RoleEditResponse) {}
	//删除角色rpc方法: 请求参数RoleDeleteRequest, 响应参数RoleDeleteResponse
	rpc RoleDelete(RoleDeleteRequest) returns (RoleDeleteResponse) {}

    //授权
	rpc RoleAuth(RoleAuthRequest) returns (RoleAuthResponse) {}
	//授权提交
    rpc RoleDoAuth(RoleDoAuthRequest) returns (RoleDoAuthResponse) {}
}

Here you need to implement the role authorization request method RoleAuthRequest() , and the role authorization request response method RoleAuthResponse( ). Through the above Auth() method, it can be determined that a role id roleId needs to be passed in the RoleAuthRequest() request, and the permission slice is returned in the response method , which needs to be constructed A message AccessModel, the code is as follows:

//权限相关模型:参考models/access.go
message AccessModel{
	int64 id=1;
	string moduleName =2;
	string actionName=3;
	int64 type=4;
	string url=5;
	int64 moduleId=6;
	int64 sort =7;
	string description=8;
	int64 status=9;
 	int64 addTime=10;
	bool checked=11;
	repeated AccessModel accessItem=12;
}

//角色授权参数
message RoleAuthRequest{
	int64 roleId=1;
}
//角色授权响应参数
message RoleAuthResponse{
	repeated AccessModel accessList=1;
}

To implement the role authorization submission request method RoleDoAuthRequest() , and the role authorization submission request response method RoleDoAuthResponse(), through the above Auth() method, it can be determined that the role id roleId and the corresponding permission id slice of the role need to be passed in the RoleDoAuthRequest request , and returned in the response method Whether the operation is completed, the code is as follows:

//角色授权提交参数
message RoleDoAuthRequest{
	int64 roleId=1;
	repeated string accessIds=2;
}

//角色授权提交响应参数
message RoleDoAuthResponse{
	bool success=1;
	string message=2;
}

 The complete code is as follows:

syntax = "proto3";

package rbac;

option go_package = "./proto/rbacRole";

//角色管理
service RbacRole {
    //获取角色rpc方法: 请求参数RoleGetRequest, 响应参数RoleGetResponse
	rpc RoleGet(RoleGetRequest) returns (RoleGetResponse) {}
	//增加角色rpc方法: 请求参数RoleAddRequest, 响应参数RoleAddResponse
	rpc RoleAdd(RoleAddRequest) returns (RoleAddResponse) {}
	//编辑角色rpc方法: 请求参数RoleEditRequest, 响应参数RoleEditResponse
	rpc RoleEdit(RoleEditRequest) returns (RoleEditResponse) {}
	//删除角色rpc方法: 请求参数RoleDeleteRequest, 响应参数RoleDeleteResponse
	rpc RoleDelete(RoleDeleteRequest) returns (RoleDeleteResponse) {}

    //授权
	rpc RoleAuth(RoleAuthRequest) returns (RoleAuthResponse) {}
	//授权提交
    rpc RoleDoAuth(RoleDoAuthRequest) returns (RoleDoAuthResponse) {}
}

//角色相关model
message RoleModel{
	int64 id=1;
	string title=2;
	string description=3;
	int64 status=4;
	int64 addTime =5;
}

//权限相关模型:参考models/access.go
message AccessModel{
	int64 id=1;
	string moduleName =2;
	string actionName=3;
	int64 type=4;
	string url=5;
	int64 moduleId=6;
	int64 sort =7;
	string description=8;
	int64 status=9;
 	int64 addTime=10;
	bool checked=11;
	repeated AccessModel accessItem=12;
}

//获取角色请求参数
message RoleGetRequest{
    //角色id
	int64 id =1;
}

//获取角色响应参数
message RoleGetResponse{
    //角色model切片
	repeated RoleModel roleList=1;
}

//增加角色请求参数
message RoleAddRequest{
    //角色名称
	string title=1;
	//说明
	string description=2;
	//状态
	int64 status=3;
	//增加时间
	int64 addTime =4;
}

//增加角色响应参数
message RoleAddResponse{
    //是否增加成功
	bool success=1;
	//返回状态说明
	string message=2;
}

//编辑角色请求参数
message RoleEditRequest{
    //角色id
	int64 id=1;
	//角色名称
	string title=2;
	//说明
	string description=3;
	//状态
	int64 status=4;
	//增加时间
	int64 addTime =5;
}

//编辑角色响应参数
message RoleEditResponse{	
	//是否编辑成功
    bool success=1;
    //返回状态说明
    string message=2;
}

//删除角色请求参数
message RoleDeleteRequest{
	//角色id
	int64 id=1;
}

//删除角色响应参数
message RoleDeleteResponse{	
	//是否删除成功
    bool success=1;
    //返回状态说明
    string message=2;
}

//角色授权参数
message RoleAuthRequest{
	int64 roleId=1;
}
//角色授权响应参数
message RoleAuthResponse{
	repeated AccessModel accessList=1;
}

//角色授权提交参数
message RoleDoAuthRequest{
	int64 roleId=1;
	repeated string accessIds=2;
}

//角色授权提交响应参数
message RoleDoAuthResponse{
	bool success=1;
	string message=2;
}

2. Compile rbacRole.proto

Because rbacRole.proto has been modified, you need to use the command protoc --proto_path=. --micro_out=. --go_out=:. .go, pb.micro.go files

3. In the handler/rbacRole.go file, implement the newly added Auth() and DoAuth() methods

Before implementation, you need to introduce the role-permission association model  under models : RoleAcces.go model:

package models

//角色-权限 关联表

type RoleAccess struct {
	AccessId int
	RoleId   int
}

func (RoleAccess) TableName() string {
	return "role_access"
}

Then implement the Auth() and DoAuth() methods, refer to [golang gin framework] 14.  Auth() and DoAuth methods in the Gin mall project-RBAC management_role permission association, and extract the code from it , in handler/rbacRole The corresponding logic in the implementation method in .go, the code is as follows:

//授权
func (e *RbacRole) RoleAuth(ctx context.Context, req *pb.RoleAuthRequest, res *pb.RoleAuthResponse) error {
	//1、获取角色id  req.RoleId
	//获取所有权限列表
	accessList := []models.Access{}
	models.DB.Where("module_id = ?", 0).Preload("AccessItem").Find(&accessList)

	//获取当前角色拥有的权限,并把权限id放在一个map对象中
	roleAccess := []models.RoleAccess{}
	models.DB.Where("role_id = ?",  req.RoleId).Find(&roleAccess)
	roleAccessMap := make(map[int]int)
	for _, v := range roleAccess {
		roleAccessMap[v.AccessId] = v.AccessId
	}

	//循环遍历所有权限数据,判断当前权限的id是否在角色权限的map对象中,如果是的话给当前数据加入checked属性
	for i := 0; i < len(accessList); i++ { //循环权限列表
		if _, ok := roleAccessMap[int(accessList[i].Id)]; ok { // 判断当前权限是否在角色权限的map对象中, 需要进行类型转换
			accessList[i].Checked = true
		}
		for j := 0; j < len(accessList[i].AccessItem); j++ { // 判断当前权限的子栏位是否在角色权限的map中
			if _, ok := roleAccessMap[int(accessList[i].AccessItem[j].Id)]; ok { // 判断当前权限是否在角色权限的map对象中
				accessList[i].AccessItem[j].Checked = true
			}
		}
	}
	//处理数据:进行类型转换匹配操作
	var tempList []*pb.AccessModel
	for _, v := range accessList {
		var tempItemList []*pb.AccessModel
		for _, k := range v.AccessItem {
			tempItemList = append(tempItemList, &pb.AccessModel{
				Id:          int64(k.Id),
				ModuleName:  k.ModuleName,
				ActionName:  k.ActionName,
				Type:        int64(k.Type),
				Url:         k.Url,
				ModuleId:    int64(k.ModuleId),
				Sort:        int64(k.Sort),
				Description: k.Description,
				Status:      int64(k.Status),
				Checked:     k.Checked,
				AddTime:     int64(k.AddTime),
			})
		}
		tempList = append(tempList, &pb.AccessModel{
			Id:          int64(v.Id),
			ModuleName:  v.ModuleName,
			ActionName:  v.ActionName,
			Type:        int64(v.Type),
			Url:         v.Url,
			ModuleId:    int64(v.ModuleId),
			Sort:        int64(v.Sort),
			Description: v.Description,
			Status:      int64(v.Status),
			AddTime:     int64(v.AddTime),
			Checked:     v.Checked,
			AccessItem:  tempItemList,
		})
	}

	res.AccessList = tempList

	return nil
}

//执行授权
func (e *RbacRole) RoleDoAuth(ctx context.Context, req *pb.RoleDoAuthRequest, res *pb.RoleDoAuthResponse) error {
	//先删除当前角色对应的权限
	roleAccess := models.RoleAccess{}
	models.DB.Where("role_id = ?", req.RoleId).Delete(&roleAccess)

	//循环遍历accessIds,增加当前角色对应的权限
	for _, v := range req.AccessIds {
		roleAccess.RoleId = int(req.RoleId)
		accessId, _ :=strconv.Atoi(v)
		roleAccess.AccessId = accessId
		models.DB.Create(&roleAccess)
	}

	res.Success = true
	res.Message = "授权成功"
	return nil
}

4. Realize the background authority management Rbac's role authority association microservice client call function

Because the rbacRole.proto file was modified and recompiled, it is necessary to copy the rbacRole.go and rbacRole folders under the server/rbac/proto folder to the proto folder in the client project

Then implement Auth() in controllers/admin/roleController.go , and DoAuth() calls the role-permission association microservice method . You need to delete the old code in Auth() and DoAuth() first, and then add a new role-permission association For the microservice method, see the code at the beginning of the article for the old method, and the new code is as follows:


//授权
func (con RoleController) Auth(c *gin.Context) {
	//获取id
	id, err := models.Int(c.Query("id"))
	if err != nil {
		con.Error(c, "传入数据错误", "/admin/role")
		return
	}
	role := models.Role{Id: id}
	models.DB.Find(&role)

	//调用微服务获取角色授权相关数据
	rbacClient := pbRbac.NewRbacRoleService("rbac", models.RbacClient)
	res, _ := rbacClient.RoleAuth(context.Background(), &pbRbac.RoleAuthRequest{
		RoleId: int64(id),
	})

	c.HTML(http.StatusOK, "admin/role/auth.html", gin.H{
		"roleId":     id,
		"accessList": res.AccessList,
	})
}

//授权提交
func (con RoleController) DoAuth(c *gin.Context) {
	//获取提交的表单数据
	roleId, err := models.Int(c.PostForm("role_id"))
	if err != nil {
		con.Error(c, "传入数据错误", "/admin/role")
		return
	}
	//获取表单提交的权限id切片
	accessIds := c.PostFormArray("access_node[]")
	//调用微服务执行授权
	rbacClient := pbRbac.NewRbacRoleService("rbac", models.RbacClient)
	res, _ := rbacClient.RoleDoAuth(context.Background(), &pbRbac.RoleDoAuthRequest{
		RoleId:    int64(roleId),
		AccessIds: accessIds,
	})

	if res.Success {
		con.Success(c, "角色授权成功", "/admin/role")
		return
	}
	con.Error(c, "授权失败", "/admin/role/auth?id="+models.String(roleId))
}

The complete roleController.go code is as follows:

package admin

import (
	"context"
	"github.com/gin-gonic/gin"
	"goshop/models"
	pbRbac "goshop/proto/rbacRole"
	"net/http"
	"strings"
)

type RoleController struct {
	BaseController
}

//角色列表
func (con RoleController) Index(c *gin.Context) {
	//调用Rbac微服务
	rbacClient := pbRbac.NewRbacRoleService("rbac", models.RbacClient)
	res, _ := rbacClient.RoleGet(context.Background(), &pbRbac.RoleGetRequest{})

	c.HTML(http.StatusOK, "admin/role/index.html", gin.H{
		"roleList": res.RoleList,
	})
}

//新增角色
func (con RoleController) Add(c *gin.Context) {
	c.HTML(http.StatusOK, "admin/role/add.html", gin.H{})
}

//新增角色:提交
func (con RoleController) DoAdd(c *gin.Context) {
	//获取表单的提交数据
	//strings.Trim(str, cutset), 去除字符串两边的cutset字符
	title := strings.Trim(c.PostForm("title"), " ") // 去除字符串两边的空格
	description := strings.Trim(c.PostForm("description"), " ")

	//判断角色名称是否为空
	if title == "" {
		con.Error(c, "角色名称不能为空", "/admin/role/add")
		return
	}

	//调用微服务,实现角色的添加
	rbacClient := pbRbac.NewRbacRoleService("rbac", models.RbacClient)
	res, _ := rbacClient.RoleAdd(context.Background(), &pbRbac.RoleAddRequest{
		Title:       title,
		Description: description,
		AddTime:     models.GetUnix(),
		Status:      1,
	})
	if !res.Success {
		con.Error(c, "增加角色失败 请重试", "/admin/role/add")
	} else {
		con.Success(c, "增加角色成功", "/admin/role")
	}
}

//编辑角色
func (con RoleController) Edit(c *gin.Context) {
	//获取角色id
	id, err := models.Int(c.Query("id"))
	if err != nil {
		con.Error(c, "传入数据错误", "/admin/role")
	} else {
		//调用微服务,获取角色信息
		rbacClient := pbRbac.NewRbacRoleService("rbac", models.RbacClient)
		res, _ := rbacClient.RoleGet(context.Background(), &pbRbac.RoleGetRequest{
			Id: int64(id),
		})
		c.HTML(http.StatusOK, "admin/role/edit.html", gin.H{
			"role": res.RoleList[0],
		})
	}
}

//编辑角色:提交
func (con RoleController) DoEdit(c *gin.Context) {
	//获取提交的表单数据
	id, err := models.Int(c.PostForm("id"))
	if err != nil {
		con.Error(c, "传入数据错误", "/admin/role")
		return
	}
	//获取表单的提交数据
	//strings.Trim(str, cutset), 去除字符串两边的cutset字符
	title := strings.Trim(c.PostForm("title"), " ") // 去除字符串两边的空格
	description := strings.Trim(c.PostForm("description"), " ")
	//判断角色名称是否为空
	if title == "" {
		con.Error(c, "角色名称不能为空", "/admin/role/add")
		return
	}
	//调用微服务修改
	rbacClient := pbRbac.NewRbacRoleService("rbac", models.RbacClient)
	res, _ := rbacClient.RoleEdit(context.Background(), &pbRbac.RoleEditRequest{
		Id:          int64(id),
		Title:       title,
		Description: description,
	})
	if !res.Success {
		con.Error(c, "修改数据失败", "/admin/role/edit?id="+models.String(id))
		return
	}
	con.Success(c, "修改数据成功", "/admin/role")
}

//删除角色
func (con RoleController) Delete(c *gin.Context) {
	//获取提交的表单数据
	id, err := models.Int(c.Query("id"))
	if err != nil {
		con.Error(c, "传入数据错误", "/admin/role")
		return
	}

	rbacClient := pbRbac.NewRbacRoleService("rbac", models.RbacClient)
	res, _ := rbacClient.RoleDelete(context.Background(), &pbRbac.RoleDeleteRequest{
		Id: int64(id),
	})
	if res.Success {
		con.Success(c, "删除数据成功", "/admin/role")
		return
	}
	con.Error(c, "删除数据失败", "/admin/role")
}

//授权
func (con RoleController) Auth(c *gin.Context) {
	//获取id
	id, err := models.Int(c.Query("id"))
	if err != nil {
		con.Error(c, "传入数据错误", "/admin/role")
		return
	}
	role := models.Role{Id: id}
	models.DB.Find(&role)

	//调用微服务获取角色授权相关数据
	rbacClient := pbRbac.NewRbacRoleService("rbac", models.RbacClient)
	res, _ := rbacClient.RoleAuth(context.Background(), &pbRbac.RoleAuthRequest{
		RoleId: int64(id),
	})

	c.HTML(http.StatusOK, "admin/role/auth.html", gin.H{
		"roleId":     id,
		"accessList": res.AccessList,
	})
}

//授权提交
func (con RoleController) DoAuth(c *gin.Context) {
	//获取提交的表单数据
	roleId, err := models.Int(c.PostForm("role_id"))
	if err != nil {
		con.Error(c, "传入数据错误", "/admin/role")
		return
	}
	//获取表单提交的权限id切片
	accessIds := c.PostFormArray("access_node[]")
	//调用微服务执行授权
	rbacClient := pbRbac.NewRbacRoleService("rbac", models.RbacClient)
	res, _ := rbacClient.RoleDoAuth(context.Background(), &pbRbac.RoleDoAuthRequest{
		RoleId:    int64(roleId),
		AccessIds: accessIds,
	})

	if res.Success {
		con.Success(c, "角色授权成功", "/admin/role")
		return
	}
	con.Error(c, "授权失败", "/admin/role/auth?id="+models.String(roleId))
}

 2. Verification authority management Rbac's role authority association micro-service function

Refer to [golang gin framework] 43. Gin mall project - the addition, deletion, modification and query of the administrator of the background Rbac microservice after the actual combat of the microservice, and the association between the administrator and the role

1. Start the server first

See [golang gin framework] 40. Gin mall project - Captcha verification code microservice code in microservice combat , here also start the verification code captcha microservice server code and authority management Rbac microservice ( user login microservice server, role Manage the microservice server, the administrator manages the microservice server) server

 

2. Start the client

Run in the project root directory: go run main.go to start the project

3. Verify whether the microservice operation associated with the role and authority of the authority management Rbac is successful 

Visit the background login page, enter the user name, password, verification code, log in to the background, enter the role management list page, and authorize the role

 

 

Well, the client operation of the role authority association microservice function of authority management Rbac is completed. The following section explains: Modify the authority verification of the mall client calling microservices and the Rbac microservice database extraction function

[Previous section] [golang gin framework] 44. Gin mall project - adding, deleting, modifying and checking microservices for permissions of background Rbac microservices after actual combat of microservices

Guess you like

Origin blog.csdn.net/zhoupenghui168/article/details/132115181