gg_auth0

package
v0.3.39 Latest Latest
Warning

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

Go to latest
Published: Mar 5, 2025 License: BSD-3-Clause Imports: 9 Imported by: 5

README

GG Auth0

GG Auth0 is a library to help developers play with JWT.

Note

Internal JWT implementation is a porting of original go-jwt library.

JWT.io has a great introduction to JSON Web Tokens.

Example

Create and Validate a Token

package main

import (
    "bitbucket.org/digi-sense/gg-core-x/gg_auth0/jwt"
    "bitbucket.org/digi-sense/gg-core-x/gg_auth0/jwt/signing"
    "bitbucket.org/digi-sense/gg-core-x/gg_auth0/jwt/elements"
    "errors"
    "fmt"
    "io/ioutil"
    "time"
)

var hmacSampleSecret []byte

func main(){
    nbf := time.Date(2015, 10, 10, 12, 0, 0, 0, time.UTC).Unix()

	// Create a new token object, specifying signing method and the claims
	// you would like it to contain.
	token := jwt.NewWithClaims(signing.SigningMethodHS256, elements.MapClaims{
		"foo": "bar",
		"nbf": nbf,
		"uid":"USER_1234",
	})

	// Sign and get the complete encoded token as a string using the secret
	tokenString, err := token.SignedString(hmacSampleSecret)

	fmt.Println(tokenString, err)

	// Parse takes the token string and a function for looking up the key. The latter is especially
	// useful if you use multiple keys for your application.  The standard is to use 'kid' in the
	// head of the token to identify which key to use, but the parsed token (head and claims) is provided
	// to the callback, providing flexibility.
	parsed, err := jwt.Parse(tokenString, func(token *elements.Token) (interface{}, error) {
		// Don't forget to validate the alg is what you expect:
		if _, ok := token.Method.(*signing.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		}

		// hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
		return hmacSampleSecret, nil
	})

	if nil==parsed{
		panic(errors.New("TOKEN not parsed!"))
	}

	if claims, ok := parsed.Claims.(elements.MapClaims); ok && parsed.Valid {
		foo := claims["foo"].(string)
		uid := claims["uid"].(string)
		if foo != "bar" {
			panic(errors.New("foo is not 'bar'"))
		}
		fmt.Println(foo, claims["nbf"], uid)
	}
}
 
func init() {
	// Load sample key data
	if keyData, e := ioutil.ReadFile("./_test/test/hmacTestKey"); e == nil {
		hmacSampleSecret = keyData
	} else {
		panic(e)
	}
}
   

Documentation

Index

Constants

View Source
const (
	CACHE_KEY                  = "jti"
	FLD_USERID                 = "user_id"
	FLD_PAYLOAD                = "payload"
	FLD_CONFIRMED              = "confirmed" // user confirmed account
	FLD_USERNAME               = "user_name"
	FLD_USERPASSWORD           = "user_psw"
	FLD_USERPASSWORD_TIMESTAMP = "user_psw_timestamp" // last change timestamp
	FLD_SECRET_TYPE            = "secret_type"
	FLD_EXP                    = "exp"
)
View Source
const (
	TAccess = iota
	TRefresh
	TConfirm
	TDelegate
)
View Source
const (
	AuthSecretName    = "auth" // used to encrypt authentication data into db
	AccessSecretName  = "access"
	RefreshSecretName = "refresh"
)

Variables

View Source
var (
	ErrorMissingSecureKey     = errors.New("missing_secure_key")
	ErrorMissingClaims        = errors.New("missing_claims")
	ErrorUnauthorized         = errors.New("unauthorized_401")
	ErrorNotConfirmed         = errors.New("not_confirmed")
	ErrorMalformedAccountData = errors.New("malformed_account_data")
	ErrorPasswordExpired      = errors.New("password_expired")
)

Functions

func GetAccessCacheDuration

func GetAccessCacheDuration() time.Duration

func GetAccessTokenDuration

func GetAccessTokenDuration() time.Duration

func GetRefreshTokenDuration

func GetRefreshTokenDuration() time.Duration

func IsPasswordExpired

func IsPasswordExpired(payload map[string]interface{}) bool

func SetAccessCacheDuration

func SetAccessCacheDuration(value time.Duration)

func SetAccessTokenDuration

func SetAccessTokenDuration(value time.Duration)

func SetRefreshTokenDuration

func SetRefreshTokenDuration(value time.Duration)

Types

type Auth0

type Auth0 struct {
	OTPLength             int
	OTPOnlyDigits         bool
	OTPDuration           time.Duration
	PasswordDurationDays  int
	AccessTokenDuration   time.Duration
	AccessCacheDuration   time.Duration
	RefreshTokenDuration  time.Duration
	ConfirmTokenDuration  time.Duration
	DelegateTokenDuration time.Duration
	// contains filtered or unexported fields
}

func NewAuth0

func NewAuth0(config ...interface{}) *Auth0

func (*Auth0) AuthChangeLogin

func (instance *Auth0) AuthChangeLogin(currentId, newCleanUsername, newCleanPassword string) *Auth0Response

AuthChangeLogin change username or password for login. New entity is created

func (*Auth0) AuthConfirm

func (instance *Auth0) AuthConfirm(confirmToken string) *Auth0Response

func (*Auth0) AuthGetCredentials

func (instance *Auth0) AuthGetCredentials(currentId string) (username, password string, err error)

AuthGetCredentials Expose user credentials in code may be Unsecure!!! Use this method only for debugging

func (*Auth0) AuthGrantDelegation

func (instance *Auth0) AuthGrantDelegation(ownerToken string) *Auth0Response

AuthGrantDelegation create a delegation token that impersonate owner and can be used

func (*Auth0) AuthRemove

func (instance *Auth0) AuthRemove(accessToken string) error

AuthRemove remove entity and associated tokens

func (*Auth0) AuthRemoveByUserId

func (instance *Auth0) AuthRemoveByUserId(userId string) error

AuthRemoveByUserId remove entity

func (*Auth0) AuthRevokeDelegation

func (instance *Auth0) AuthRevokeDelegation(delegationToken string) error

func (*Auth0) AuthSignIn

func (instance *Auth0) AuthSignIn(cleanUsername, cleanPassword string) *Auth0Response

AuthSignIn try to log in and returns itemId, itemPayload, error

func (*Auth0) AuthSignInNoExpire

func (instance *Auth0) AuthSignInNoExpire(cleanUsername, cleanPassword string) *Auth0Response

func (*Auth0) AuthSignInOTP

func (instance *Auth0) AuthSignInOTP(cleanUsername, cleanPassword, otp string) (response *Auth0Response)

func (*Auth0) AuthSignInOTPNoExpire

func (instance *Auth0) AuthSignInOTPNoExpire(cleanUsername, cleanPassword, otp string) (response *Auth0Response)

func (*Auth0) AuthSignUp

func (instance *Auth0) AuthSignUp(cleanUsername, cleanPassword string, cleanPayload map[string]interface{}) *Auth0Response

func (*Auth0) AuthSignUpAndConfirm

func (instance *Auth0) AuthSignUpAndConfirm(cleanUsername, cleanPassword string, cleanPayload map[string]interface{}) (response *Auth0Response)

func (*Auth0) AuthUpdate

func (instance *Auth0) AuthUpdate(currentId string, cleanPayload map[string]interface{}) (string, error)

AuthUpdate update existing item Parameter currentId is required. return itemId and error

func (*Auth0) Close

func (instance *Auth0) Close() (err error)

func (*Auth0) Open

func (instance *Auth0) Open() (err error)

func (*Auth0) Secrets

func (instance *Auth0) Secrets() Auth0ConfigSecrets

func (*Auth0) TokenClaims

func (instance *Auth0) TokenClaims(stringToken string) (claims map[string]interface{}, err error)

func (*Auth0) TokenClaimsNoValidate

func (instance *Auth0) TokenClaimsNoValidate(stringToken string) (claims map[string]interface{})

func (*Auth0) TokenParse

func (instance *Auth0) TokenParse(stringToken string) (map[string]interface{}, error)

func (*Auth0) TokenRefresh

func (instance *Auth0) TokenRefresh(stringRefreshToken string) *Auth0Response

func (*Auth0) TokenRefreshAccess

func (instance *Auth0) TokenRefreshAccess(stringAccessToken, stringRefreshToken string) *Auth0Response

TokenRefreshAccess utility method that do not check on db for token existance

func (*Auth0) TokenValidate

func (instance *Auth0) TokenValidate(stringToken string) (bool, error)

type Auth0Claims

type Auth0Claims struct {
	UserId     string                 `json:"user_id,omitempty"`
	Payload    map[string]interface{} `json:"payload,omitempty"`
	SecretType string                 `json:"secret_type,omitempty"`
	elements.StandardClaims
}

type Auth0Config

type Auth0Config struct {
	Secrets      Auth0ConfigSecrets  `json:"secrets"`
	CacheStorage *Auth0ConfigStorage `json:"cache-storage"`
	AuthStorage  *Auth0ConfigStorage `json:"auth-storage"`
}

func Auth0ConfigLoad

func Auth0ConfigLoad(fileName string) (*Auth0Config, error)

func Auth0ConfigNew

func Auth0ConfigNew() *Auth0Config

func Auth0ConfigParse

func Auth0ConfigParse(json string) *Auth0Config

func (*Auth0Config) GoString

func (instance *Auth0Config) GoString() string

func (*Auth0Config) String

func (instance *Auth0Config) String() string

type Auth0ConfigSecrets

type Auth0ConfigSecrets map[string]string

func (Auth0ConfigSecrets) Get

func (instance Auth0ConfigSecrets) Get(key string) string

func (Auth0ConfigSecrets) GetNotEmpty

func (instance Auth0ConfigSecrets) GetNotEmpty(key string) string

func (Auth0ConfigSecrets) Put

func (instance Auth0ConfigSecrets) Put(key, value string)

func (Auth0ConfigSecrets) Remove

func (instance Auth0ConfigSecrets) Remove(key string) (value string)

func (Auth0ConfigSecrets) String

func (instance Auth0ConfigSecrets) String() string

type Auth0ConfigStorage

type Auth0ConfigStorage struct {
	Driver string `json:"driver"`
	Dsn    string `json:"dsn"`
}

func Auth0ConfigStorageParse

func Auth0ConfigStorageParse(json string) *Auth0ConfigStorage

type Auth0Response

type Auth0Response struct {
	Error        string                 `json:"error"`
	ItemId       string                 `json:"item_id"`
	ItemPayload  map[string]interface{} `json:"item_payload"`
	AccessToken  string                 `json:"access_token"`
	RefreshToken string                 `json:"refresh_token"`
	ConfirmToken string                 `json:"confirm_token"`
	OTP          string                 `json:"otp"`
}

func (*Auth0Response) GoString

func (instance *Auth0Response) GoString() string

func (*Auth0Response) String

func (instance *Auth0Response) String() string

Directories

Path Synopsis
jwt

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
JackTT - Gopher 🇻🇳