common

package
v0.7.4 Latest Latest
Warning

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

Go to latest
Published: Jun 19, 2026 License: MIT Imports: 13 Imported by: 0

README

Common Utilities Library

A collection of shared types, interfaces, and utility functions used throughout the engine and microservices.

Features

  • JWT Management: unified SessionClaims structure and token encoding/decoding.
  • Random Generation: helpers for generating secure random alphanumeric codes.
  • Base Interfaces: Standard interfaces for Repositories and UseCases.
  • Context Keys: Standardized keys for storing/retrieving values from context.Context.

API Reference

JWT & Session
SessionClaims

Standard claims structure for authenticated users.

type SessionClaims struct {
    UserID      string   `json:"user_id"`
    Username    string   `json:"username"`
    Permissions []string `json:"permission"`
    // ...other fields
}
TokenEncode / TokenDecode
// Create a token pair (access + refresh)
claims := &common.SessionClaims{UserID: "123", ...}
tokens, err := common.TokenEncode(claims)

// Decode a token string
claims, err := common.TokenDecode(tokenStr)
GetSession

Retrieve claims from context (usually set by middleware).

claims, err := common.GetSession(ctx)
if err == nil {
    fmt.Println(claims.UserID)
}
Random Generation
RandomCode

Generates cryptographically secure random strings.

// Generate 6-digit numeric code
code := common.RandomCode(6, common.RandomCodeNumeric) // "123456"

// Generate 12-char alphanumeric code with separators every 4 chars
// Output example: "ABCD-1234-EFGH"
code := common.RandomCode(12, common.RandomCodeAlphaNumeric, "-", 4)
Context Helpers
// Get Request ID from context
reqID := common.GetContextRequestID(ctx)

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CheckPassword

func CheckPassword(hashedPassword, plainPassword string) error

CheckPassword compares plain vs hashed

func GetContextRequestID

func GetContextRequestID(ctx context.Context) string

func GetContextSessionGeneric

func GetContextSessionGeneric[T any](ctx context.Context) *T

func HashPassword

func HashPassword(password string) (string, error)

HashPassword hashes the plain password

func NewCreatedBySnapshot added in v0.7.3

func NewCreatedBySnapshot(claims *SessionClaims) *json.RawMessage

NewCreatedBySnapshot marshals SessionClaims into a *json.RawMessage. Returns nil if claims is nil.

func RandomCode

func RandomCode(n int, option RandomCodeOption, separator ...any) string

RandomCode generates a random code with flexible separator/grouping. n: total character count (not including separators) option: character set type separator: []any{string separator, int groupSize} (optional; groupSize default 4)

func Rounder

func Rounder(num float64, intermed float64, precision int) float64

Rounder to round float number with some intermed and precision decimal e.g: 2.558--->2.6 Rounder(2.558, 0.5, 1)--->2.6 (intermed is a number that determine range of round ceil and round floor can accept negatif number from:https://play.golang.org/p/KNhgeuU5sT

func SetClaimFactory

func SetClaimFactory(factory func() jwt.Claims)

Optional setter, hanya dipakai oleh service yang butuh klaim custom

func ToPtr added in v0.7.4

func ToPtr[T any](v T) *T

ToPtr returns a pointer to v. Generic utility for any type.

func TokenDecode

func TokenDecode(tokenStr string) (jwt.Claims, error)

func UUIDPtr added in v0.7.4

func UUIDPtr(s string) *uuid.UUID

UUIDPtr parses s into *uuid.UUID. Returns nil if s is empty. Panics if s is non-empty but invalid (use MustParse semantics).

func ValidTokenPermission

func ValidTokenPermission(ctx context.Context, perm string) bool

Types

type BaseRepositoryInterface

type BaseRepositoryInterface[T any] interface {
	WithContext(ctx context.Context) BaseRepositoryInterface[T]
	Insert(entity *T) error
	FindByID(id any) (*T, error)
	Update(entity *T, fields ...string) error
	SoftDelete(id any) error
}

BaseRepositoryInterface defines common repository behaviors for all datastores. Only includes basic CRUD operations that are truly common across all datastores.

type BaseUsecase

type BaseUsecase[T any] struct {
	Repo    BaseRepositoryInterface[T]
	Context context.Context
}

func NewBaseUsecase

func NewBaseUsecase[T any](repo BaseRepositoryInterface[T]) *BaseUsecase[T]

func (*BaseUsecase[T]) Create

func (u *BaseUsecase[T]) Create(entity *T) error

func (*BaseUsecase[T]) Delete

func (u *BaseUsecase[T]) Delete(id any) error

func (*BaseUsecase[T]) GetByID

func (u *BaseUsecase[T]) GetByID(id any) (*T, error)

func (*BaseUsecase[T]) Update

func (u *BaseUsecase[T]) Update(entity *T, fields ...string) error

func (*BaseUsecase[T]) WithContext

func (u *BaseUsecase[T]) WithContext(ctx context.Context) *BaseUsecase[T]

type ContextKey

type ContextKey string
const (
	ContextRequestIDKey        ContextKey = "request_id"
	ContextUserKey             ContextKey = "user"
	ContextSessionKey          ContextKey = "session"
	ContextCorrelationIDKey    ContextKey = "correlation_id"
	ContextLocaleKey           ContextKey = "locale"
	ContextClientIPKey         ContextKey = "client_ip"
	ContextRequestStartTimeKey ContextKey = "request_start_time"
	ContextTraceIDKey          ContextKey = "trace_id"
	ContextSpanIDKey           ContextKey = "span_id"
)

type CreatedBySnapshot added in v0.7.3

type CreatedBySnapshot struct {
	ID             string `json:"id"`
	Name           string `json:"name"`
	Email          string `json:"email"`
	CompanyID      string `json:"company_id"`
	BranchID       string `json:"branch_id"`
	BranchRegionID string `json:"branch_region_id"`
	DepartmentID   string `json:"department_id"`
}

CreatedBySnapshot is the standard denormalized creator info embedded as JSONB in every table that tracks document creation. Populated once from SessionClaims at creation time — survives downstream user changes (rename, delete, transfer).

type QueryOption

type QueryOption struct {
	Limit      int64    `query:"per_page"`
	Page       int64    `query:"page"`
	Search     string   `query:"search"`
	OrderBy    string   `query:"order_by"`
	Offset     int64    `query:"-"`
	Orders     []string `query:"-"`
	Conditions []any    `query:"-"`
}

func (*QueryOption) BuildOption

func (r *QueryOption) BuildOption() *QueryOption

func (*QueryOption) GetLimit

func (r *QueryOption) GetLimit() int64

func (*QueryOption) GetOffset

func (r *QueryOption) GetOffset() int64

func (*QueryOption) GetOrders

func (r *QueryOption) GetOrders() []string

func (*QueryOption) GetPage

func (r *QueryOption) GetPage() int64

func (*QueryOption) GetSearch

func (r *QueryOption) GetSearch() string

type RandomCodeOption

type RandomCodeOption int

RandomCodeOption lets you customize the type of random code generated.

const (
	RandomCodeAlpha        RandomCodeOption = iota // Letters only (A-Z)
	RandomCodeNumeric                              // Numbers only (0-9)
	RandomCodeAlphaNumeric                         // Letters (A-Z) + numbers (0-9)
)

type SessionClaims

type SessionClaims struct {
	UserID         string   `json:"user_id"`
	Username       string   `json:"username"`
	DisplayName    string   `json:"display_name"`
	Email          string   `json:"email"`
	CompanyID      string   `json:"company_id"`
	BranchID       string   `json:"branch_id"`
	BranchRegionID string   `json:"branch_region_id"`
	DepartmentID   string   `json:"department_id"`
	RoleID         string   `json:"role_id"`
	Permissions    []string `json:"permission"`
	Type           string   `json:"type"`
	jwt.RegisteredClaims
}

func GetContextSession

func GetContextSession(ctx context.Context) *SessionClaims

type TokenPair

type TokenPair struct {
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token,omitempty"`
}

func TokenEncode

func TokenEncode(c jwt.Claims) (*TokenPair, error)

TokenEncode — otomatis set expiry (1 tahun) untuk semua struct turunan SessionClaims.

Jump to

Keyboard shortcuts

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