token_go

package module
v0.1.65 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2023 License: Apache-2.0 Imports: 17 Imported by: 2

README

Token-Go

This library focuses on solving login authentication problems, such as: login, multi-account login, shared token login, QR Code login, logout, kickout, banned, second auth, temp-token, SSO ...

Installation

go get github.com/weloe/token-go

Simple Example

import (
	"fmt"
	tokenGo "github.com/weloe/token-go"
	"log"
	"net/http"
)

var enforcer *tokenGo.Enforcer

func main() {
	var err error
	// use default adapter
	adapter := tokenGo.NewDefaultAdapter()
	enforcer, err = tokenGo.NewEnforcer(adapter)
	// enable logger
	enforcer.EnableLog()
	if err != nil {
		log.Fatal(err)
	}

	http.HandleFunc("/user/login", Login)
	http.HandleFunc("/user/logout", Logout)
	http.HandleFunc("/user/isLogin", IsLogin)
	http.HandleFunc("/user/kickout", Kickout)

	log.Fatal(http.ListenAndServe(":8081", nil))
}

func Login(w http.ResponseWriter, req *http.Request) {
	token, err := enforcer.Login("1", tokenGo.NewHttpContext(req, w))
	if err != nil {
		fmt.Fprintf(w, "Login error: %s\n", err)
	}
	fmt.Fprintf(w, "token: %s\n", token)
}

func Logout(w http.ResponseWriter, req *http.Request) {
	err := enforcer.Logout(tokenGo.NewHttpContext(req, w))
	if err != nil {
		fmt.Fprintf(w, "Logout error: %s\n", err)
	}
	fmt.Fprintf(w, "logout success")
}

func IsLogin(w http.ResponseWriter, req *http.Request) {
	login, err := enforcer.IsLogin(tokenGo.NewHttpContext(req, w))
	if err != nil {
		fmt.Fprintf(w, "IsLogin() = %v: %v", login, err)
	}
	fmt.Fprintf(w, "IsLogin() = %v", login)
}

func Kickout(w http.ResponseWriter, req *http.Request) {
	err := enforcer.Kickout(req.URL.Query().Get("id"), "")
	if err != nil {
		fmt.Fprintf(w, "error: %s\n", err)
	}
	fmt.Fprintf(w, "logout success")
}

Custom TokenConfig

The same user can only log in once: IsConcurrent = false && IsShare = false

The same user logs in multiple times and shares a token: IsConcurrent = true && IsShare = true

Multiple logins of the same user to multiple tokens: IsConcurrent = true && IsShare = false

import (
	"fmt"
	tokenGo "github.com/weloe/token-go"
	"github.com/weloe/token-go/config"
	"log"
	"net/http"
)

var enforcer *tokenGo.Enforcer

func main() {
	var err error
	// use default adapter
	adapter := tokenGo.NewDefaultAdapter()
	tokenConfig := &config.TokenConfig{
		TokenName:     "uuid",
		Timeout:       60,
		IsReadCookie:  true,
		IsReadHeader:  true,
		IsReadBody:    false,
		IsConcurrent:  true,
		IsShare:       true,
		MaxLoginCount: -1,
	}
	enforcer, err = tokenGo.NewEnforcer(adapter, tokenConfig)
}

You can also configure it using a yml or ini file like this

token-go/token_conf.ini at master · weloe/token-go · GitHub

token-go/token_conf.yaml at master · weloe/token-go · GitHub

Then use enforcer, err = tokenGo.NewEnforcer(adapter, filepath) to init.

Authorization

A simple permission verification method is also provided

type ACL interface {
	GetPermission(id string) []string
}
type RBAC interface {
	GetRole(id string) []string
}

Implement either of these two interfaces and call enforcer.SetAuth(model) After that, you can use these two APIs for permission verification

// implement RBAC
CheckRole(ctx ctx.Context, role string) error
// implement ACL
CheckPermission(ctx ctx.Context, permission string) error
example
type Auth struct {
}

func (m *Auth) GetRole(id string) []string {
	var arr = make([]string, 2)
	arr[1] = "user"
	return arr
}
func (m *Auth) GetPermission(id string) []string {
	var arr = make([]string, 2)
	arr[1] = "user::get"
	return arr
}


func main() {
	var err error
	// use default adapter
	adapter := tokenGo.NewDefaultAdapter()
	enforcer, err = tokenGo.NewEnforcer(adapter)
	// set auth
	enforcer.SetAuth(&Auth{})
	// enable logger
	enforcer.EnableLog()
	if err != nil {
		log.Fatal(err)
	}
	
	http.HandleFunc("/user/check", CheckAuth)
	
	log.Fatal(http.ListenAndServe(":8081", nil))
}

func CheckAuth(w http.ResponseWriter, req *http.Request) {
	ctx := tokenGo.NewHttpContext(req, w)
	err := enforcer.CheckRole(ctx, "user")
	if err != nil {
		fmt.Fprintf(w, "CheckRole() error: %s\n", err)
		return
	}
	err = enforcer.CheckPermission(ctx, "user::get")
	if err != nil {
		fmt.Fprintf(w, "CheckPermission() error: %s\n", err)
		return
	}
	fmt.Fprintf(w, "you have authorization")
}

SSO

SSO-Server examples: https://github.com/weloe/token-go/blob/master/examples/sso/sso-server/sso-server.go

SSO-Client examples: https://github.com/weloe/token-go/blob/master/examples/sso/sso-client-3/sso-client.go

Extensions

https://github.com/weloe/token-go-extensions

Adapter
RedisAdapter go get github.com/weloe/token-go-extensions/redis-adapter
Enforcer
StatelessEnforcer go get github.com/weloe/token-go-extensions/jwt

Documentation

https://github.com/weloe/token-go/wiki

Api

token_go package - github.com/weloe/token-go - Go Packages

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewDefaultAdapter

func NewDefaultAdapter() persist.Adapter

func NewHttpContext

func NewHttpContext(req *http.Request, writer http.ResponseWriter) ctx.Context

Types

type DistributedEnforcer added in v0.1.6

type DistributedEnforcer struct {
	*Enforcer
}

func NewDistributedEnforcer added in v0.1.6

func NewDistributedEnforcer(enforcer *Enforcer) *DistributedEnforcer

func (*DistributedEnforcer) DeleteSelf added in v0.1.6

func (e *DistributedEnforcer) DeleteSelf(key string) error

func (*DistributedEnforcer) EnableDispatcher added in v0.1.6

func (e *DistributedEnforcer) EnableDispatcher(b bool)

func (*DistributedEnforcer) SetSelf added in v0.1.6

func (e *DistributedEnforcer) SetSelf(key string, value interface{}, timeout int64) error

func (*DistributedEnforcer) SetStrSelf added in v0.1.6

func (e *DistributedEnforcer) SetStrSelf(key string, value string, timeout int64) error

func (*DistributedEnforcer) UpdateSelf added in v0.1.6

func (e *DistributedEnforcer) UpdateSelf(key string, value interface{}) error

func (*DistributedEnforcer) UpdateStrSelf added in v0.1.6

func (e *DistributedEnforcer) UpdateStrSelf(key string, value string) error

func (*DistributedEnforcer) UpdateTimeoutSelf added in v0.1.6

func (e *DistributedEnforcer) UpdateTimeoutSelf(key string, timeout int64) error

type Enforcer

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

func InitWithConfig

func InitWithConfig(tokenConfig *config.TokenConfig, adapter persist.Adapter) (*Enforcer, error)

func InitWithDefaultConfig

func InitWithDefaultConfig(adapter persist.Adapter) (*Enforcer, error)

func InitWithFile

func InitWithFile(conf string, adapter persist.Adapter) (*Enforcer, error)

func NewEnforcer

func NewEnforcer(adapter persist.Adapter, args ...interface{}) (*Enforcer, error)

func (*Enforcer) AddTokenGenerateFun

func (e *Enforcer) AddTokenGenerateFun(tokenStyle string, f model.HandlerFunc) error

AddTokenGenerateFun add token generate strategy

func (*Enforcer) Banned

func (e *Enforcer) Banned(id string, service string, level int, time int64) error

Banned ban user, if time == 0,the timeout is not set

func (*Enforcer) CancelAuth added in v0.1.3

func (e *Enforcer) CancelAuth(tempToken string) error

CancelAuth update state to constant.CancelAuth

func (*Enforcer) CheckLogin

func (e *Enforcer) CheckLogin(ctx ctx.Context) error

func (*Enforcer) CheckLoginByToken added in v0.0.9

func (e *Enforcer) CheckLoginByToken(token string) error

func (*Enforcer) CheckPermission

func (e *Enforcer) CheckPermission(ctx ctx.Context, permission string) error

func (*Enforcer) CheckRole

func (e *Enforcer) CheckRole(ctx ctx.Context, role string) error

func (*Enforcer) CloseSafe added in v0.0.9

func (e *Enforcer) CloseSafe(token string, service string) error

func (*Enforcer) ConfirmAuth added in v0.1.3

func (e *Enforcer) ConfirmAuth(tempToken string) error

ConfirmAuth update state to constant.ConfirmAuth

func (*Enforcer) CreateQRCodeState added in v0.1.3

func (e *Enforcer) CreateQRCodeState(QRCodeId string, timeout int64) error

func (*Enforcer) CreateTempToken added in v0.1.0

func (e *Enforcer) CreateTempToken(token string, service string, value string, timeout int64) (string, error)

func (*Enforcer) CreateTempTokenByStyle added in v0.1.7

func (e *Enforcer) CreateTempTokenByStyle(style string, service string, value string, timeout int64) (string, error)

func (*Enforcer) DeleteQRCode added in v0.1.5

func (e *Enforcer) DeleteQRCode(QRCodeId string) error

func (*Enforcer) DeleteSession added in v0.0.6

func (e *Enforcer) DeleteSession(id string) error

func (*Enforcer) DeleteTempToken added in v0.1.0

func (e *Enforcer) DeleteTempToken(service string, tempToken string) error

func (*Enforcer) EnableLog

func (e *Enforcer) EnableLog()

func (*Enforcer) EnableUpdatableWatcher added in v0.1.6

func (e *Enforcer) EnableUpdatableWatcher(b bool)

func (*Enforcer) GetAdapter

func (e *Enforcer) GetAdapter() persist.Adapter

func (*Enforcer) GetBannedLevel added in v0.0.5

func (e *Enforcer) GetBannedLevel(id string, service string) (int64, error)

GetBannedLevel get banned level

func (*Enforcer) GetBannedTime added in v0.0.5

func (e *Enforcer) GetBannedTime(id string, service string) int64

GetBannedTime get banned time

func (*Enforcer) GetId added in v0.1.0

func (e *Enforcer) GetId(ctx ctx.Context) string

GetId get the id from the Adapter, do not check the value

if GetId()= -4, it means that user be replaced
if GetId()= -5, it means that user be kicked
if GetId()= -6, it means that user be banned

func (*Enforcer) GetIdByToken added in v0.0.5

func (e *Enforcer) GetIdByToken(token string) string

GetIdByToken get the id from the Adapter

func (*Enforcer) GetLogger added in v0.0.5

func (e *Enforcer) GetLogger() log.Logger

func (*Enforcer) GetLoginCount

func (e *Enforcer) GetLoginCount(id string, device ...string) int

func (*Enforcer) GetLoginCounts added in v0.1.7

func (e *Enforcer) GetLoginCounts() (int, error)

func (*Enforcer) GetLoginId

func (e *Enforcer) GetLoginId(ctx ctx.Context) (string, error)

GetLoginId get id and check it

func (*Enforcer) GetLoginIdByToken added in v0.0.9

func (e *Enforcer) GetLoginIdByToken(token string) (string, error)

func (*Enforcer) GetLoginTokenCounts added in v0.1.7

func (e *Enforcer) GetLoginTokenCounts() (int, error)

func (*Enforcer) GetQRCode added in v0.1.3

func (e *Enforcer) GetQRCode(QRCodeId string) *model.QRCode

func (*Enforcer) GetQRCodeState added in v0.1.3

func (e *Enforcer) GetQRCodeState(QRCodeId string) model.QRCodeState

GetQRCodeState

WaitScan   = 1
WaitAuth   = 2
ConfirmAuth  = 3
CancelAuth = 4
Expired    = 5

func (*Enforcer) GetQRCodeTimeout added in v0.1.3

func (e *Enforcer) GetQRCodeTimeout(QRCodeId string) int64

func (*Enforcer) GetRequestToken

func (e *Enforcer) GetRequestToken(ctx ctx.Context) string

GetRequestToken read token from requestHeader | cookie | requestBody

func (*Enforcer) GetSafeTime added in v0.0.9

func (e *Enforcer) GetSafeTime(token string, service string) int64

func (*Enforcer) GetSession

func (e *Enforcer) GetSession(id string) *model.Session

func (*Enforcer) GetTempTokenTimeout added in v0.1.0

func (e *Enforcer) GetTempTokenTimeout(service string, tempToken string) int64

func (*Enforcer) GetTokenConfig added in v0.0.5

func (e *Enforcer) GetTokenConfig() config.TokenConfig

func (*Enforcer) GetType

func (e *Enforcer) GetType() string

func (*Enforcer) GetUpdatableWatcher added in v0.1.7

func (e *Enforcer) GetUpdatableWatcher() persist.UpdatableWatcher

func (*Enforcer) GetWatcher added in v0.0.5

func (e *Enforcer) GetWatcher() persist.Watcher

func (*Enforcer) IsBanned added in v0.0.5

func (e *Enforcer) IsBanned(id string, service string) bool

IsBanned if banned return true, else return false

func (*Enforcer) IsLogEnable

func (e *Enforcer) IsLogEnable() bool

func (*Enforcer) IsLogin

func (e *Enforcer) IsLogin(ctx ctx.Context) (bool, error)

IsLogin check if user logged in by token.

func (*Enforcer) IsLoginById

func (e *Enforcer) IsLoginById(id string, device ...string) (bool, error)

IsLoginById check if user logged in by loginId. check all tokenValue and if one is validated return true

func (*Enforcer) IsLoginByToken added in v0.0.5

func (e *Enforcer) IsLoginByToken(tokenValue string) (bool, error)

func (*Enforcer) IsSafe added in v0.0.9

func (e *Enforcer) IsSafe(token string, service string) bool

func (*Enforcer) Kickout

func (e *Enforcer) Kickout(id string, device ...string) error

Kickout kickout user

func (*Enforcer) Login

func (e *Enforcer) Login(id string, ctx ctx.Context) (string, error)

Login login by id and default loginModel, return tokenValue and error

func (*Enforcer) LoginById added in v0.0.6

func (e *Enforcer) LoginById(id string, device ...string) (string, error)

func (*Enforcer) LoginByModel

func (e *Enforcer) LoginByModel(id string, loginModel *model.Login, ctx ctx.Context) (string, error)

LoginByModel login by id and loginModel, return tokenValue and error

func (*Enforcer) Logout

func (e *Enforcer) Logout(ctx ctx.Context) error

Logout user logout

func (*Enforcer) LogoutById added in v0.0.6

func (e *Enforcer) LogoutById(id string, device ...string) error

LogoutById force user to logout

func (*Enforcer) LogoutByToken added in v0.0.5

func (e *Enforcer) LogoutByToken(token string) error

LogoutByToken clear token info

func (*Enforcer) OpenSafe added in v0.0.9

func (e *Enforcer) OpenSafe(token string, service string, time int64) error

func (*Enforcer) ParseTempToken added in v0.1.0

func (e *Enforcer) ParseTempToken(service string, tempToken string) string

func (*Enforcer) Replaced

func (e *Enforcer) Replaced(id string, device ...string) error

Replaced replace other user

func (*Enforcer) ResponseToken added in v0.0.5

func (e *Enforcer) ResponseToken(tokenValue string, loginModel *model.Login, ctx ctx.Context) error

ResponseToken set token to cookie or header

func (*Enforcer) Scanned added in v0.1.3

func (e *Enforcer) Scanned(QRCodeId string, loginId string) (string, error)

Scanned update state to constant.WaitAuth, return tempToken

func (*Enforcer) SetAdapter

func (e *Enforcer) SetAdapter(adapter persist.Adapter)

func (*Enforcer) SetAuth

func (e *Enforcer) SetAuth(manager interface{})

func (*Enforcer) SetDispatcher added in v0.1.6

func (e *Enforcer) SetDispatcher(dispatcher persist.Dispatcher)

func (*Enforcer) SetIdByToken added in v0.1.3

func (e *Enforcer) SetIdByToken(id string, tokenValue string, timeout int64) error

func (*Enforcer) SetJwtSecretKey added in v0.0.5

func (e *Enforcer) SetJwtSecretKey(key string)

func (*Enforcer) SetLogger

func (e *Enforcer) SetLogger(logger log.Logger)

func (*Enforcer) SetSession

func (e *Enforcer) SetSession(id string, session *model.Session, timeout int64) error

func (*Enforcer) SetType

func (e *Enforcer) SetType(t string)

func (*Enforcer) SetUpdatableWatcher added in v0.1.7

func (e *Enforcer) SetUpdatableWatcher(watcher persist.UpdatableWatcher)

func (*Enforcer) SetWatcher

func (e *Enforcer) SetWatcher(watcher persist.Watcher)

func (*Enforcer) UnBanned added in v0.0.5

func (e *Enforcer) UnBanned(id string, services ...string) error

UnBanned Unblock user account

func (*Enforcer) UpdateSession added in v0.0.6

func (e *Enforcer) UpdateSession(id string, session *model.Session) error

type IDistributedEnforcer added in v0.1.6

type IDistributedEnforcer interface {
	IEnforcer
	// SetStrSelf store string in all instances
	SetStrSelf(key string, value string, timeout int64) error
	// UpdateStrSelf only update string value in all instances
	UpdateStrSelf(key string, value string) error
	// SetSelf store interface{} in all instances
	SetSelf(key string, value interface{}, timeout int64) error
	// UpdateSelf only update interface{} value in all instances
	UpdateSelf(key string, value interface{}) error
	// DeleteSelf delete interface{} value in all instances
	DeleteSelf(key string) error
	// UpdateTimeoutSelf update timeout in all instances
	UpdateTimeoutSelf(key string, timeout int64) error
}

type IEnforcer

type IEnforcer interface {
	// Enforcer field api
	SetType(t string)
	GetType() string
	GetAdapter() persist.Adapter
	SetAdapter(adapter persist.Adapter)
	SetWatcher(watcher persist.Watcher)
	GetWatcher() persist.Watcher
	SetLogger(logger log.Logger)
	GetLogger() log.Logger
	EnableLog()
	IsLogEnable() bool
	GetTokenConfig() config.TokenConfig

	// Login login api
	Login(id string, ctx ctx.Context) (string, error)
	LoginById(id string, device ...string) (string, error)
	LoginByModel(id string, loginModel *model.Login, ctx ctx.Context) (string, error)

	Logout(ctx ctx.Context) error
	LogoutById(id string, device ...string) error
	LogoutByToken(token string) error

	IsLogin(ctx ctx.Context) (bool, error)
	IsLoginByToken(token string) (bool, error)
	IsLoginById(id string, device ...string) (bool, error)
	CheckLogin(ctx ctx.Context) error
	CheckLoginByToken(token string) error

	GetLoginId(ctx ctx.Context) (string, error)
	GetLoginIdByToken(token string) (string, error)
	GetId(ctx ctx.Context) string
	GetIdByToken(token string) string
	GetLoginCount(id string, device ...string) int

	GetLoginCounts() (int, error)
	GetLoginTokenCounts() (int, error)

	Kickout(id string, device ...string) error
	Replaced(id string, device ...string) error

	// Banned banned api
	Banned(id string, service string, level int, time int64) error
	UnBanned(id string, services ...string) error
	IsBanned(id string, service string) bool
	GetBannedLevel(id string, service string) (int64, error)
	GetBannedTime(id string, service string) int64

	// Second auth api
	OpenSafe(token string, service string, time int64) error
	IsSafe(token string, service string) bool
	GetSafeTime(token string, service string) int64
	CloseSafe(token string, service string) error

	// Temp token api
	CreateTempToken(token string, service string, value string, timeout int64) (string, error)
	CreateTempTokenByStyle(style string, service string, value string, timeout int64) (string, error)
	GetTempTokenTimeout(service string, tempToken string) int64
	ParseTempToken(service string, tempToken string) string
	DeleteTempToken(service string, tempToken string) error

	GetRequestToken(ctx ctx.Context) string
	AddTokenGenerateFun(tokenStyle string, f model.HandlerFunc) error

	// QRCode api
	CreateQRCodeState(QRCodeId string, timeout int64) error
	GetQRCode(QRCodeId string) *model.QRCode
	GetQRCodeState(QRCodeId string) model.QRCodeState
	GetQRCodeTimeout(QRCodeId string) int64
	DeleteQRCode(QRCodeId string) error
	Scanned(QRCodeId string, loginId string) (string, error)
	ConfirmAuth(QRCodeTempToken string) error
	CancelAuth(QRCodeTempToken string) error

	// Access control api
	SetAuth(manager interface{})
	CheckRole(ctx ctx.Context, role string) error
	CheckPermission(ctx ctx.Context, permission string) error

	// Session api
	GetSession(id string) *model.Session
	DeleteSession(id string) error
	UpdateSession(id string, session *model.Session) error
	SetSession(id string, session *model.Session, timeout int64) error
}

Jump to

Keyboard shortcuts

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