auth

package
v0.0.9 Latest Latest
Warning

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

Go to latest
Published: Apr 3, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

Package auth provides authentication and authorization for XxSql.

Index

Constants

This section is empty.

Variables

RolePermissions maps roles to their permissions.

Functions

This section is empty.

Types

type APIKey added in v0.0.5

type APIKey struct {
	ID          string     `json:"id"`          // Key identifier (e.g., "ak_abc123")
	Name        string     `json:"name"`        // Human-readable name
	KeyHash     string     `json:"key_hash"`    // SHA256 hash of the full key
	Username    string     `json:"username"`    // Owner username
	Permissions Permission `json:"permissions"` // Granted permissions
	CreatedAt   time.Time  `json:"created_at"`
	ExpiresAt   time.Time  `json:"expires_at"` // Zero means no expiration
	LastUsedAt  time.Time  `json:"last_used_at"`
	Enabled     bool       `json:"enabled"`
}

APIKey represents an API key for programmatic access.

func (*APIKey) HasPermission added in v0.0.5

func (k *APIKey) HasPermission(perm Permission) bool

HasPermission checks if the key has the given permission.

func (*APIKey) IsExpired added in v0.0.5

func (k *APIKey) IsExpired() bool

IsExpired checks if the API key is expired.

type APIKeyManager added in v0.0.5

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

APIKeyManager manages API keys.

func NewAPIKeyManager added in v0.0.5

func NewAPIKeyManager(dataDir string) *APIKeyManager

NewAPIKeyManager creates a new API key manager.

func (*APIKeyManager) DeleteUserKeys added in v0.0.5

func (m *APIKeyManager) DeleteUserKeys(username string)

DeleteUserKeys deletes all API keys for a user.

func (*APIKeyManager) EnableKey added in v0.0.5

func (m *APIKeyManager) EnableKey(keyID string, enabled bool) error

EnableKey enables or disables an API key.

func (*APIKeyManager) GenerateKey added in v0.0.5

func (m *APIKeyManager) GenerateKey(name, username string, permissions Permission, expiresIn time.Duration) (string, *APIKey, error)

GenerateKey generates a new API key. Returns the full key (to be shown once) and the stored APIKey struct.

func (*APIKeyManager) GetKey added in v0.0.5

func (m *APIKeyManager) GetKey(keyID string) (*APIKey, error)

GetKey retrieves an API key by ID.

func (*APIKeyManager) ListAllKeys added in v0.0.5

func (m *APIKeyManager) ListAllKeys() []*APIKey

ListAllKeys lists all API keys (admin only).

func (*APIKeyManager) ListKeys added in v0.0.5

func (m *APIKeyManager) ListKeys(username string) []*APIKey

ListKeys lists all API keys for a user.

func (*APIKeyManager) Load added in v0.0.5

func (m *APIKeyManager) Load() error

Load loads API keys from the persistence file.

func (*APIKeyManager) RevokeKey added in v0.0.5

func (m *APIKeyManager) RevokeKey(keyID string) error

RevokeKey revokes (deletes) an API key.

func (*APIKeyManager) Save added in v0.0.5

func (m *APIKeyManager) Save() error

Save saves API keys to the persistence file.

func (*APIKeyManager) Stats added in v0.0.5

func (m *APIKeyManager) Stats() map[string]interface{}

Stats returns statistics about API keys.

func (*APIKeyManager) ValidateKey added in v0.0.5

func (m *APIKeyManager) ValidateKey(fullKey string) (*APIKey, error)

ValidateKey validates an API key and returns the associated APIKey struct.

type DatabasePrivilege

type DatabasePrivilege struct {
	Database string
	Select   bool
	Insert   bool
	Update   bool
	Delete   bool
	Create   bool
	Drop     bool
	Index    bool
	Alter    bool
}

DatabasePrivilege represents privileges on all tables in a database.

func (*DatabasePrivilege) HasPrivilege

func (d *DatabasePrivilege) HasPrivilege(perm Permission) bool

HasPrivilege checks if a database privilege has a specific permission.

type GlobalPrivilege

type GlobalPrivilege struct {
	Select bool
	Insert bool
	Update bool
	Delete bool
	Create bool
	Drop   bool
	Index  bool
	Alter  bool
	Grant  bool // WITH GRANT OPTION
}

GlobalPrivilege represents global privileges.

func (*GlobalPrivilege) HasPermission

func (g *GlobalPrivilege) HasPermission(perm Permission) bool

HasPermission checks if a global privilege has a specific permission.

type Manager

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

Manager manages users and sessions.

func NewManager

func NewManager(opts ...ManagerOption) *Manager

NewManager creates a new auth manager.

func (*Manager) Authenticate

func (m *Manager) Authenticate(username, password string) (*Session, error)

Authenticate authenticates a user and creates a session.

func (*Manager) ChangePassword

func (m *Manager) ChangePassword(username, oldPassword, newPassword string) error

ChangePassword changes a user's password.

func (*Manager) CheckPermission

func (m *Manager) CheckPermission(username string, perm Permission) (bool, error)

CheckPermission checks if a user has a specific permission.

func (*Manager) CheckTablePermission

func (m *Manager) CheckTablePermission(username, database, table string, perm Permission) bool

CheckTablePermission checks if a user has a specific permission on a table.

func (*Manager) CleanupExpiredSessions

func (m *Manager) CleanupExpiredSessions() int

CleanupExpiredSessions removes expired sessions.

func (*Manager) CreateUser

func (m *Manager) CreateUser(username, password string, role UserRole) (*User, error)

CreateUser creates a new user.

func (*Manager) DeleteUser

func (m *Manager) DeleteUser(username string) error

DeleteUser deletes a user.

func (*Manager) GetGrants

func (m *Manager) GetGrants(username string) ([]string, error)

GetGrants returns all grants for a user.

func (*Manager) GetMySQLAuthHash

func (m *Manager) GetMySQLAuthHash(username string) ([]byte, error)

GetMySQLAuthHash returns the MySQL auth hash for a user.

func (*Manager) GetUser

func (m *Manager) GetUser(username string) (*User, error)

GetUser retrieves a user by username.

func (*Manager) GetUserByID

func (m *Manager) GetUserByID(id uint64) (*User, error)

GetUserByID retrieves a user by ID.

func (*Manager) GrantDatabase

func (m *Manager) GrantDatabase(username, database string, priv *DatabasePrivilege) error

GrantDatabase grants database-level privileges to a user.

func (*Manager) GrantGlobal

func (m *Manager) GrantGlobal(username string, priv *GlobalPrivilege) error

GrantGlobal grants global privileges to a user.

func (*Manager) GrantTable

func (m *Manager) GrantTable(username, database, table string, priv *TablePrivilege) error

GrantTable grants table-level privileges to a user.

func (*Manager) InvalidateSession

func (m *Manager) InvalidateSession(sessionID string)

InvalidateSession invalidates a session.

func (*Manager) ListUsers

func (m *Manager) ListUsers() []*User

ListUsers lists all users.

func (*Manager) Load

func (m *Manager) Load() error

Load loads users from the persistence file.

func (*Manager) LoadGrants

func (m *Manager) LoadGrants() error

LoadGrants loads grants from the persistence file.

func (*Manager) RefreshSession

func (m *Manager) RefreshSession(sessionID string) (*Session, error)

RefreshSession refreshes a session's expiration time.

func (*Manager) RevokeDatabase

func (m *Manager) RevokeDatabase(username, database string, priv *DatabasePrivilege) error

RevokeDatabase revokes database-level privileges from a user.

func (*Manager) RevokeGlobal

func (m *Manager) RevokeGlobal(username string, priv *GlobalPrivilege) error

RevokeGlobal revokes global privileges from a user.

func (*Manager) RevokeTable

func (m *Manager) RevokeTable(username, database, table string, priv *TablePrivilege) error

RevokeTable revokes table-level privileges from a user.

func (*Manager) Save

func (m *Manager) Save() error

Save saves users to the persistence file.

func (*Manager) SaveGrants

func (m *Manager) SaveGrants() error

SaveGrants saves grants to the persistence file.

func (*Manager) SetUserDatabase

func (m *Manager) SetUserDatabase(sessionID, database string) error

SetUserDatabase sets the database for a session.

func (*Manager) ValidateSession

func (m *Manager) ValidateSession(sessionID string) (*Session, error)

ValidateSession validates a session and returns it if valid.

func (*Manager) VerifyMySQLAuth

func (m *Manager) VerifyMySQLAuth(username string, salt, authResponse []byte) (bool, error)

VerifyMySQLAuth verifies MySQL native password authentication. The client sends: SHA1(password) XOR SHA1(salt + SHA1(SHA1(password))) We have stored: SHA1(SHA1(password))

type ManagerOption

type ManagerOption func(*Manager)

ManagerOption is a functional option for Manager.

func WithDataDir

func WithDataDir(dir string) ManagerOption

WithDataDir sets the data directory for persistence.

func WithSessionTTL

func WithSessionTTL(ttl time.Duration) ManagerOption

WithSessionTTL sets the session TTL.

type Permission

type Permission uint32

Permission represents a permission bit.

const (
	PermManageUsers Permission = 1 << iota
	PermManageConfig
	PermStartStop
	PermCreateTable
	PermDropTable
	PermCreateDatabase
	PermDropDatabase
	PermSelect
	PermInsert
	PermUpdate
	PermDelete
	PermCreateIndex
	PermDropIndex
	PermBackup
	PermRestore
)

type PermissionChecker

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

PermissionChecker provides permission checking for a session.

func NewPermissionChecker

func NewPermissionChecker(session *Session) *PermissionChecker

NewPermissionChecker creates a new permission checker.

func (*PermissionChecker) Check

func (p *PermissionChecker) Check(perm Permission) bool

Check checks if the session has the given permission.

func (*PermissionChecker) Require

func (p *PermissionChecker) Require(perm Permission) error

Require checks the permission and returns an error if not granted.

type Session

type Session struct {
	ID        string
	UserID    uint64
	Username  string
	Role      UserRole
	CreatedAt time.Time
	ExpiresAt time.Time
	Database  string
}

Session represents an authenticated session.

func (*Session) HasPermission

func (s *Session) HasPermission(perm Permission) bool

HasPermission checks if the session has the given permission.

func (*Session) IsExpired

func (s *Session) IsExpired() bool

IsExpired checks if the session is expired.

type TablePrivilege

type TablePrivilege struct {
	Database string
	Table    string
	Select   bool
	Insert   bool
	Update   bool
	Delete   bool
	Create   bool
	Drop     bool
	Index    bool
	Alter    bool
}

TablePrivilege represents privileges on a specific table.

func (*TablePrivilege) HasPrivilege

func (t *TablePrivilege) HasPrivilege(perm Permission) bool

HasPrivilege checks if a specific privilege is granted.

type User

type User struct {
	ID            uint64
	Username      string
	PasswordHash  string // bcrypt hash for internal auth
	MySQLAuthHash []byte // SHA1(SHA1(password)) for MySQL native auth
	Role          UserRole
	CreatedAt     time.Time
	UpdatedAt     time.Time
}

User represents a database user.

type UserRole

type UserRole int

UserRole represents a user's role.

const (
	RoleAdmin UserRole = iota
	RoleUser
)

func (UserRole) String

func (r UserRole) String() string

String returns the string representation of the role.

Jump to

Keyboard shortcuts

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