gtoken

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Jul 11, 2026 License: MIT Imports: 25 Imported by: 0

Documentation

Index

Constants

View Source
const (
	CacheModeCache   = 0
	CacheModeRedis   = 1
	CacheModeFile    = 2
	CacheModeFileDat = "gtoken.dat"

	DefaultExpireIn        = 7 * 24 * time.Hour
	DefaultRefreshExpireIn = 24 * time.Hour
	DefaultRefreshLimit    = uint8(1)
	DefaultSecretKey       = "g1t@o3K!e7n"
	DefaultTokenIDLength   = 12

	TokenKeyInRequest = "token" // ok for: router, query, body, form, custom

	DefaultLogPrefix = "[GToken]"

	DefaultPrefixToken  = "jwt:"
	DefaultPrefixUser   = "user:"
	DefaultPrefixFamily = "refresh-family:"
	DefaultPrefixAccess = "refresh-access:"

	PrefixBearer = "Bearer "

	DefaultCodeOK           = 0
	DefaultCodeUnauthorized = 401
)
View Source
const (
	LogLevelDebug   = "debug"
	LogLevelInfo    = "info"
	LogLevelWarning = "warning"
	LogLevelError   = "error"
)

Variables

View Source
var (
	// ErrRefreshTokenRejected is the generic refresh rejection used at public boundaries.
	ErrRefreshTokenRejected = errors.New("refresh token rejected")
	// ErrRefreshTokenExpired identifies an expired refresh credential for internal control flow.
	ErrRefreshTokenExpired = errors.New("refresh token expired")
	// ErrRefreshTokenReplay identifies reuse of a consumed refresh credential.
	ErrRefreshTokenReplay = errors.New("refresh token replay")
)

Functions

func CheckAuthRequired

func CheckAuthRequired(publicPaths []string, urlPath string, urlMethod string) bool

func ParseRequestToken added in v1.1.0

func ParseRequestToken(r *ghttp.Request) string

ParseRequestToken tries to get token from the following path by priority: 1. header.Authorization 2. token

func WriteLog

func WriteLog(ctx context.Context, msg string, logLevel string)

Types

type DefaultResponse

type DefaultResponse struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

type GToken

type GToken struct {
	CacheMode        uint8                                       // 0 cache (default) 1 redis 2 file
	ExpireIn         time.Duration                               // how long a token will be invalid
	SingleSession    bool                                        // if true, only one token can be kept, so the old one will be deleted
	AutoRefreshToken bool                                        // whether to extend legacy token expiry automatically. Deprecated: use explicit token-pair renewal in production
	SecretKey        []byte                                      // jwt secret key, why use []byte: https://golang-jwt.github.io/jwt/usage/signing_methods/#frequently-asked-questions
	TokenIDLength    uint8                                       // length of NanoID, default 12
	PublicPaths      []string                                    // non-auth paths. Support restful formats like "POST:/login"
	DoBeforeAuth     func(r *ghttp.Request) (ok bool)            // generally, we omit the file requests in this func
	DoAfterAuth      func(r *ghttp.Request, ok bool, data g.Map) // generally, we add info into context in this func
	RefreshExpireIn  time.Duration                               // absolute lifetime of the one-time refresh credential
	RefreshLimit     uint8                                       // number of explicit renewals; the token-pair API currently requires 1
	Clock            func() time.Time                            // optional UTC clock for deterministic tests
	CacheFilePath    string                                      // optional persistence path for CacheModeFile
	// contains filtered or unexported fields
}

func (*GToken) Init

func (m *GToken) Init(ctx context.Context) bool

func (*GToken) NewToken

func (m *GToken) NewToken(ctx context.Context, userID string, extraData g.Map) (token string, tokenInfo *TokenInfo, err error)

NewToken returns a new token

func (*GToken) NewTokenPair added in v1.2.0

func (m *GToken) NewTokenPair(ctx context.Context, userID string, extraData g.Map) (*TokenPair, error)

NewTokenPair issues an access token and a one-time refresh credential.

func (*GToken) RefreshTokenPair added in v1.2.0

func (m *GToken) RefreshTokenPair(ctx context.Context, refreshToken string, expectedExtraData g.Map) (*TokenPair, error)

RefreshTokenPair atomically consumes a refresh credential and issues the final access token.

func (*GToken) RemoveToken

func (m *GToken) RemoveToken(ctx context.Context, token string) (ok bool, err error)

RemoveToken deletes Token

func (*GToken) RevokeTokenFamily added in v1.2.0

func (m *GToken) RevokeTokenFamily(ctx context.Context, accessToken string, refreshToken string) error

RevokeTokenFamily invalidates a token family identified by either access or refresh credential.

func (*GToken) UseMiddleware

func (m *GToken) UseMiddleware(ctx context.Context, group *ghttp.RouterGroup) error

func (*GToken) ValidateToken

func (m *GToken) ValidateToken(ctx context.Context, token string) (*TokenInfo, error)

ValidateToken returns token info. If AutoRefreshToken is true, refresh token ttl.

type TokenFamily added in v1.2.0

type TokenFamily struct {
	FamilyID               string      `json:"familyID"`
	UserID                 string      `json:"userID"`
	ExtraData              g.Map       `json:"extraData"`
	RefreshDigest          string      `json:"refreshDigest"`
	CurrentAccessTokenID   string      `json:"currentAccessTokenID"`
	SuccessorAccessTokenID string      `json:"successorAccessTokenID,omitempty"`
	IssuedAt               *gtime.Time `json:"issuedAt"`
	RefreshExpiresAt       *gtime.Time `json:"refreshExpiresAt"`
	FamilyExpiresAt        *gtime.Time `json:"familyExpiresAt"`
	RefreshExpiresAtMillis int64       `json:"refreshExpiresAtMillis"`
	FamilyExpiresAtMillis  int64       `json:"familyExpiresAtMillis"`
	State                  string      `json:"state"`
}

TokenFamily is the persisted lifecycle record shared by an initial and renewed access token.

type TokenInfo added in v1.1.0

type TokenInfo struct {
	UserID    string      `json:"userID"`
	TokenID   string      `json:"tokenID"`
	ExtraData g.Map       `json:"extraData"`
	ExpireAt  *gtime.Time `json:"ExpireAt"`
	RefreshAt *gtime.Time `json:"RefreshAt"`
	FamilyID  string      `json:"familyID,omitempty"`
}

type TokenPair added in v1.2.0

type TokenPair struct {
	AccessToken      string
	AccessTokenInfo  *TokenInfo
	RefreshToken     string
	RefreshExpiresAt *gtime.Time
}

TokenPair contains an access token and, on initial issuance, a one-time refresh token.

Jump to

Keyboard shortcuts

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