options.go 1.47 KiB
Newer Older
package jwtmdl

import (
	"time"

	"corelab.mkcl.org/MKCLOS/coredevelopmentplatform/corepkgv2/authmdl/sessionmdl"
)

type Options struct {
	Key       string
	UserID    string
	ClientIP  string
	Metadata  string
	Groups    []string
	ExpiresAt int64
	Session   sessionmdl.Session
}

type Option func(*Options)

Akshay Bharambe's avatar
Akshay Bharambe committed
// WithKey uses provided jwt key for token generation
func WithKey(k string) Option {
	return func(args *Options) {
		args.Key = k
	}
}

func WithUserID(uid string) Option {
	return func(args *Options) {
		args.UserID = uid
	}
}

Akshay Bharambe's avatar
Akshay Bharambe committed
// WithSession enables session validation on jwt decode. Required fields must not be empty.
func WithSession(sid, sessionFor string) Option {
	return func(args *Options) {
		args.Session = sessionmdl.Session{
			SessionId:  sid,
			SessionFor: sessionFor,
		}
	}
}

func WithClientIP(ip string) Option {
	return func(args *Options) {
		args.ClientIP = ip
	}
}

Akshay Bharambe's avatar
Akshay Bharambe committed
// WithMetaData embeds provided data in token. It is available againt `metadata` key. **It must be a valid json**
func WithMetaData(data string) Option {
	return func(args *Options) {
		args.Metadata = data
	}
}

func WithGroups(gs []string) Option {
	return func(args *Options) {
		args.Groups = gs
	}
}

Akshay Bharambe's avatar
Akshay Bharambe committed
// WithExpiration adds provided expiration to jwt token. Use `0` or ignore this option to generate a token witout expiry.
func WithExpiration(e time.Duration) Option {
	return func(args *Options) {
		if e == 0 {
			args.ExpiresAt = 0
			return
		}

		args.ExpiresAt = time.Now().Add(e).Unix()
	}
}