types

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Jan 21, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package types provides common types used by juango applications.

Index

Constants

View Source
const (
	// User actions
	ActionUserCreated          = "user.created"
	ActionUserUpdated          = "user.updated"
	ActionUserDeactivated      = "user.deactivated"
	ActionUserReactivated      = "user.reactivated"
	ActionUserLoggedIn         = "user.logged_in"
	ActionUserLoggedOut        = "user.logged_out"
	ActionAdminModeEnabled     = "user.admin_mode_enabled"
	ActionAdminModeDisabled    = "user.admin_mode_disabled"
	ActionAdminModeExpired     = "user.admin_mode_expired"
	ActionImpersonationStarted = "user.impersonation_started"
	ActionImpersonationStopped = "user.impersonation_stopped"
	ActionImpersonationExpired = "user.impersonation_expired"

	// Task actions
	ActionTaskCreated   = "task.created"
	ActionTaskStarted   = "task.started"
	ActionTaskCompleted = "task.completed"
	ActionTaskFailed    = "task.failed"
)

Audit log action constants.

View Source
const (
	ResourceTypeUser = "user"
	ResourceTypeTask = "task"
)

Resource types for audit logging.

Variables

View Source
var (
	ErrNotFound       = errors.New("not found")
	ErrUnauthorized   = errors.New("unauthorized")
	ErrForbidden      = errors.New("forbidden")
	ErrBadRequest     = errors.New("bad request")
	ErrInternalServer = errors.New("internal server error")
)

Common errors.

Functions

func CleanIdentifier

func CleanIdentifier(identifier string) string

CleanIdentifier cleans a potentially malformed identifier by removing double slashes while preserving protocol specifications like http://.

func WriteHTTPError

func WriteHTTPError(w http.ResponseWriter, err error)

WriteHTTPError writes an HTTPError to the response writer.

Types

type AdminModeDisableResponse

type AdminModeDisableResponse struct {
	Message string `json:"message"`
}

AdminModeDisableResponse is the response for disabling admin mode.

type AdminModeEnableResponse

type AdminModeEnableResponse struct {
	Message string          `json:"message"`
	State   *AdminModeState `json:"state"`
}

AdminModeEnableResponse is the response for enabling admin mode.

type AdminModeRequest

type AdminModeRequest struct {
	Reason string `json:"reason"`
}

AdminModeRequest is the request body for enabling admin mode.

type AdminModeState

type AdminModeState struct {
	Enabled   bool      `json:"enabled"`
	Since     time.Time `json:"since"`
	Reason    string    `json:"reason"`
	IPAddress string    `json:"ip_address"`
}

AdminModeState represents the current state of admin mode for a user session.

func (*AdminModeState) Duration

func (a *AdminModeState) Duration() time.Duration

Duration returns how long admin mode has been active.

func (*AdminModeState) IsExpired

func (a *AdminModeState) IsExpired(timeout time.Duration) bool

IsExpired checks if the admin mode session has expired.

type AdminModeStatusResponse

type AdminModeStatusResponse struct {
	IsAdmin   bool            `json:"is_admin"`
	AdminMode *AdminModeState `json:"admin_mode,omitempty"`
}

AdminModeStatusResponse is the response for the admin mode status endpoint.

type AuditLog

type AuditLog struct {
	ID           int64          `db:"id" json:"id"`
	Timestamp    time.Time      `db:"timestamp" json:"timestamp"`
	ActorUserID  NullUUID       `db:"actor_user_id" json:"actor_user_id"`
	Action       string         `db:"action" json:"action"`
	ResourceType string         `db:"resource_type" json:"resource_type"`
	ResourceID   string         `db:"resource_id" json:"resource_id"`
	Changes      JSONMap        `db:"changes" json:"changes"`
	IPAddress    sql.NullString `db:"ip_address" json:"ip_address,omitempty"`
	UserAgent    sql.NullString `db:"user_agent" json:"user_agent,omitempty"`
}

AuditLog represents a log entry for tracking changes in the system.

func NewAuditLog

func NewAuditLog(actorUserID *NullUUID, action, resourceType, resourceID string) *AuditLog

NewAuditLog creates a new audit log entry with common fields.

func (*AuditLog) AddDetail

func (a *AuditLog) AddDetail(key string, value interface{}) *AuditLog

AddDetail adds a key-value detail to the changes map.

func (*AuditLog) WithBeforeAfter

func (a *AuditLog) WithBeforeAfter(before, after interface{}) *AuditLog

WithBeforeAfter adds before/after state to the audit log.

func (*AuditLog) WithChanges

func (a *AuditLog) WithChanges(changes map[string]interface{}) *AuditLog

WithChanges adds change details to the audit log.

func (*AuditLog) WithIPAddress

func (a *AuditLog) WithIPAddress(ip string) *AuditLog

WithIPAddress adds IP address to the audit log.

func (*AuditLog) WithUserAgent

func (a *AuditLog) WithUserAgent(ua string) *AuditLog

WithUserAgent adds user agent to the audit log.

type FlexibleBoolean

type FlexibleBoolean bool

FlexibleBoolean handles JSON where boolean values may be strings. Some providers (like JumpCloud) return "true"/"false" as strings.

func (*FlexibleBoolean) UnmarshalJSON

func (bit *FlexibleBoolean) UnmarshalJSON(data []byte) error

type HTTPError

type HTTPError struct {
	Code int    // HTTP response code to send to client; 0 means 500
	Msg  string // Response body to send to client
	Err  error  // Detailed error to log on the server
}

HTTPError represents an error that is surfaced to the user via HTTP.

func HTTPErrorFromStatus

func HTTPErrorFromStatus(code int, err error) HTTPError

HTTPErrorFromStatus creates an HTTPError from an HTTP status code.

func NewHTTPError

func NewHTTPError(code int, msg string, err error) HTTPError

NewHTTPError creates a new HTTPError.

func (HTTPError) Error

func (e HTTPError) Error() string

func (HTTPError) Unwrap

func (e HTTPError) Unwrap() error

type ImpersonationStartRequest

type ImpersonationStartRequest struct {
	TargetUserID string `json:"target_user_id"`
	Reason       string `json:"reason"`
}

ImpersonationStartRequest is the request body for starting impersonation.

type ImpersonationStartResponse

type ImpersonationStartResponse struct {
	Message       string              `json:"message"`
	Impersonation *ImpersonationState `json:"impersonation"`
}

ImpersonationStartResponse is the response for starting impersonation.

type ImpersonationState

type ImpersonationState struct {
	Enabled         bool      `json:"enabled"`
	Since           time.Time `json:"since"`
	Reason          string    `json:"reason"`
	TargetUserID    uuid.UUID `json:"target_user_id"`
	TargetUserEmail string    `json:"target_user_email"`
	TargetUserName  string    `json:"target_user_name"`
	OriginalAdminID uuid.UUID `json:"original_admin_id"`
	IPAddress       string    `json:"ip_address"`
}

ImpersonationState represents the current state of user impersonation for an admin session.

func (*ImpersonationState) Duration

func (i *ImpersonationState) Duration() time.Duration

Duration returns how long impersonation has been active.

func (*ImpersonationState) IsExpired

func (i *ImpersonationState) IsExpired(timeout time.Duration) bool

IsExpired checks if the impersonation session has expired.

type ImpersonationStatusResponse

type ImpersonationStatusResponse struct {
	Active        bool                `json:"active"`
	Impersonation *ImpersonationState `json:"impersonation,omitempty"`
}

ImpersonationStatusResponse is the response for the impersonation status endpoint.

type ImpersonationStopResponse

type ImpersonationStopResponse struct {
	Message string `json:"message"`
}

ImpersonationStopResponse is the response for stopping impersonation.

type JSONMap

type JSONMap map[string]interface{}

JSONMap represents a JSON object (map) in the database. Used for flexible key-value storage like audit log changes.

func (*JSONMap) Scan

func (j *JSONMap) Scan(val interface{}) error

Scan implements the sql.Scanner interface for reading from database.

func (JSONMap) Value

func (j JSONMap) Value() (driver.Value, error)

Value implements the driver.Valuer interface for writing to database.

type Notification

type Notification struct {
	ID        uuid.UUID        `db:"id" json:"id"`
	UserID    uuid.UUID        `db:"user_id" json:"user_id"`
	Type      NotificationType `db:"type" json:"type"`
	Title     string           `db:"title" json:"title"`
	Message   string           `db:"message" json:"message"`
	Link      sql.NullString   `db:"link" json:"link,omitempty"`
	Read      bool             `db:"read" json:"read"`
	ReadAt    sql.NullTime     `db:"read_at" json:"read_at,omitempty"`
	CreatedAt time.Time        `db:"created_at" json:"created_at"`
}

Notification represents a user notification.

type NotificationCreateRequest

type NotificationCreateRequest struct {
	UserID  uuid.UUID        `json:"user_id"`
	Type    NotificationType `json:"type"`
	Title   string           `json:"title"`
	Message string           `json:"message"`
	Link    string           `json:"link,omitempty"`
}

NotificationCreateRequest is the request body for creating a notification.

type NotificationListResponse

type NotificationListResponse struct {
	Notifications []Notification `json:"notifications"`
	UnreadCount   int            `json:"unread_count"`
}

NotificationListResponse is the response for listing notifications.

type NotificationType

type NotificationType string

NotificationType represents the type of notification.

const (
	NotificationTypeInfo    NotificationType = "info"
	NotificationTypeWarning NotificationType = "warning"
	NotificationTypeError   NotificationType = "error"
	NotificationTypeSuccess NotificationType = "success"
)

type NullUUID

type NullUUID struct {
	UUID  uuid.UUID
	Valid bool
}

NullUUID represents a UUID that may be null.

func (*NullUUID) Scan

func (n *NullUUID) Scan(value interface{}) error

Scan implements the sql.Scanner interface.

func (NullUUID) Value

func (n NullUUID) Value() (driver.Value, error)

Value implements the driver.Valuer interface.

type OIDCClaims

type OIDCClaims struct {
	// Sub is the user's unique identifier at the provider.
	Sub string `json:"sub"`
	Iss string `json:"iss"`

	// Name is the user's full name.
	Name              string          `json:"name,omitempty"`
	Groups            []string        `json:"groups,omitempty"`
	Email             string          `json:"email,omitempty"`
	EmailVerified     FlexibleBoolean `json:"email_verified,omitempty"`
	ProfilePictureURL string          `json:"picture,omitempty"`
	Username          string          `json:"preferred_username,omitempty"`
}

OIDCClaims represents claims from an OIDC ID token.

func (*OIDCClaims) Identifier

func (c *OIDCClaims) Identifier() string

Identifier returns a unique identifier string combining the Iss and Sub claims.

type OIDCConfig

type OIDCConfig struct {
	Issuer       string
	ClientID     string
	ClientSecret string
	Scopes       []string
	ExtraParams  map[string]string
	Expiry       time.Duration
}

OIDCConfig holds OIDC provider configuration.

type OIDCUserInfo

type OIDCUserInfo struct {
	Sub               string          `json:"sub"`
	Name              string          `json:"name"`
	GivenName         string          `json:"given_name"`
	FamilyName        string          `json:"family_name"`
	PreferredUsername string          `json:"preferred_username"`
	Email             string          `json:"email"`
	EmailVerified     FlexibleBoolean `json:"email_verified,omitempty"`
	Picture           string          `json:"picture"`
}

OIDCUserInfo represents additional user info from the userinfo endpoint.

type SessionResponse

type SessionResponse struct {
	Authenticated bool                `json:"authenticated"`
	User          *User               `json:"user,omitempty"`
	Reason        string              `json:"reason,omitempty"`
	Impersonation *ImpersonationState `json:"impersonation,omitempty"`
}

SessionResponse represents the response from the session check API.

type StringArray

type StringArray []string

StringArray represents a JSON array of strings in the database.

func (*StringArray) Scan

func (s *StringArray) Scan(val interface{}) error

Scan implements the sql.Scanner interface for reading from database.

func (StringArray) Value

func (s StringArray) Value() (driver.Value, error)

Value implements the driver.Valuer interface for writing to database.

type UnreadCountResponse

type UnreadCountResponse struct {
	Count int `json:"count"`
}

UnreadCountResponse is the response for getting unread notification count.

type User

type User struct {
	ID                 uuid.UUID      `db:"id" json:"id"`
	Email              string         `db:"email" json:"email"`
	Name               string         `db:"name" json:"name"`
	LastLogin          *time.Time     `db:"last_login" json:"last_login,omitempty"`
	ProviderIdentifier sql.NullString `db:"provider_identifier" json:"-"`
	DisplayName        string         `db:"display_name" json:"display_name"`
	ProfilePicURL      string         `db:"profile_pic_url" json:"profile_pic_url"`
	IsAdmin            bool           `db:"is_admin" json:"is_admin"`

	CreatedAt  time.Time    `db:"created_at" json:"created_at"`
	ModifiedAt time.Time    `db:"modified_at" json:"modified_at"`
	DeletedAt  sql.NullTime `db:"deleted_at" json:"deleted_at,omitempty"`
}

User represents an application user.

func (*User) FromClaim

func (u *User) FromClaim(claims *OIDCClaims)

FromClaim updates a User from OIDC claims. All fields will be updated, except for the ID.

func (*User) IsActive

func (u *User) IsActive() bool

IsActive returns true if the user is not soft-deleted.

Jump to

Keyboard shortcuts

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