multi

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Aug 28, 2021 License: MIT Imports: 16 Imported by: 29

README

Multi

Golang Iris Web 框架认证中间件

文档

文档

简单使用

example

完整使用

Documentation

Index

Constants

View Source
const (
	GtSessionTokenPrefix        = "GST:"           // token 缓存前缀
	GtSessionBindUserPrefix     = "GSBU:"          // token 绑定用户前缀
	GtSessionUserPrefix         = "GSU:"           // 用户前缀
	GtSessionUserMaxTokenPrefix = "GTUserMaxToken" // 用户最大 token 数前缀
)
View Source
const (
	NoneAuthority    int = iota // 空授权
	AdminAuthority              // 管理员
	TenancyAuthority            // 商户
	GeneralAuthority            //普通用户
)
View Source
const (
	NoAuth int = iota
	AuthPwd
	AuthCode
	AuthThirdParty
)
View Source
const (
	LoginTypeWeb int = iota
	LoginTypeApp
	LoginTypeWx
	LoginTypeDevice
)

Variables

View Source
var (
	ErrTokenInvalid      = errors.New("token 不可用!")
	ErrEmptyToken        = errors.New("token 为空!")
	ErrOverMaxTokenCount = errors.New("已达到同时登录设备上限!")
)
View Source
var (
	RedisSessionTimeoutWeb    = 4 * time.Hour            // 4 小时
	RedisSessionTimeoutApp    = 7 * 24 * time.Hour       // 7 天
	RedisSessionTimeoutWx     = 5 * 52 * 168 * time.Hour // 1年
	RedisSessionTimeoutDevice = 5 * 52 * 168 * time.Hour // 1年
)
View Source
var (
	GtSessionUserMaxTokenDefault int64 = 10
)

Functions

func Base64Decode

func Base64Decode(src []byte) ([]byte, error)

Base64Decode decodes "src" to jwt base64 url format. We could use the base64.RawURLEncoding but the below is a bit faster.

func Base64Encode

func Base64Encode(src []byte) []byte

func FromHeader

func FromHeader(ctx *context.Context) string

FromHeader is a token extractor. It reads the token from the Authorization request header of form: Authorization: "Bearer {token}".

func FromQuery

func FromQuery(ctx *context.Context) string

FromQuery is a token extractor. It reads the token from the "token" url query parameter.

func GetAuthorityId

func GetAuthorityId(ctx *context.Context) string

GetAuthorityId 角色id

func GetAuthorityType

func GetAuthorityType(ctx *context.Context) int

GetAuthorityType 角色名

func GetCreationDate

func GetCreationDate(ctx *context.Context) int64

GetCreationDate 登录时间

func GetExpiresIn

func GetExpiresIn(ctx *context.Context) int64

GetExpiresIn 有效期

func GetTenancyId

func GetTenancyId(ctx *context.Context) uint

GetTenancyId 商户id

func GetTenancyName

func GetTenancyName(ctx *context.Context) string

GetTenancyName 商户名称

func GetToken

func GetToken() (string, error)

func GetUserId

func GetUserId(ctx *context.Context) uint

GetUserId 用户id

func GetUsername

func GetUsername(ctx *context.Context) string

GetUsername 用户名

func GetVerifiedToken

func GetVerifiedToken(ctx *context.Context) []byte

func InitDriver

func InitDriver(c *Config) error

InitDriver 认证驱动 redis 需要设置redis local 使用本地内存

func IsAdmin

func IsAdmin(ctx *context.Context) bool

func IsGeneral

func IsGeneral(ctx *context.Context) bool

func IsTenancy

func IsTenancy(ctx *context.Context) bool

Types

type Authentication

type Authentication interface {
	GenerateToken(claims *CustomClaims) (string, int64, error)  // 生成 token
	DelUserTokenCache(token string) error                       // 清除用户当前token信息
	UpdateUserTokenCacheExpire(token string) error              // 更新token 过期时间
	GetCustomClaims(token string) (*CustomClaims, error)        // 获取token用户信息
	GetTokenByClaims(claims *CustomClaims) (string, error)      // 通过用户信息获取token
	CleanUserTokenCache(authorityType int, userId string) error // 清除用户所有 token
	SetUserTokenMaxCount(tokenMaxCount int64) error             // 设置最大登录限制
	IsAdmin(token string) (bool, error)
	IsTenancy(token string) (bool, error)
	IsGeneral(token string) (bool, error)
	Close()
}

Authentication 认证

var AuthDriver Authentication

type Config

type Config struct {
	DriverType      string
	TokenMaxCount   int64
	UniversalClient redis.UniversalClient
}

type CustomClaims

type CustomClaims struct {
	ID            string `json:"id" redis:"id"`
	Username      string `json:"username" redis:"username"`
	TenancyId     uint   `json:"tenancy_id" redis:"tenancy_id"`
	TenancyName   string `json:"tenancy_name" redis:"tenancy_name"`
	AuthorityId   string `json:"authority_id" redis:"authority_id"`
	AuthorityType int    `json:"authority_type" redis:"authority_type"`
	LoginType     int    `json:"login_type" redis:"login_type"`
	AuthType      int    `json:"auth_type" redis:"auth_type"`
	CreationDate  int64  `json:"creation_data" redis:"creation_data"`
	ExpiresIn     int64  `json:"expires_in" redis:"expires_in"`
}

Custom claims structure ID 用户id Username 用户名 TenancyId 商户id TenancyName 商户名称 AuthorityId 角色id AuthorityType 角色类型 LoginType 登录类型 web,app,wechat AuthType 授权类型 密码,验证码,第三方 CreationDate 登录时间 ExpiresIn 有效期

func Get

func Get(ctx *context.Context) *CustomClaims

Get returns the claims decoded by a verifier.

type LocalAuth

type LocalAuth struct {
	Cache *cache.Cache
}

func NewLocalAuth

func NewLocalAuth() *LocalAuth

func (*LocalAuth) CleanUserTokenCache

func (la *LocalAuth) CleanUserTokenCache(authorityType int, userId string) error

CleanUserTokenCache 清空token缓存

func (*LocalAuth) Close

func (la *LocalAuth) Close()

兼容 redis

func (*LocalAuth) DelUserTokenCache

func (la *LocalAuth) DelUserTokenCache(token string) error

func (*LocalAuth) GenerateToken

func (la *LocalAuth) GenerateToken(claims *CustomClaims) (string, int64, error)

GenerateToken

func (*LocalAuth) GetCustomClaims

func (la *LocalAuth) GetCustomClaims(token string) (*CustomClaims, error)

func (*LocalAuth) GetTokenByClaims

func (la *LocalAuth) GetTokenByClaims(cla *CustomClaims) (string, error)

GetTokenByClaims 获取用户信息

func (*LocalAuth) IsAdmin

func (la *LocalAuth) IsAdmin(token string) (bool, error)

IsAdmin

func (*LocalAuth) IsGeneral

func (la *LocalAuth) IsGeneral(token string) (bool, error)

IsGeneral

func (*LocalAuth) IsTenancy

func (la *LocalAuth) IsTenancy(token string) (bool, error)

IsTenancy

func (*LocalAuth) SetUserTokenMaxCount

func (la *LocalAuth) SetUserTokenMaxCount(tokenMaxCount int64) error

SetUserTokenMaxCount 最大登录限制

func (*LocalAuth) UpdateUserTokenCacheExpire

func (la *LocalAuth) UpdateUserTokenCacheExpire(token string) error

type RedisAuth

type RedisAuth struct {
	Client redis.UniversalClient
}

RedisAuth

func NewRedisAuth

func NewRedisAuth(client redis.UniversalClient) (*RedisAuth, error)

NewRedisAuth

func (*RedisAuth) CleanUserTokenCache

func (ra *RedisAuth) CleanUserTokenCache(authorityType int, userId string) error

CleanUserTokenCache 清空token缓存

func (*RedisAuth) Close

func (ra *RedisAuth) Close()

Close

func (*RedisAuth) DelUserTokenCache

func (ra *RedisAuth) DelUserTokenCache(token string) error

DelUserTokenCache 删除token缓存

func (*RedisAuth) GenerateToken

func (ra *RedisAuth) GenerateToken(claims *CustomClaims) (string, int64, error)

GenerateToken

func (*RedisAuth) GetCustomClaims

func (ra *RedisAuth) GetCustomClaims(token string) (*CustomClaims, error)

GetCustomClaims 获取用户信息

func (*RedisAuth) GetTokenByClaims

func (ra *RedisAuth) GetTokenByClaims(cla *CustomClaims) (string, error)

GetTokenByClaims 获取用户信息

func (*RedisAuth) IsAdmin

func (ra *RedisAuth) IsAdmin(token string) (bool, error)

IsAdmin

func (*RedisAuth) IsGeneral

func (ra *RedisAuth) IsGeneral(token string) (bool, error)

IsGeneral

func (*RedisAuth) IsTenancy

func (ra *RedisAuth) IsTenancy(token string) (bool, error)

IsTenancy

func (*RedisAuth) SetUserTokenMaxCount

func (ra *RedisAuth) SetUserTokenMaxCount(tokenMaxCount int64) error

SetUserTokenMaxCount 最大登录限制

func (*RedisAuth) UpdateUserTokenCacheExpire

func (ra *RedisAuth) UpdateUserTokenCacheExpire(token string) error

UpdateUserTokenCacheExpire 更新过期时间

type TokenExtractor

type TokenExtractor func(*context.Context) string

TokenExtractor is a function that takes a context as input and returns a token. An empty string should be returned if no token found without additional information.

func FromJSON

func FromJSON(jsonKey string) TokenExtractor

FromJSON is a token extractor. Reads a json request body and extracts the json based on the given field. The request content-type should contain the: application/json header value, otherwise this method will not try to read and consume the body.

type TokenValidator

type TokenValidator interface {
	// ValidateToken accepts the token, the claims extracted from that
	// and any error that may caused by claims validation (e.g. ErrExpired)
	// or the previous validator.
	// A token validator can skip the builtin validation and return a nil error.
	// Usage:
	//  func(v *myValidator) ValidateToken(token []byte, standardClaims Claims, err error) error {
	//    if err!=nil { return err } <- to respect the previous error
	//    // otherwise return nil or any custom error.
	//  }
	//
	// Look `Blocklist`, `Expected` and `Leeway` for builtin implementations.
	ValidateToken(token []byte, err error) error
}

TokenValidator provides further token and claims validation.

type TokenValidatorFunc

type TokenValidatorFunc func(token []byte, err error) error

TokenValidatorFunc is the interface-as-function shortcut for a TokenValidator.

func (TokenValidatorFunc) ValidateToken

func (fn TokenValidatorFunc) ValidateToken(token []byte, err error) error

ValidateToken completes the ValidateToken interface. It calls itself.

type VerifiedToken

type VerifiedToken struct {
	Token   []byte // The original token.
	Header  []byte // The header (decoded) part.
	Payload []byte // The payload (decoded) part.
}

type Verifier

type Verifier struct {
	Extractors   []TokenExtractor
	Validators   []TokenValidator
	ErrorHandler func(ctx *context.Context, err error)
}

func NewVerifier

func NewVerifier(validators ...TokenValidator) *Verifier

func (*Verifier) RequestToken

func (v *Verifier) RequestToken(ctx *context.Context) (token string)

RequestToken extracts the token from the

func (*Verifier) Verify

func (v *Verifier) Verify(validators ...TokenValidator) context.Handler

func (*Verifier) VerifyToken

func (v *Verifier) VerifyToken(token []byte, validators ...TokenValidator) ([]byte, *CustomClaims, error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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