token

package
v1.21.0 Latest Latest
Warning

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

Go to latest
Published: Jul 23, 2022 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

Package token wraps jwt-go library and provides higher level abstraction to work with JWT.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func HashID

func HashID(h hash.Hash, val string) string

HashID tries to hash val with hash.Hash and fallback to crc if needed

func SetUserDataToCtx

func SetUserDataToCtx(ctx context.Context, user UserData) context.Context

func SetUserInfo

func SetUserInfo(r *http.Request, user User) *http.Request

SetUserInfo sets user into request context

func SetUserToCtx

func SetUserToCtx(ctx context.Context, user User) context.Context

Types

type Audience

type Audience interface {
	Get() ([]string, error)
}

Audience defines interface returning list of allowed audiences

type AudienceFunc

type AudienceFunc func() ([]string, error)

AudienceFunc type is an adapter to allow the use of ordinary functions as Audience.

func (AudienceFunc) Get

func (f AudienceFunc) Get() ([]string, error)

Get calls f()

type Claims

type Claims struct {
	jwt.StandardClaims
	User        *User      `json:"user,omitempty"` // user info
	SessionOnly bool       `json:"sess_only,omitempty"`
	Handshake   *Handshake `json:"handshake,omitempty"` // used for oauth handshake
	NoAva       bool       `json:"no-ava,omitempty"`    // disable avatar, always use identicon
}

Claims stores user info for token and state & from from login

func (Claims) String

func (c Claims) String() string

type ClaimsUpdFunc

type ClaimsUpdFunc func(claims Claims) Claims

ClaimsUpdFunc type is an adapter to allow the use of ordinary functions as ClaimsUpdater. If f is a function with the appropriate signature, ClaimsUpdFunc(f) is a Handler that calls f.

func (ClaimsUpdFunc) Update

func (f ClaimsUpdFunc) Update(claims Claims) Claims

Update calls f(id)

type ClaimsUpdater

type ClaimsUpdater interface {
	Update(claims Claims) Claims
}

ClaimsUpdater defines interface adding extras to claims

type Collection

type Collection struct {
	Type  string                 `json:"type"`
	Items map[string]interface{} `json:"items"`
}

func NewCollection

func NewCollection(name string) *Collection

func (*Collection) Add

func (c *Collection) Add(name string, val interface{})

type Collections

type Collections map[string]*Collection

func NewCollections added in v1.21.0

func NewCollections() Collections

type Handshake

type Handshake struct {
	State string `json:"state,omitempty"`
	From  string `json:"from,omitempty"`
	ID    string `json:"id,omitempty"`
}

Handshake used for oauth handshake

type Opts

type Opts struct {
	SecretReader   Secret
	ClaimsUpd      ClaimsUpdater
	SecureCookies  bool
	TokenDuration  time.Duration
	CookieDuration time.Duration
	DisableXSRF    bool
	DisableIAT     bool // disable IssuedAt claim
	// optional (custom) names for cookies and headers
	JWTCookieName   string
	JWTCookieDomain string
	JWTHeaderKey    string
	XSRFCookieName  string
	XSRFHeaderKey   string
	JWTQuery        string
	AudienceReader  Audience      // allowed aud values
	Issuer          string        // optional value for iss claim, usually application name
	AudSecrets      bool          // uses different secret for differed auds. important: adds pre-parsing of unverified token
	SendJWTHeader   bool          // if enabled send JWT as a header instead of cookie
	SameSite        http.SameSite // define a cookie attribute making it impossible for the browser to send this cookie cross-site
}

Opts holds constructor params

type Secret

type Secret interface {
	Get(aud string) (string, error) // aud matching is optional. Implementation may decide if supported or ignored
}

Secret defines interface returning secret key for given id (aud)

type SecretFunc

type SecretFunc func(aud string) (string, error)

SecretFunc type is an adapter to allow the use of ordinary functions as Secret. If f is a function with the appropriate signature, SecretFunc(f) is a Handler that calls f.

func (SecretFunc) Get

func (f SecretFunc) Get(aud string) (string, error)

Get calls f()

type Service

type Service struct {
	Opts
}

Service wraps jwt operations supports both header and cookie tokens

func NewService

func NewService(opts Opts) *Service

NewService makes JWT service

func (*Service) Get

func (j *Service) Get(r *http.Request) (Claims, string, error)

Get token from url, header or cookie if cookie used, verify xsrf token to match

func (*Service) IsExpired

func (j *Service) IsExpired(claims Claims) bool

IsExpired returns true if claims expired

func (*Service) Parse

func (j *Service) Parse(tokenString string) (Claims, error)

Parse token string and verify. Not checking for expiration

func (*Service) Reset

func (j *Service) Reset(w http.ResponseWriter)

Reset token's cookies

func (*Service) Set

func (j *Service) Set(w http.ResponseWriter, claims Claims) (Claims, error)

Set creates token cookie with xsrf cookie and put it to ResponseWriter accepts claims and sets expiration if none defined. permanent flag means long-living cookie, false makes it session only.

func (*Service) Token

func (j *Service) Token(claims Claims) (string, error)

Token makes token with claims

type User

type User struct {
	// set by service
	Name     string `json:"name"`
	ID       string `json:"id"`
	Picture  string `json:"picture"`
	Audience string `json:"aud,omitempty"`

	// set by client
	IP         string                 `json:"ip,omitempty"`
	Email      string                 `json:"email,omitempty"`
	Attributes map[string]interface{} `json:"attrs,omitempty"`
	Role       string                 `json:"role,omitempty"`
}

User is the basic part of oauth data provided by service

func GetUserFromCtx

func GetUserFromCtx(ctx context.Context) (user User, err error)

func GetUserInfo

func GetUserInfo(r *http.Request) (user User, err error)

GetUserInfo returns user info from request context

func MustGetUserInfo

func MustGetUserInfo(r *http.Request) User

MustGetUserInfo gets user info and panics if can't extract it from the request. should be called from authenticated controllers only

func (*User) BoolAttr

func (u *User) BoolAttr(key string) bool

BoolAttr gets boolean attribute

func (*User) GetRole

func (u *User) GetRole() string

GetRole gets user role

func (*User) IsAdmin

func (u *User) IsAdmin() bool

IsAdmin is a shortcut to get admin attribute

func (*User) IsPaidSub

func (u *User) IsPaidSub() bool

IsPaidSub is a shortcut to get "paidSubscriberAttr" attribute

func (*User) SetAdmin

func (u *User) SetAdmin(val bool)

SetAdmin is a shortcut to set "admin" attribute

func (*User) SetBoolAttr

func (u *User) SetBoolAttr(key string, val bool)

SetBoolAttr sets boolean attribute

func (*User) SetPaidSub

func (u *User) SetPaidSub(val bool)

SetPaidSub is a shortcut to set "paidSubscriberAttr" attribute

func (*User) SetRole

func (u *User) SetRole(role string)

SetRole sets user role for RBAC

func (*User) SetSliceAttr

func (u *User) SetSliceAttr(key string, val []string)

SetSliceAttr sets slice attribute for given key

func (*User) SetStrAttr

func (u *User) SetStrAttr(key, val string)

SetStrAttr sets string attribute

func (*User) SliceAttr

func (u *User) SliceAttr(key string) []string

SliceAttr gets slice attribute

func (*User) StrAttr

func (u *User) StrAttr(key string) string

StrAttr gets string attribute

type UserData

type UserData struct {
	User        User                   `json:"user"`
	Social      string                 `json:"social"`
	Collections Collections            `json:"collections"`
	Raw         map[string]interface{} `json:"raw"`
}

func GetUserDataFromCtx

func GetUserDataFromCtx(ctx context.Context) (user UserData, err error)

func (*UserData) AddCollection

func (ud *UserData) AddCollection(collection Collection)

func (*UserData) CreateCollection

func (ud *UserData) CreateCollection(name string) *Collection

func (*UserData) CreateEmailCollection

func (ud *UserData) CreateEmailCollection() *Collection

func (*UserData) GetCollection

func (ud *UserData) GetCollection(name string) *Collection

func (*UserData) SetRaw

func (ud *UserData) SetRaw(key string, val interface{})

type Validator

type Validator interface {
	Validate(token string, claims Claims) bool
}

Validator defines interface to accept o reject claims with consumer defined logic It works with valid token and allows to reject some, based on token match or user's fields

type ValidatorFunc

type ValidatorFunc func(token string, claims Claims) bool

ValidatorFunc type is an adapter to allow the use of ordinary functions as Validator. If f is a function with the appropriate signature, ValidatorFunc(f) is a Validator that calls f.

func (ValidatorFunc) Validate

func (f ValidatorFunc) Validate(token string, claims Claims) bool

Validate calls f(id)

Jump to

Keyboard shortcuts

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