security

package
v0.2.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 25, 2025 License: MIT Imports: 10 Imported by: 0

README

鉴权模块

模块描述

此模块为鉴权功能模块,类似spring-security,但由于当前版本(1.17.2)golang的语法特点,实现注解式鉴权需要的操作,比直接控制router的方式,更复杂、码量更多,因此,仍以router管理的方式实现,具体方法,可阅读security/router.go。

这里的权限,参照了罗杨博士的casbin的设计逻辑,将权限分为主体、客体、操作三个元素,在请求时,将请求的权限三要素与目标的权限三要素进行匹配判断(match)。

这里的角色,使用父子层级的关系,与权限为多对多的关系,父角色除直属自身的权限外,还递归包含子角色的全部权限。

此模块自带系统超管角色,超管用户ID为1,但暂无用户表,用户表由使用者自行拓展。

使用此模块注册的路由,会自动录入权限入库,并根据路由sub分组,创建相应的微模块角色,这些角色默认会以超管为父角色,你可以根据需要,开发角色管理,将这些角色划归其他角色所有。

security源码结构

  1. security.go

    模块配置入口。

  2. casbin.go

    权限模型文件,包含部分权限的数据库增删改查功能。

  3. role.go

    角色模型文件。

  4. handler.go

    鉴权拦截的函数。

  5. router.go

    鉴权路由相关的代码。封装了Router结构体,并赋予了Regist()函数,该函数主要完成gin框架路由注册、添加jwt和security的路由拦截函数、api权限登记入库三个功能。

  6. metadata.go

    security模块元数据导入。鉴于模块启用早于api的路由登记,所以,需等到web应用启动完成时,才可以进行元数据导入的操作,因此,在security.go中,以异步的方式进行轮询等待。

    go func() {
      for !IsServerRunning {
        time.Sleep(time.Duration(10) * time.Microsecond)
      }
      importMetaData()
    }()
    

Documentation

Index

Constants

View Source
const (
	MethodGet     httpmethod = "GET"
	MethodHead    httpmethod = "HEAD"
	MethodPost    httpmethod = "POST"
	MethodPut     httpmethod = "PUT"
	MethodPatch   httpmethod = "PATCH" // RFC 5789
	MethodDelete  httpmethod = "DELETE"
	MethodOptions httpmethod = "OPTIONS"
)

Variables

View Source
var (
	ErrNotActive             = errors.New("未启用security模块")
	ErrNotActiveInvalidParam = errors.New("参数错误,未启用security模块")
	ErrRegistFailed          = errors.New("无法注册:错误的uri,需要更多层级的路由")

	ErrPolicyNotFound = errors.New("找不到权限信息")
	ErrNoApiPolicy    = errors.New("接口权限不足")
	ErrNoCustomerInfo = errors.New("无法获取用户信息")
)
View Source
var SECURITY_HANDLER gin.HandlerFunc = func(ctx *gin.Context) {
	if id := jwt.GetClaims(ctx).Id; len(id) == 0 {
		log.Error(ErrNoCustomerInfo)
		restful.Errors.FromError(ErrNoCustomerInfo).Restful(ctx)
		ctx.Abort()
	} else if uid, e := strconv.ParseUint(id, 10, 64); e != nil || uid == 0 {
		log.Error(ErrNoCustomerInfo)
		restful.Errors.FromError(ErrNoCustomerInfo).Restful(ctx)
		ctx.Abort()
	} else if p, b := role.GetPolicy(apiObj(ctx.Request.Method, ctx.Request.URL.Path), role.ACT_API_ACCESS); !b {
		log.Error(ErrPolicyNotFound)
		restful.Errors.FromError(ErrPolicyNotFound).Restful(ctx)
		ctx.Abort()
	} else if urs, e := role.FindUserRoleByUid(uid); e != nil {
		log.Error(e)
		restful.Errors.FromError(e).Restful(ctx)
		ctx.Abort()
	} else if len(urs) == 0 {
		log.Error(ErrNoApiPolicy)
		restful.Errors.FromError(ErrNoApiPolicy).Restful(ctx)
		ctx.Abort()
	} else {
		for _, ur := range urs {
			if nil != ur.Role && ur.Role.Match(p) {
				ctx.Next()
				return
			}
		}

		restful.Errors.FromError(ErrNoApiPolicy).Restful(ctx)
		ctx.Abort()
	}
}

Functions

func DELETE added in v0.2.3

func DELETE(policy string, uri string, handler gin.HandlerFunc)

func GET added in v0.2.3

func GET(policy string, uri string, handler gin.HandlerFunc)
func HEAD(policy string, uri string, handler gin.HandlerFunc)

func OPTIONS added in v0.2.3

func OPTIONS(policy string, uri string, handler gin.HandlerFunc)

func PATCH added in v0.2.3

func PATCH(policy string, uri string, handler gin.HandlerFunc)

func POST added in v0.2.3

func POST(policy string, uri string, handler gin.HandlerFunc)

func PUT added in v0.2.3

func PUT(policy string, uri string, handler gin.HandlerFunc)

Types

type SecurityConfig

type SecurityConfig struct {
	Enable           bool `mapstructure:"enable" json:"enable" yaml:"enable"`                                   // 是否开启
	AllowCors        bool `mapstructure:"allow_cors" json:"allow_cors" yaml:"allow_cors"`                       // 是否允许跨域
	EnableRedisCache bool `mapstructure:"enable-redis-cache" json:"enableRedisCache" yaml:"enable-redis-cache"` // 是否开启redis缓存
}

func (SecurityConfig) Load

func (c SecurityConfig) Load()

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL