0


go实战全家桶优化goweb实现权限控制

GO全家桶

UML

开源

water/goweb

控制端

type IrpcCheckAllowed interface {
// 测试开关、是否检查权限,方便测试可以关闭
IfCheckRes() bool
IfCheckSession() bool

// 根据token获取useid的实现
 RpcUserIdGetBySession(ctx *gin.Context, token string) (*webdto.WebUserId, error)

// RPC 设置ctx上下文的CooUserID信息的实现
 RpcSetUserId(c *gin.Context) //set *webdto.WebUserId

// RPC 获取ctx上下文的CooUserID信息的 实现
 RpcGetUserId(ctx *gin.Context) *webdto.WebUserId

//rpc 检查权限的实现
 RpcCheckAllowed(ctx context.Context, req *webdto.WebCheckRequest) (*webdto.WebCheckResult, error)

}

应用端

// 应用服务上下文获取信息
type IwebCheckAllowed interface {
    SetUserId(c *gin.Context)

    GetUserId(ctx *gin.Context) *webdto.WebUserId

    CheckToken(c *gin.Context) (int, error)

    GetSessionToken(c *gin.Context) (int, *webdto.WebUserId, error)

    WebCheckAllowed(c *gin.Context)
}

内部WEBSERVER无权限控制

/*
@Title    文件名称: main.go
@Description  描述: 有芯通用索引微服务
@Contact.user raymond
@Author  作者: [email protected]  时间(2024-02-18 22:38:21)
@Update  作者: [email protected]  时间(2024-02-18 22:38:21)
*/
func InjectMiddleware() {

    // 注册业务权限rpc接口,FindBeanRpcNocheckRight这个不鉴权,鉴权的rpc在general-common业务服务使用
    webcheck.FindBeanWebCheckRight().RegisterIrpc(webcustom.FindBeanRpcNocheckRight())
    // 注入业务中间件(webmiddleware.DemoWebMiddleWare())样例,只是打日志
    //webcheck.FindBeanWebCheckRight().RegisterMiddlewares(handlerfunc.WebExampleMiddleware())

}

// https://www.jianshu.com/p/982c4fabb11d swagg参数

func StartWeb() {
    defer func() {
       if r := recover(); r != nil {
          goutils.Error("[main] Recovered  Error in:", r)
          fmt.Println("[main] Recovered Error in:", r)
          buf := make([]byte, 4096)
          n := runtime.Stack(buf, false)
          fmt.Println(string(buf[:n]))
          goutils.Error(string(buf[:n]))

       }
    }()
    InjectMiddleware()

    goutils.Info("now starting serverNats....")
    goperfstat.FindBeanGoperfStat().SetEnable2Out(false)
    goperfstat.FindBeanGoperfStat().StartStats()

    var config = ichubconfig.FindBeanIchubConfig()
    serverDto := config.ReadIchubWebServer()
    goutils.Info("serverDto=", serverDto)
    var server = webserver.New(serverDto)

    var swagger = config.ReadWebSwagger()
    //注册服务
    goutils.Info("swagger is http://" + swagger.Host + "/swagger/index.html#/")
    fmt.Println("serverName ", serverDto.ServerName)

    server.StartWebSwagger(router.Swagger, router.Register)

}

有权限控制

package webstart

import (
    "fmt"
    "gitee.com/leijmdas/gobase/goconfig/common/golog"
    "gitee.com/leijmdas/gobase/goconfig/common/ichubconfig"
    "gitee.com/leijmdas/goplatform/api/goauth/authproxy"
    "gitee.com/leijmdas/goplatform/web/server/router"
    "gitee.com/leijmdas/goweb/common/webright/webcheck"
    "gitee.com/leijmdas/goweb/common/webright/webmiddleware/handlerfunc"
    "gitee.com/leijmdas/goweb/common/webserver"
    "gitee.com/leijmdas/goweb/domain/service"
    "github.com/sirupsen/logrus"
    "runtime"
)

/*
    @Title    文件名称: websample.go
    @Description  描述: 通用引擎微服务
    @Contact.user raymond
    @Author  作者: [email protected]  时间(2024-02-18 22:38:21)
    @Update  作者: [email protected]  时间(2024-02-18 22:38:21)
*/

// https://www.jianshu.com/p/982c4fabb11d swagg参数
func InjectMiddleware() {

    // 注册业务权限rpc接口,FindBeanRpcNocheckRight这个不鉴权,鉴权的rpc在general-common业务服务使用
    //webcheck.FindBeanWebCheckRight().RegisterIrpc(webcustom.FindBeanRpcCheckRight())
    webcheck.FindBeanWebCheckRight().RegisterIrpc(authproxy.FindBeanAuthProxy())
    // 注入业务中间件(webmiddleware.DemoWebMiddleWare())样例,只是打日志
    webcheck.FindBeanWebCheckRight().RegisterMiddlewares(handlerfunc.WebExampleMiddleware())

}
func StartWeb() {
    defer func() {
       if r := recover(); r != nil {
          golog.Error("[main] Recovered  Error in:", r)
          fmt.Println("[main] Recovered Error in:", r)
          buf := make([]byte, 4096)
          n := runtime.Stack(buf, false)
          //fmt.Println(string(buf[:n]))
          golog.Error(string(buf[:n]))

       }
    }()
    InjectMiddleware()
    service.Init()

    var config = ichubconfig.FindBeanIchubConfig()
    serverDto := config.ReadWebServer()

    golog.Info("serverDto=", serverDto)
    var server = webserver.New(serverDto)
    logrus.Info("http://localhost:88/swagger/index.html#/")
    //注册服务

    server.StartWebSwagger(router.Swagger, router.Register)

}

// go get -u -v github.com/swaggo/gin-swagger//go get -u -v github.com/swaggo/files
// go get -u -v github.com/alecthomas/template

控制端实现

package authproxy

import (
    "context"
    "errors"
    "gitee.com/leijmdas/gobase/goconfig/common/base/goutils"
    "gitee.com/leijmdas/gobase/goconfig/common/golog"
    "gitee.com/leijmdas/goplatform/api/goauth"
    "gitee.com/leijmdas/goweb/common/webright/webcheck/webcustom"
    "gitee.com/leijmdas/goweb/common/webright/webconsts"
    "gitee.com/leijmdas/goweb/common/webright/webdto"
    "github.com/gin-gonic/gin"
)

type AuthProxy struct {
    *webcustom.RpcCheckRight
}

func NewAuthProxy() *AuthProxy {
    return &AuthProxy{
       RpcCheckRight: webcustom.NewRpcCheckRight(),
    }
}

func (r AuthProxy) RpcUserIdGetBySession(c *gin.Context, token string) (*webdto.WebUserId, error) {
    var apiUserResult = goauth.FindBeanauthApiService().Auth(token)
    if !apiUserResult.IsSuccess() {
       return nil, errors.New(apiUserResult.Msg)
    }

    var webuser = webdto.NewWebUserId()
    webuser.ApiUserResult = apiUserResult.Data
    return webuser, nil
}

func (r AuthProxy) RpcSetUserId(c *gin.Context) {

    token := c.GetHeader(webconsts.AccessToken)
    if token == "" {
       goutils.Error("toke is empty!")
       return
    }
    var webuser, err = r.RpcUserIdGetBySession(c, token)
    if err != nil {
       golog.Error(err)
       return
    }
    webdto.SetUserId(c, webuser)
}

func (r AuthProxy) RpcGetUserId(c *gin.Context) *webdto.WebUserId {

    return webdto.GetUserId(c)
}

func (r AuthProxy) RpcCheckAllowed(c context.Context, req *webdto.WebCheckRequest) (*webdto.WebCheckResult, error) {
    token := c.(*gin.Context).GetHeader(webconsts.AccessToken)
    if token == "" {
       goutils.Error("toke is empty!")
       return nil, errors.New("token is empty")
    }
    var webuser, err = r.RpcUserIdGetBySession(c.(*gin.Context), token)
    if err != nil {
       golog.Error(err)
       return nil, err
    }

    // 还要增加接口权限 判断url是否有权限
    var result = webdto.NewWebCheckResult()
    result.Allowed = true
    result.ApiUserResult = webuser.ApiUserResult

    return result, nil
}

func (r AuthProxy) IfCheckRes() bool {
    return true
}
func (self *AuthProxy) IfCheckSession() bool {
    return true
}

注入业务中间件

// 注入业务中间件(webmiddleware.DemoWebMiddleWare())样例,只是打日志
webcheck.FindBeanWebCheckRight().RegisterMiddlewares(handlerfunc.WebExampleMiddleware())

func (this *WebRouters) InstallMiddleWare(router *gin.Engine) *gin.Engine {
    router.Use(webmiddlewares.CheckSessionToken(), webmiddlewares.CheckAllowed())
    router.Use(webmiddlewares.WebMiddleware()...)
    //router.Use(gin.)
    router.Use(middleware.RequestID(), middleware.Context(), gin.Recovery(), middleware.Cors())
    //router.Use(gin.Logger(),gindump.Dump())
    router.Use(gzip.Gzip(gzip.DefaultCompression))
    this.AddRouter(router)
    return router
}

本文转载自: https://blog.csdn.net/leijmdas/article/details/142329911
版权归原作者 leijmdas 所有, 如有侵权,请联系我们删除。

“go实战全家桶优化goweb实现权限控制”的评论:

还没有评论