gsecurity

package module
v0.0.0-...-7962067 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2023 License: Apache-2.0 Imports: 12 Imported by: 0

README

gsecurity


go version >= 1.18

English | 中文

Golang implementation imitating sa-token

  • Login authentication
  • Kick people offline
  • Account banned
  • Session query
  • Authority certification
go get github.com/veerdone/gsecurity

Document

Login
// Login return a token, then set token to cookie or response header or response body
token := gsecurity.Login(10010)

// or use LoginAndSet,login then set token to the cookie
// the second method parameter needs to be implemented Adaptor
http.HandleFunc("/set/session", func(w http.ResponseWriter, req *http.Request) {
    gsecurity.LoginAndSet(10010, standardadaptor.New(req, w))
})
Account Banned
// disable with userId and disable expire time
gsecurity.Disable(10010, 3600)

// disable with userId, disable level, disable expire time
gsecurity.DisableWithLevel(10010, 1, 3600)

// disable with userId, disable level, disable expire time and service
gsecurity.DisableWithLevelAndService(10010, 1, 3600, "comment")

// has been disabled with userId
disabled := gsecurity.IsDisable(10010)
// or
gsecurity.IsDisableWithLevel(10010, 1)
gsecurity.IsDisableWithLevelAndService(10010, 1, "comment")

// has been disabled with userId, return error
disbleErr := gsecurity.CheckDisable(10010)
// or
gsecurity.CheckDisableWithLevel(10010, 1)
gsecurity.CheckDisableWithLevelAndService(10010, 1, "comment")
Session query
http.HandleFunc("/set/session", func (w http.ResponseWriter, req *http.Request) {
// if not login will return nil
    session := gsecurity.Sessions(standardadaptor.New(req, w))
    if session != nil {
        session.Set("key", "value")
        session.Get("key")
    }
})


Example

Documentation

Index

Constants

View Source
const (
	// NeverExpire token never expire
	NeverExpire = -1
	// NotValueExist Store getExTime if value not exist return this value
	NotValueExist = -2
	// BeReplace being knocked off the line
	BeReplace        = -4
	BeKick           = -5
	LoginIdReqCtx    = "LoginIdReqCtx"
	LoginTokenReqCtx = "LoginTokenReqCtx"
)
View Source
const ContextKey = "GSecurityContextKey"
View Source
const (
	DefaultDevice = "default-device"
)

Variables

View Source
var (
	ErrBeReplace = errors.New("has been replaced")
	ErrNotLogin  = errors.New("not login")
	ErrBeKick    = errors.New("has been kicked")
)
View Source
var (
	DefaultConfig = Config{
		TokenName:      "G-Security",
		Timeout:        2592000,
		IsConcurrent:   true,
		IsShare:        true,
		TokenStyle:     UUID,
		ReadFromQuery:  false,
		ReadFromCookie: true,
		ReadFromHeader: false,
		WriteToHeader:  false,
		WriteToCookie:  true,
		Cookie: Cookie{
			Path:     "/",
			Secure:   false,
			HttpOnly: false,
			SameSite: "Lax",
		},
	}
)
View Source
var ErrNoAdaptorInContext = errors.New("no adaptor in context")

Functions

func CheckDisable

func CheckDisable(id int64) error

func CheckDisableWithLevel

func CheckDisableWithLevel(id, level int64) error

func CheckDisableWithLevelAndService

func CheckDisableWithLevelAndService(id, level int64, service string) error

CheckDisableWithLevelAndService check disable with id, level and service, if it's disabled, return ErrDisable

func CheckDisableWithService

func CheckDisableWithService(id int64, service string) error

func CheckLogin

func CheckLogin(a Adaptor) error

func CheckLoginFromCtx

func CheckLoginFromCtx(ctx context.Context) error

CheckLoginFromCtx The method at the end of FromCtx can be used only when Adaptor is the value and ContextKey is the Key in the Context

func Disable

func Disable(id, exTime int64)

func DisableExTime

func DisableExTime(id int64) int64

func DisableExTimeWithService

func DisableExTimeWithService(id int64, services string) int64

DisableExTimeWithService get disabled expire time, if never expire return NeverExpire, if not disable return NotValueExist

func DisableWithLevel

func DisableWithLevel(id, level, exTime int64)

func DisableWithLevelAndService

func DisableWithLevelAndService(id, level, exTime int64, service string)

DisableWithLevelAndService disable with the id, level, expire time of seconds and service

func DisableWithService

func DisableWithService(id, exTime int64, service string)

func GetLoginId

func GetLoginId(a Adaptor) int64

func GetLoginIdFromCtx

func GetLoginIdFromCtx(ctx context.Context) int64

GetLoginIdFromCtx The method at the end of FromCtx can be used only when Adaptor is the value and ContextKey is the Key in the Context

func GetLoginToken

func GetLoginToken(a Adaptor) string

func GetLoginTokenFromCtx

func GetLoginTokenFromCtx(ctx context.Context) string

GetLoginTokenFromCtx The method at the end of FromCtx can be used only when Adaptor is the value and ContextKey is the Key in the Context

func HasPermission

func HasPermission(a Adaptor, p string) bool

func HasPermissionAnd

func HasPermissionAnd(a Adaptor, ps ...string) bool

func HasPermissionAndFromCtx

func HasPermissionAndFromCtx(ctx context.Context, ps ...string) bool

HasPermissionAndFromCtx The method at the end of FromCtx can be used only when Adaptor is the value and ContextKey is the Key in the Context

func HasPermissionFromCtx

func HasPermissionFromCtx(ctx context.Context, p string) bool

HasPermissionFromCtx The method at the end of FromCtx can be used only when Adaptor is the value and ContextKey is the Key in the Context

func HasPermissionOr

func HasPermissionOr(a Adaptor, ps ...string) bool

func HasPermissionOrFromCtx

func HasPermissionOrFromCtx(ctx context.Context, ps ...string) bool

HasPermissionOrFromCtx The method at the end of FromCtx can be used only when Adaptor is the value and ContextKey is the Key in the Context

func HasRole

func HasRole(a Adaptor, role string) bool

func HasRoleAnd

func HasRoleAnd(a Adaptor, roles ...string) bool

func HasRoleAndFromCtx

func HasRoleAndFromCtx(ctx context.Context, roles ...string) bool

HasRoleAndFromCtx The method at the end of FromCtx can be used only when Adaptor is the value and ContextKey is the Key in the Context

func HasRoleFromCtx

func HasRoleFromCtx(ctx context.Context, role string) bool

HasRoleFromCtx The method at the end of FromCtx can be used only when Adaptor is the value and ContextKey is the Key in the Context

func HasRoleOr

func HasRoleOr(a Adaptor, roles ...string) bool

func HasRoleOrFromCtx

func HasRoleOrFromCtx(ctx context.Context, roles ...string) bool

HasRoleOrFromCtx The method at the end of FromCtx can be used only when Adaptor is the value and ContextKey is the Key in the Context

func IsDisable

func IsDisable(id int64) bool

func IsDisableWithLevel

func IsDisableWithLevel(id, level int64) bool

func IsDisableWithLevelAndService

func IsDisableWithLevelAndService(id, level int64, service string) bool

IsDisableWithLevelAndService check is disable with id, level and service

func IsDisableWithService

func IsDisableWithService(id int64, service string) bool

func IsLogin

func IsLogin(a Adaptor) bool

func IsLoginFromCtx

func IsLoginFromCtx(ctx context.Context) bool

IsLoginFromCtx The method at the end of FromCtx can be used only when Adaptor is the value and ContextKey is the Key in the Context

func KeyMatch

func KeyMatch(key1 string, key2 string) bool

KeyMatch Example: "user.add" match "user.*" return true

func KeyMatch2

func KeyMatch2(key1 string, key2 string) bool

KeyMatch2 Example: "user.add" match "*.add" return true

func Kick

func Kick(id int64)

Kick kicking user offline by id

func KickWithDevice

func KickWithDevice(id int64, device string)

KickWithDevice kicking user offline by id and device

func KickWithToken

func KickWithToken(token string)

KickWithToken kicking user offline by token

func Login

func Login(id int64) string

func LoginAndSet

func LoginAndSet(id int64, a Adaptor) string

func LoginAndSetFromCtx

func LoginAndSetFromCtx(id int64, ctx context.Context) string

LoginAndSetFromCtx The method at the end of FromCtx can be used only when Adaptor is the value and ContextKey is the Key in the Context

func Logout

func Logout(a Adaptor)

func LogoutById

func LogoutById(id int64)

func LogoutByIdAndDevice

func LogoutByIdAndDevice(id int64, device string)

func LogoutFromCtx

func LogoutFromCtx(ctx context.Context)

LogoutFromCtx The method at the end of FromCtx can be used only when Adaptor is the value and ContextKey is the Key in the Context

func NewErrDisable

func NewErrDisable(level int64, service string) error

func RmDisable

func RmDisable(id int64)

func RmDisableWithServices

func RmDisableWithServices(id int64, services ...string)

RmDisableWithServices remove disable with id and services

func SetDefaultSecurity

func SetDefaultSecurity(l *Logic)

func SetLogger

func SetLogger(l *zap.Logger)

func SetLoggerEnable

func SetLoggerEnable(enable bool)

Types

type Adaptor

type Adaptor interface {
	GetFromHeader(tokenName string) string
	GetFromQuery(tokenName string) string
	GetFromCookie(tokenName string) string
	SetCookie(conf Config, token string)
	SetHeader(headerName, headerVal string)
	Get(key string) interface{}
	Set(key string, val interface{})
}

type Authorization

type Authorization interface {
	GetPermissionList(id int64) []string
	GetRoleList(id int64) []string
}

type Config

type Config struct {
	// token name (also Cookie name and data persistence prefix)
	TokenName string
	// token validity period
	Timeout int64
	// whether to allow concurrent logins with the same account (if true, allow concurrent logins, if false,
	// new logins will crowd out old logins)
	IsConcurrent bool
	// whether to share a token when multiple people log in to the same account (if true, all logins share a token;
	// if false, create a token for each login)
	IsShare bool
	// generated token's style, can be customized
	TokenStyle GenerateToken
	// read token from query, default true
	ReadFromQuery bool
	// read token from header, default true
	ReadFromHeader bool
	// read token from cookie, default true
	ReadFromCookie bool
	// set token to header, default false
	WriteToHeader bool
	// set token to cookie, default true
	WriteToCookie bool
	Cookie        Cookie
}
type Cookie struct {
	Domain   string
	Path     string
	Secure   bool
	HttpOnly bool
	SameSite string
}

type ErrDisable

type ErrDisable struct {
	// contains filtered or unexported fields
}

func (ErrDisable) Error

func (e ErrDisable) Error() string

type GenerateToken

type GenerateToken func() string
var (
	UUID    GenerateToken = uuid.NewString
	Rand32  GenerateToken = rand32
	Rand64  GenerateToken = rand64
	Rand128 GenerateToken = rand128
)

type Logic

type Logic struct {
	Store
	Config
	LoginType string
	// contains filtered or unexported fields
}

func NewLogic

func NewLogic(conf Config, store Store) *Logic

func NewLogicWithLoginType

func NewLogicWithLoginType(loginType string, config Config, store Store) *Logic

func (*Logic) CheckDisableWithLevelAndService

func (l *Logic) CheckDisableWithLevelAndService(id, level int64, service string) error

func (*Logic) CheckLoginByToken

func (l *Logic) CheckLoginByToken(token string) error

CheckLoginByToken check token is login, if it's login, return nil, else return error

func (*Logic) DisableExTime

func (l *Logic) DisableExTime(id int64, service string) int64

func (*Logic) DisableWithLevelAndService

func (l *Logic) DisableWithLevelAndService(id, level, exTime int64, service string)

func (*Logic) GetConfig

func (l *Logic) GetConfig() Config

func (*Logic) GetIdByToken

func (l *Logic) GetIdByToken(token string) int64

GetIdByToken if not login or token is invalid, return 0

func (*Logic) GetPermissionList

func (l *Logic) GetPermissionList(id int64) []string

func (*Logic) GetRoleList

func (l *Logic) GetRoleList(id int64) []string

func (*Logic) GetSessionById

func (l *Logic) GetSessionById(id int64) *Session

GetSessionById get session by id, if id not exist, return nil

func (*Logic) GetSessionByIdOrCreate

func (l *Logic) GetSessionByIdOrCreate(id int64) *Session

GetSessionByIdOrCreate get session by id, if not exist, create and return

func (*Logic) GetSessionByToken

func (l *Logic) GetSessionByToken(token string) *Session

GetSessionByToken get session by token, if token not exist, return nil

func (*Logic) GetStore

func (l *Logic) GetStore() Store

func (*Logic) GetTokenByIdAndDevice

func (l *Logic) GetTokenByIdAndDevice(id int64, device string) string

GetTokenByIdAndDevice get token by id and device, if not exist, return ""

func (*Logic) GetTokenTimeout

func (l *Logic) GetTokenTimeout(token string) int64

GetTokenTimeout get expire time by token, return value is the number of seconds

func (*Logic) IsDisableWithLevelAndService

func (l *Logic) IsDisableWithLevelAndService(id, level int64, service string) bool

func (*Logic) IsLoginByToken

func (l *Logic) IsLoginByToken(token string) bool

IsLoginByToken validate token is login

func (*Logic) Kick

func (l *Logic) Kick(id int64)

func (*Logic) KickWithToken

func (l *Logic) KickWithToken(token string)

func (*Logic) Login

func (l *Logic) Login(id int64) string

Login use id login

func (*Logic) LoginWithDevice

func (l *Logic) LoginWithDevice(id int64, device string) string

LoginWithDevice login with id and device

func (*Logic) Logout

func (l *Logic) Logout(id int64)

Logout with id

func (*Logic) LogoutByIdAndDevice

func (l *Logic) LogoutByIdAndDevice(id int64, device string)

LogoutByIdAndDevice logout with id and device

func (*Logic) LogoutByToken

func (l *Logic) LogoutByToken(token string)

LogoutByToken logout with token

func (*Logic) RmDisableWithServices

func (l *Logic) RmDisableWithServices(id int64, services ...string)

func (*Logic) SetAuthorization

func (l *Logic) SetAuthorization(a Authorization)

type Security

type Security struct {
	*Logic
}

func NewSecurity

func NewSecurity(l *Logic) *Security

func (*Security) CheckDisable

func (s *Security) CheckDisable(id int64) error

func (*Security) CheckDisableWithLevel

func (s *Security) CheckDisableWithLevel(id, level int64) error

func (*Security) CheckDisableWithLevelAndService

func (s *Security) CheckDisableWithLevelAndService(id, level int64, service string) error

CheckDisableWithLevelAndService check disable with id, level and service, if it's disabled, return ErrDisable

func (*Security) CheckDisableWithService

func (s *Security) CheckDisableWithService(id int64, service string) error

func (*Security) CheckLogin

func (s *Security) CheckLogin(a Adaptor) error

CheckLogin get token from adaptor.Adaptor and check token login or not, if not login, return ErrNotLogin

func (*Security) Disable

func (s *Security) Disable(id, exTime int64)

func (*Security) DisableExTime

func (s *Security) DisableExTime(id int64) int64

func (*Security) DisableExTimeWithService

func (s *Security) DisableExTimeWithService(id int64, service string) int64

DisableExTimeWithService get disabled expire time, if never expire return NeverExpire, if not disable return NotValueExist

func (*Security) DisableWithLevel

func (s *Security) DisableWithLevel(id, level, exTime int64)

func (*Security) DisableWithLevelAndService

func (s *Security) DisableWithLevelAndService(id, level, exTime int64, service string)

DisableWithLevelAndService disable with the id, level, expire time of seconds and service

func (*Security) DisableWithService

func (s *Security) DisableWithService(id, exTime int64, service string)

func (*Security) GetLoginId

func (s *Security) GetLoginId(a Adaptor) int64

func (*Security) GetPermissionList

func (s *Security) GetPermissionList(a Adaptor) []string

func (*Security) GetRoleList

func (s *Security) GetRoleList(a Adaptor) []string

func (*Security) GetToken

func (s *Security) GetToken(a Adaptor) string

GetToken get token from adaptor.Adaptor

func (*Security) HasPermission

func (s *Security) HasPermission(a Adaptor, p string) bool

func (*Security) HasPermissionAnd

func (s *Security) HasPermissionAnd(a Adaptor, ps ...string) bool

func (*Security) HasPermissionOr

func (s *Security) HasPermissionOr(a Adaptor, ps ...string) bool

func (*Security) HasRole

func (s *Security) HasRole(a Adaptor, role string) bool

func (*Security) HasRoleAnd

func (s *Security) HasRoleAnd(a Adaptor, roles ...string) bool

func (*Security) HasRoleOr

func (s *Security) HasRoleOr(a Adaptor, roles ...string) bool

func (*Security) IsDisable

func (s *Security) IsDisable(id int64) bool

func (*Security) IsDisableWithLevel

func (s *Security) IsDisableWithLevel(id, level int64) bool

func (*Security) IsDisableWithLevelAndService

func (s *Security) IsDisableWithLevelAndService(id, level int64, service string) bool

IsDisableWithLevelAndService check is disable with id, level and service

func (*Security) IsDisableWithService

func (s *Security) IsDisableWithService(id int64, service string) bool

func (*Security) IsLogin

func (s *Security) IsLogin(a Adaptor) bool

IsLogin get token from adaptor.Adaptor and check token login or not

func (*Security) Login

func (s *Security) Login(id int64) string

Login use id login, return token

func (*Security) LoginAndSet

func (s *Security) LoginAndSet(id int64, a Adaptor) string

LoginAndSet use id to login, and set token to cookie, return token

func (*Security) LoginWithDevice

func (s *Security) LoginWithDevice(id int64, device string) string

LoginWithDevice use id and device to login, return token

func (*Security) LoginWithDeviceAndSet

func (s *Security) LoginWithDeviceAndSet(id int64, device string, a Adaptor) string

func (*Security) Logout

func (s *Security) Logout(a Adaptor)

Logout get token from adaptor.Adaptor then use token to logout

func (*Security) LogoutById

func (s *Security) LogoutById(id int64)

LogoutById logout of the id

func (*Security) LogoutByIdAndDevice

func (s *Security) LogoutByIdAndDevice(id int64, device string)

LogoutByIdAndDevice logout of the id and device

func (*Security) RmDisable

func (s *Security) RmDisable(id int64)

func (*Security) RmDisableWithServices

func (s *Security) RmDisableWithServices(id int64, services ...string)

RmDisableWithServices remove disable with id and services

func (*Security) Session

func (s *Security) Session(a Adaptor) *Session

Session get token from adaptor.Adaptor then get Session by token

func (*Security) SetAuthorization

func (s *Security) SetAuthorization(a Authorization)

type Session

type Session struct {
	Id            string                 `json:"id,omitempty"`
	CreateTime    int64                  `json:"createTime,omitempty"`
	Data          map[string]interface{} `json:"data,omitempty"`
	TokenSignList []TokenSign            `json:"tokenSignList,omitempty"`
	// contains filtered or unexported fields
}

func Sessions

func Sessions(a Adaptor) *Session

func SessionsFromCtx

func SessionsFromCtx(ctx context.Context) *Session

SessionsFromCtx The method at the end of FromCtx can be used only when Adaptor is the value and ContextKey is the Key in the Context

func (*Session) AddTokenSign

func (s *Session) AddTokenSign(ts TokenSign)

func (*Session) DelTokenSignByToken

func (s *Session) DelTokenSignByToken(token string)

func (*Session) Get

func (s *Session) Get(key string) (interface{}, bool)

func (*Session) GetTokenSignByDevice

func (s *Session) GetTokenSignByDevice(device string) (TokenSign, bool)

func (*Session) GetTokenSignByToken

func (s *Session) GetTokenSignByToken(token string) (TokenSign, bool)

func (*Session) MarshalBinary

func (s *Session) MarshalBinary() (data []byte, err error)

func (*Session) Set

func (s *Session) Set(key string, val interface{})

func (*Session) UnmarshalBinary

func (s *Session) UnmarshalBinary(data []byte) error

type Store

type Store interface {
	Set(key string, val interface{}, exTime int64)
	Get(key string) (interface{}, bool)
	GetSession(key string) (interface{}, bool)
	Update(key string, val interface{})
	Delete(key string)
	GetExTime(key string) int64
	UpdateSessionTimeout(key string, exTime int64)
}

func NewDefaultStore

func NewDefaultStore(clearSleepTime int) Store

NewDefaultStore clearSleepTime is the number of seconds between each check when using default storage

func NewRedisStore

func NewRedisStore(r *redis.Client) Store

type TokenSign

type TokenSign struct {
	Val    string `json:"val,omitempty"`
	Device string `json:"device,omitempty"`
}

func (*TokenSign) MarshalBinary

func (t *TokenSign) MarshalBinary() (data []byte, err error)

func (*TokenSign) UnmarshalBinary

func (t *TokenSign) UnmarshalBinary(data []byte) error

Directories

Path Synopsis
adaptor
examples

Jump to

Keyboard shortcuts

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