models

package
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Oct 4, 2026 License: Apache-2.0 Imports: 5 Imported by: 0

Documentation

Index

Constants

View Source
const (
	GroupTypeLocal    = "local"
	GroupTypeLDAP     = "ldap"
	GroupTypeExternal = "external"
)

Common group types.

View Source
const (
	GroupRoleMember = "member"
	GroupRoleAdmin  = "admin"
	GroupRoleOwner  = "owner"
)

Common group roles.

View Source
const (
	RoleUser  = "user"
	RoleGuest = "guest"
)

Additional role names (RoleAdmin and RoleAgent are defined in user.go).

View Source
const (
	PermissionViewTickets     = "view_tickets"
	PermissionCreateTickets   = "create_tickets"
	PermissionEditTickets     = "edit_tickets"
	PermissionDeleteTickets   = "delete_tickets"
	PermissionAssignTickets   = "assign_tickets"
	PermissionViewAllTickets  = "view_all_tickets"
	PermissionManageUsers     = "manage_users"
	PermissionManageQueues    = "manage_queues"
	PermissionManageSettings  = "manage_settings"
	PermissionViewReports     = "view_reports"
	PermissionManageTemplates = "manage_templates"
	PermissionManageWorkflows = "manage_workflows"
)

Common permissions.

View Source
const (
	SessionKeyUserID          = "UserID"
	SessionKeyUserLogin       = "UserLogin"
	SessionKeyUserType        = "UserType"
	SessionKeyUserTitle       = "UserTitle"
	SessionKeyUserFullname    = "UserFullname" // OTRS uses lowercase 'n'
	SessionKeyCreateTime      = "CreateTime"
	SessionKeyLastRequest     = "LastRequest"
	SessionKeyUserRemoteAddr  = "UserRemoteAddr"
	SessionKeyUserRemoteAgent = "UserRemoteUserAgent"
)

Session data keys (matching OTRS conventions).

View Source
const (
	UserTypeAgent    = "User"
	UserTypeCustomer = "Customer"
)

User type constants.

View Source
const DefaultRateLimit = 1000

DefaultRateLimit is the default rate limit for new tokens (requests per hour)

View Source
const TokenPrefix = "gf_"

TokenPrefix is the prefix for all API tokens

View Source
const TokenPrefixLength = 8

TokenPrefixLength is the length of the identifier prefix (after gf_)

View Source
const TokenRandomLength = 32

TokenRandomLength is the length of the random part of the token

Variables

View Source
var PermissionTypes = []string{
	"ro",
	"move_into",
	"create",
	"note",
	"owner",
	"priority",
	"rw",
}

Permission types (OTRS-compatible).

View Source
var ValidScopes = map[string]string{
	"*":              "Full access (inherits all user permissions)",
	"tickets:read":   "View tickets",
	"tickets:write":  "Create and update tickets",
	"tickets:delete": "Delete tickets",
	"articles:read":  "Read ticket articles",
	"articles:write": "Add articles and replies",
	"users:read":     "View user information",
	"queues:read":    "View queue information",
	"admin:*":        "Admin operations (agents only)",
}

ValidScopes defines the allowed scope values

Functions

func IsScopeAllowed

func IsScopeAllowed(scope string, userRole string, isCustomer bool) bool

IsScopeAllowed checks if a scope is allowed for a given user context

func IsValidScope

func IsValidScope(scope string) bool

IsValidScope checks if a scope is valid (exists in registry)

func RegisterScope

func RegisterScope(def *ScopeDefinition)

RegisterScope adds a scope to the registry (used by plugins)

func UnregisterScope

func UnregisterScope(scope string)

UnregisterScope removes a scope (used when plugins unload)

Types

type APIToken

type APIToken struct {
	ID            int64            `json:"id" db:"id"`
	UserID        int              `json:"user_id" db:"user_id"`
	UserType      APITokenUserType `json:"user_type" db:"user_type"`
	Name          string           `json:"name" db:"name"`
	Prefix        string           `json:"prefix" db:"prefix"`
	TokenHash     string           `json:"-" db:"token_hash"` // Never expose hash
	Scopes        []string         `json:"scopes,omitempty"`  // Parsed from JSON
	ScopesJSON    sql.NullString   `json:"-" db:"scopes"`     // Raw JSON from DB
	ExpiresAt     sql.NullTime     `json:"expires_at,omitempty" db:"expires_at"`
	LastUsedAt    sql.NullTime     `json:"last_used_at,omitempty" db:"last_used_at"`
	LastUsedIP    sql.NullString   `json:"last_used_ip,omitempty" db:"last_used_ip"`
	RateLimit     int              `json:"rate_limit" db:"rate_limit"`
	CreatedAt     time.Time        `json:"created_at" db:"created_at"`
	CreatedBy     sql.NullInt64    `json:"created_by,omitempty" db:"created_by"`
	RevokedAt     sql.NullTime     `json:"revoked_at,omitempty" db:"revoked_at"`
	RevokedBy     sql.NullInt64    `json:"revoked_by,omitempty" db:"revoked_by"`
	CustomerLogin string           `json:"customer_login,omitempty"` // For customer tokens: login from customer_user
}

APIToken represents a personal access token for API authentication

func (*APIToken) HasScope

func (t *APIToken) HasScope(scope string) bool

HasScope returns true if the token has the specified scope If scopes is nil/empty, token has all permissions (inherits from user)

func (*APIToken) IsActive

func (t *APIToken) IsActive() bool

IsActive returns true if the token is valid for use

func (*APIToken) IsExpired

func (t *APIToken) IsExpired() bool

IsExpired returns true if the token has expired

func (*APIToken) IsRevoked

func (t *APIToken) IsRevoked() bool

IsRevoked returns true if the token has been revoked

type APITokenCreateRequest

type APITokenCreateRequest struct {
	Name      string   `json:"name" binding:"required,min=1,max=100"`
	Scopes    []string `json:"scopes,omitempty"`
	ExpiresIn string   `json:"expires_in,omitempty"` // "30d", "90d", "1y", "never"
}

APITokenCreateRequest represents a request to create a new token

type APITokenCreateResponse

type APITokenCreateResponse struct {
	ID        int64     `json:"id"`
	Name      string    `json:"name"`
	Prefix    string    `json:"prefix"`
	Token     string    `json:"token"` // Full token - shown only at creation
	Scopes    []string  `json:"scopes,omitempty"`
	ExpiresAt *string   `json:"expires_at,omitempty"`
	CreatedAt time.Time `json:"created_at"`
	Warning   string    `json:"warning"`
}

APITokenCreateResponse includes the full token (shown only once)

type APITokenListItem

type APITokenListItem struct {
	ID         int64    `json:"id"`
	Name       string   `json:"name"`
	Prefix     string   `json:"prefix"`
	Scopes     []string `json:"scopes,omitempty"`
	ExpiresAt  *string  `json:"expires_at,omitempty"`
	LastUsedAt *string  `json:"last_used_at,omitempty"`
	CreatedAt  string   `json:"created_at"`
	IsActive   bool     `json:"is_active"`
}

APITokenListItem represents a token in list responses (no secret)

type APITokenUserType

type APITokenUserType string

APITokenUserType represents the type of user for API tokens

const (
	APITokenUserAgent    APITokenUserType = "agent"
	APITokenUserCustomer APITokenUserType = "customer"
)

type ChangePasswordRequest

type ChangePasswordRequest struct {
	OldPassword string `json:"old_password" binding:"required"`
	NewPassword string `json:"new_password" binding:"required,min=8"`
}

type DBGroupRole

type DBGroupRole struct {
	RoleID          int       `json:"role_id"`
	GroupID         int       `json:"group_id"`
	PermissionKey   string    `json:"permission_key"`
	PermissionValue int       `json:"permission_value"`
	CreateTime      time.Time `json:"create_time"`
	CreateBy        int       `json:"create_by"`
	ChangeTime      time.Time `json:"change_time"`
	ChangeBy        int       `json:"change_by"`
}

Maps to the `group_role` table.

type DBRole

type DBRole struct {
	ID         int       `json:"id"`
	Name       string    `json:"name"`
	Comments   string    `json:"comments"`
	ValidID    int       `json:"valid_id"`
	CreateTime time.Time `json:"create_time"`
	CreateBy   int       `json:"create_by"`
	ChangeTime time.Time `json:"change_time"`
	ChangeBy   int       `json:"change_by"`
}

Maps to the `roles` table.

func (*DBRole) IsValid

func (r *DBRole) IsValid() bool

IsValid returns true if the role is active (valid_id = 1).

type DBRoleUser

type DBRoleUser struct {
	UserID     int       `json:"user_id"`
	RoleID     int       `json:"role_id"`
	CreateTime time.Time `json:"create_time"`
	CreateBy   int       `json:"create_by"`
	ChangeTime time.Time `json:"change_time"`
	ChangeBy   int       `json:"change_by"`
}

Maps to the `role_user` table.

type Group

type Group struct {
	// OTRS-compatible fields (required for database operations)
	ID         interface{} `json:"id"` // Can be int or string depending on context
	Name       string      `json:"name"`
	Comments   string      `json:"comments,omitempty"`
	ValidID    int         `json:"valid_id,omitempty"`
	CreateTime time.Time   `json:"create_time,omitempty"`
	CreateBy   int         `json:"create_by,omitempty"`
	ChangeTime time.Time   `json:"change_time,omitempty"`
	ChangeBy   int         `json:"change_by,omitempty"`

	// Additional fields for LDAP/extended functionality
	Description string            `json:"description,omitempty"`
	Type        string            `json:"type,omitempty"`    // ldap, local, external
	DN          string            `json:"dn,omitempty"`      // LDAP Distinguished Name
	Members     []string          `json:"members,omitempty"` // User IDs
	Permissions []string          `json:"permissions,omitempty"`
	IsActive    bool              `json:"is_active,omitempty"`
	IsSystem    bool              `json:"is_system,omitempty"`
	Metadata    map[string]string `json:"metadata,omitempty"`
	CreatedAt   time.Time         `json:"created_at,omitempty"`
	UpdatedAt   time.Time         `json:"updated_at,omitempty"`
}

Group represents a user group in the system.

type GroupMembership

type GroupMembership struct {
	GroupID string    `json:"group_id"`
	UserID  string    `json:"user_id"`
	Role    string    `json:"role,omitempty"` // member, admin, etc.
	AddedBy string    `json:"added_by,omitempty"`
	AddedAt time.Time `json:"added_at"`
}

GroupMembership represents a user's membership in a group.

type IdentityProvider

type IdentityProvider struct {
	ID              uint      `json:"id"`
	OrgID           *uint     `json:"org_id,omitempty"`
	Name            string    `json:"name"`
	ProviderType    string    `json:"provider_type"`
	ClientID        string    `json:"client_id"`
	ClientSecret    string    `json:"-"`
	DiscoveryURL    string    `json:"discovery_url"`
	SigningCert     string    `json:"signing_cert"`
	PrivateKey      string    `json:"-"`
	EntityID        string    `json:"entity_id"`
	ACSURL          string    `json:"acs_url"`
	IdPMetadataXML  string    `json:"idp_metadata_xml"`
	Scopes          string    `json:"scopes"`
	UserClaimEmail  string    `json:"user_claim_email"`
	UserClaimName   string    `json:"user_claim_name"`
	UserClaimGroups string    `json:"user_claim_groups"`
	Enabled         bool      `json:"enabled"`
	AutoProvision   bool      `json:"auto_provision"`
	UserTable       string    `json:"user_table"`
	AutoAddToGroup  string    `json:"auto_add_to_group"`
	CreateTime      time.Time `json:"create_time"`
	CreateBy        uint      `json:"create_by"`
	ChangeTime      time.Time `json:"change_time"`
	ChangeBy        uint      `json:"change_by"`
}

func (*IdentityProvider) GetProviderType

func (m *IdentityProvider) GetProviderType() string

func (*IdentityProvider) IsActive

func (m *IdentityProvider) IsActive() bool

type IdentityProviderOrg

type IdentityProviderOrg struct {
	ProviderID uint `json:"provider_id"`
	OrgID      uint `json:"org_id"`
}

type LoginRequest

type LoginRequest struct {
	Email    string `json:"email" binding:"required,email"`
	Password string `json:"password" binding:"required,min=6"`
}

type LoginResponse

type LoginResponse struct {
	Token        string    `json:"token"`
	RefreshToken string    `json:"refresh_token"`
	User         *User     `json:"user"`
	ExpiresAt    time.Time `json:"expires_at"`
}

type LookupItem

type LookupItem struct {
	ID     int    `json:"id"`
	Value  string `json:"value"`
	Label  string `json:"label"`
	Order  int    `json:"order"`
	Active bool   `json:"active"`
}

LookupItem represents a generic lookup value (priority, type, status, etc.)

type Permission

type Permission struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description"`
	Category    string `json:"category"`
	IsSystem    bool   `json:"is_system"`
}

Permission represents a system permission.

type Role

type Role struct {
	ID          string            `json:"id"`
	Name        string            `json:"name"`
	Description string            `json:"description"`
	Permissions []string          `json:"permissions"`
	IsSystem    bool              `json:"is_system"`
	IsActive    bool              `json:"is_active"`
	Metadata    map[string]string `json:"metadata,omitempty"`
	CreatedAt   time.Time         `json:"created_at"`
	UpdatedAt   time.Time         `json:"updated_at"`
}

Role represents a user role in the system.

type ScopeDefinition

type ScopeDefinition struct {
	Scope       string `json:"scope"`
	Description string `json:"description"`
	Category    string `json:"category"`     // e.g., "core", "plugin:myplugin"
	RequireRole string `json:"require_role"` // e.g., "Admin", "Agent", "" (any)
	AgentOnly   bool   `json:"agent_only"`   // If true, not available to customers
}

ScopeDefinition defines an API token scope

func GetAllScopes

func GetAllScopes() []*ScopeDefinition

GetAllScopes returns all registered scopes (for admin/debugging)

func GetAvailableScopes

func GetAvailableScopes(userRole string, isCustomer bool) []*ScopeDefinition

GetAvailableScopes returns scopes available for a given user context

type ScopeRegistry

type ScopeRegistry struct {
	// contains filtered or unexported fields
}

ScopeRegistry manages available API token scopes

type Session

type Session struct {
	SessionID    string    `json:"session_id"`
	UserID       int       `json:"user_id"`
	UserLogin    string    `json:"user_login"`
	UserType     string    `json:"user_type"` // "User" (agent) or "Customer"
	UserTitle    string    `json:"user_title"`
	UserFullName string    `json:"user_full_name"`
	CreateTime   time.Time `json:"create_time"`
	LastRequest  time.Time `json:"last_request"`
	RemoteAddr   string    `json:"remote_addr"`
	UserAgent    string    `json:"user_agent"`
}

Session represents an active user session. The OTRS sessions table uses a key-value store format with columns: session_id, data_key, data_value, serialized

type SessionData

type SessionData struct {
	SessionID  string `json:"session_id"`
	DataKey    string `json:"data_key"`
	DataValue  string `json:"data_value"`
	Serialized int    `json:"serialized"` // 0=plain text, 1=serialized
}

SessionData represents a key-value pair in the sessions table.

type SystemMaintenance

type SystemMaintenance struct {
	ID               int       `json:"id"`
	StartDate        int64     `json:"start_date"`         // Unix epoch timestamp
	StopDate         int64     `json:"stop_date"`          // Unix epoch timestamp
	Comments         string    `json:"comments"`           // Admin reference/description
	LoginMessage     *string   `json:"login_message"`      // Message shown on login page
	ShowLoginMessage int       `json:"show_login_message"` // 0 or 1
	NotifyMessage    *string   `json:"notify_message"`     // Notification banner message
	ValidID          int       `json:"valid_id"`           // 1=valid, 2=invalid
	CreateTime       time.Time `json:"create_time"`
	CreateBy         int       `json:"create_by"`
	ChangeTime       time.Time `json:"change_time"`
	ChangeBy         int       `json:"change_by"`
}

SystemMaintenance represents a scheduled system maintenance window. This maps directly to the OTRS system_maintenance table.

func (*SystemMaintenance) Duration

func (m *SystemMaintenance) Duration() int

Duration returns the maintenance duration in minutes.

func (*SystemMaintenance) GetLoginMessage

func (m *SystemMaintenance) GetLoginMessage() string

GetLoginMessage returns the login message or empty string if nil.

func (*SystemMaintenance) GetNotifyMessage

func (m *SystemMaintenance) GetNotifyMessage() string

GetNotifyMessage returns the notify message or empty string if nil.

func (*SystemMaintenance) IsCurrentlyActive

func (m *SystemMaintenance) IsCurrentlyActive() bool

IsCurrentlyActive returns true if the maintenance is currently active.

func (*SystemMaintenance) IsPast

func (m *SystemMaintenance) IsPast() bool

IsPast returns true if the maintenance window has ended.

func (*SystemMaintenance) IsUpcoming

func (m *SystemMaintenance) IsUpcoming(withinMinutes int) bool

IsUpcoming returns true if the maintenance starts within the given minutes.

func (*SystemMaintenance) IsValid

func (m *SystemMaintenance) IsValid() bool

IsValid returns true if the maintenance record is valid.

func (*SystemMaintenance) ShowsLoginMessage

func (m *SystemMaintenance) ShowsLoginMessage() bool

ShowsLoginMessage returns true if the login message should be displayed.

func (*SystemMaintenance) StartDateFormatted

func (m *SystemMaintenance) StartDateFormatted() string

StartDateFormatted returns the start date as a formatted string for display.

func (*SystemMaintenance) StartDateInput

func (m *SystemMaintenance) StartDateInput() string

StartDateInput returns the start date formatted for HTML datetime-local input.

func (*SystemMaintenance) StopDateFormatted

func (m *SystemMaintenance) StopDateFormatted() string

StopDateFormatted returns the stop date as a formatted string for display.

func (*SystemMaintenance) StopDateInput

func (m *SystemMaintenance) StopDateInput() string

StopDateInput returns the stop date formatted for HTML datetime-local input.

type User

type User struct {
	ID               uint       `json:"id" db:"id"`
	Login            string     `json:"login" db:"login"`
	Email            string     `json:"email"`     // Not in users table, use login as email
	Password         string     `json:"-" db:"pw"` // Never expose in JSON
	Title            string     `json:"title" db:"title"`
	FirstName        string     `json:"first_name" db:"first_name"`
	LastName         string     `json:"last_name" db:"last_name"`
	ValidID          int        `json:"valid_id" db:"valid_id"` // OTRS valid field (1=valid, 2=invalid, 3=invalid-temporarily)
	CreateTime       time.Time  `json:"create_time" db:"create_time"`
	CreateBy         int        `json:"create_by" db:"create_by"`
	ChangeTime       time.Time  `json:"change_time" db:"change_time"`
	ChangeBy         int        `json:"change_by" db:"change_by"`
	Role             string     `json:"role"`                        // Admin, Agent, Customer
	IsInAdminGroup   bool       `json:"is_in_admin_group,omitempty"` // User is in admin group (for nav display)
	TenantID         uint       `json:"tenant_id,omitempty"`
	LastLogin        *time.Time `json:"last_login,omitempty"`
	FailedLoginCount int        `json:"-"`
	LockedUntil      *time.Time `json:"-"`
	Groups           []string   `json:"groups,omitempty"` // Group names for the user
}

func (*User) IncrementFailedLogin

func (u *User) IncrementFailedLogin()

func (*User) IsActive

func (u *User) IsActive() bool

IsActive returns true if the user is active (valid_id = 1 in OTRS).

func (*User) IsLocked

func (u *User) IsLocked() bool

func (*User) LockAccount

func (u *User) LockAccount(duration time.Duration)

func (*User) ResetFailedLogin

func (u *User) ResetFailedLogin()

func (*User) UnlockAccount

func (u *User) UnlockAccount()

type UserRole

type UserRole string
const (
	RoleAdmin    UserRole = "Admin"
	RoleAgent    UserRole = "Agent"
	RoleCustomer UserRole = "Customer"
)

Jump to

Keyboard shortcuts

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