db

package
v0.7.4 Latest Latest
Warning

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

Go to latest
Published: Apr 9, 2022 License: AGPL-3.0 Imports: 18 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var AllTables = []interface{}{
	&Action{},
	&Bulletin{},
	&Challenge{},
	&Flag{},
	&GameBox{},
	&Log{},
	&Manager{},
	&Team{},
}
View Source
var ErrActionScoreInvalid = errors.New("invalid score, please check the action type and the sign of the score")
View Source
var ErrBadCredentials = errors.New("bad credentials")
View Source
var ErrBadLogLevel = errors.New("bad log level")
View Source
var ErrBadLogType = errors.New("bad log type")
View Source
var ErrBulletinNotExists = errors.New("bulletin does not exist")
View Source
var ErrChallengeAlreadyExists = errors.New("challenge already exits")
View Source
var ErrChallengeNotExists = errors.New("challenge does not exist")
View Source
var ErrDuplicateAction = errors.New("duplicate action")
View Source
var ErrFlagNotExists = errors.New("flag does not find")
View Source
var ErrGameBoxAlreadyExists = errors.New("game box already exits")
View Source
var ErrGameBoxNotExists = errors.New("game box does not exist")
View Source
var ErrManagerAlreadyExists = errors.New("manager already exits")
View Source
var ErrManagerNotExists = errors.New("manager dose not exist")
View Source
var ErrTeamAlreadyExists = errors.New("team already exits")
View Source
var ErrTeamNotExists = errors.New("team dose not exist")

Functions

func Init

func Init() error

Init initializes the database.

func SetDatabaseStore

func SetDatabaseStore(db *gorm.DB)

SetDatabaseStore sets the database table store.

Types

type Action

type Action struct {
	gorm.Model

	Type           ActionType `gorm:"uniqueIndex:action_unique_idx"`
	TeamID         uint       `gorm:"uniqueIndex:action_unique_idx"`
	ChallengeID    uint       `gorm:"uniqueIndex:action_unique_idx"`
	GameBoxID      uint       `gorm:"uniqueIndex:action_unique_idx"`
	AttackerTeamID uint       `gorm:"uniqueIndex:action_unique_idx"`
	Round          uint       `gorm:"uniqueIndex:action_unique_idx"`

	Score float64
}

Action represents the action such as check down or being attacked.

type ActionType

type ActionType uint
const (
	ActionTypeBeenAttack ActionType = iota
	ActionTypeCheckDown
	ActionTypeAttack
	ActionTypeServiceOnline
)

type ActionsStore

type ActionsStore interface {
	// Create creates a new action and persists to database, it returns the Action if succeeded.
	Create(ctx context.Context, opts CreateActionOptions) (*Action, error)
	// Get returns the actions according to the given options.
	Get(ctx context.Context, opts GetActionOptions) ([]*Action, error)
	// SetScore updates the action's score.
	SetScore(ctx context.Context, opts SetActionScoreOptions) error
	// CountScore counts score with the given options.
	CountScore(ctx context.Context, opts CountActionScoreOptions) (float64, error)
	// GetEmptyScore returns the empty score actions in the given round.
	GetEmptyScore(ctx context.Context, round uint, actionType ActionType) ([]*Action, error)
	// Delete deletes the actions with the given options.
	Delete(ctx context.Context, opts DeleteActionOptions) error
	// DeleteAll deletes all the actions.
	DeleteAll(ctx context.Context) error
}

ActionsStore is the persistent interface for actions.

var Actions ActionsStore

Actions is the default instance of the ActionsStore.

func NewActionsStore

func NewActionsStore(db *gorm.DB) ActionsStore

NewActionsStore returns a ActionsStore instance with the given database connection.

type Bulletin

type Bulletin struct {
	gorm.Model

	Title string
	Body  string
}

Bulletin represents the bulletin which sent to teams.

type BulletinsStore

type BulletinsStore interface {
	// Create creates a new bulletin and persists to database.
	// It returns the bulletin ID when bulletin created.
	Create(ctx context.Context, opts CreateBulletinOptions) (uint, error)
	// Get returns all the bulletins.
	Get(ctx context.Context) ([]*Bulletin, error)
	// GetByID returns the bulletin with given id.
	// It returns ErrBulletinNotExists when not found.
	GetByID(ctx context.Context, id uint) (*Bulletin, error)
	// Update updates the bulletin with given id.
	Update(ctx context.Context, id uint, opts UpdateBulletinOptions) error
	// DeleteByID deletes the bulletin with given id.
	DeleteByID(ctx context.Context, id uint) error
	// DeleteAll deletes all the bulletins.
	DeleteAll(ctx context.Context) error
}

BulletinsStore is the persistent interface for bulletins.

var Bulletins BulletinsStore

Bulletins is the default instance of the BulletinsStore.

func NewBulletinsStore

func NewBulletinsStore(db *gorm.DB) BulletinsStore

NewBulletinsStore returns a BulletinsStore instance with the given database connection.

type Challenge

type Challenge struct {
	gorm.Model

	Title            string
	BaseScore        float64
	AutoRenewFlag    bool
	RenewFlagCommand string
}

Challenge represents the AWD challenge.

type ChallengesStore

type ChallengesStore interface {
	// Create creates a new challenge and persists to database.
	// It returns the challenge ID when challenge created.
	Create(ctx context.Context, opts CreateChallengeOptions) (uint, error)
	// BatchCreate creates challenges in batch.
	// It returns the challenges after they are created.
	BatchCreate(ctx context.Context, opts []CreateChallengeOptions) ([]*Challenge, error)
	// Get returns all the challenges.
	Get(ctx context.Context) ([]*Challenge, error)
	// GetByID returns the challenge with given id.
	// It returns ErrChallengeNotExists when not found.
	GetByID(ctx context.Context, id uint) (*Challenge, error)
	// GetByIDs returns the challenges with given ids.
	// It ignores the not exists challenge.
	GetByIDs(ctx context.Context, ids ...uint) ([]*Challenge, error)
	// Update updates the challenge with given id.
	Update(ctx context.Context, id uint, opts UpdateChallengeOptions) error
	// DeleteByID deletes the challenge with given id.
	DeleteByID(ctx context.Context, id uint) error
	// DeleteAll deletes all the challenges.
	DeleteAll(ctx context.Context) error
}

ChallengesStore is the persistent interface for challenges.

var Challenges ChallengesStore

Challenges is the default instance of the ChallengesStore.

func NewChallengesStore

func NewChallengesStore(db *gorm.DB) ChallengesStore

NewChallengesStore returns a ChallengesStore instance with the given database connection.

type CountActionScoreOptions

type CountActionScoreOptions struct {
	Type           ActionType
	TeamID         uint
	ChallengeID    uint
	GameBoxID      uint
	AttackerTeamID uint
	Round          uint
}

type CountFlagOptions

type CountFlagOptions struct {
	TeamID      uint
	ChallengeID uint
	GameBoxID   uint
	Round       uint
}

type CreateActionOptions

type CreateActionOptions struct {
	Type           ActionType
	GameBoxID      uint
	AttackerTeamID uint
	Round          uint
}

type CreateBulletinOptions

type CreateBulletinOptions struct {
	Title string
	Body  string
}

type CreateChallengeOptions

type CreateChallengeOptions struct {
	Title            string
	BaseScore        float64
	AutoRenewFlag    bool
	RenewFlagCommand string
}

type CreateFlagOptions

type CreateFlagOptions struct {
	Flags []FlagMetadata
}

type CreateGameBoxOptions

type CreateGameBoxOptions struct {
	TeamID      uint
	ChallengeID uint
	IPAddress   string
	Port        uint
	Description string
	InternalSSH SSHConfig
}

type CreateLogOptions

type CreateLogOptions struct {
	Level LogLevel
	Type  LogType
	Body  string
}

type CreateManagerOptions

type CreateManagerOptions struct {
	Name           string
	Password       string
	IsCheckAccount bool
}

type CreateTeamOptions

type CreateTeamOptions struct {
	Name     string
	Password string
}

type DatabaseType

type DatabaseType string
const (
	DatabaseTypeMySQL    DatabaseType = "mysql"
	DatabaseTypePostgres DatabaseType = "postgres"
)

type DeleteActionOptions

type DeleteActionOptions struct {
	ActionID       uint
	Type           ActionType
	TeamID         uint
	ChallengeID    uint
	GameBoxID      uint
	AttackerTeamID uint
	Round          uint
}

type Flag

type Flag struct {
	gorm.Model

	TeamID      uint `gorm:"uniqueIndex:flag_unique_idx"`
	ChallengeID uint `gorm:"uniqueIndex:flag_unique_idx"`
	GameBoxID   uint `gorm:"uniqueIndex:flag_unique_idx"`
	Round       uint `gorm:"uniqueIndex:flag_unique_idx"`

	Value string
}

Flag represents the flag which team submitted.

type FlagMetadata

type FlagMetadata struct {
	GameBoxID uint
	Round     uint
	Value     string
}

type FlagsStore

type FlagsStore interface {
	// BatchCreate creates flags and persists to database.
	BatchCreate(ctx context.Context, opts CreateFlagOptions) error
	// Get returns the flags.
	Get(ctx context.Context, opts GetFlagOptions) ([]*Flag, int64, error)
	// Count counts the number of the flags with the given options.
	Count(ctx context.Context, opts CountFlagOptions) (int64, error)
	// Check checks the given flag.
	// It returns ErrFlagNotExists when not found.
	Check(ctx context.Context, flag string) (*Flag, error)
	// DeleteAll deletes all the flags.
	DeleteAll(ctx context.Context) error
}

FlagsStore is the persistent interface for flags.

var Flags FlagsStore

Flags is the default instance of the FlagsStore.

func NewFlagsStore

func NewFlagsStore(db *gorm.DB) FlagsStore

NewFlagsStore returns a FlagsStore instance with the given database connection.

type GameBox

type GameBox struct {
	gorm.Model

	TeamID      uint
	Team        *Team `gorm:"-"`
	ChallengeID uint
	Challenge   *Challenge `gorm:"-"`

	IPAddress   string
	Port        uint
	Description string

	InternalSSHPort     uint
	InternalSSHUser     string
	InternalSSHPassword string

	Visible    bool
	Score      float64 // The score can be negative.
	IsDown     bool
	IsCaptured bool
}

GameBox represents the game box.

type GameBoxCountScoreOptions

type GameBoxCountScoreOptions struct {
	TeamID      uint
	ChallengeID uint
	Visible     bool // If Visible is `false`, it returns the visible and invisible game boxes.
	IsDown      bool
	IsCaptured  bool
}

type GameBoxInfo

type GameBoxInfo struct {
	ChallengeID uint
	IsCaptured  bool
	IsDown      bool
	Score       float64 `json:",omitempty"` // Manager only
}

GameBoxInfo contains the game box info.

type GameBoxInfoList

type GameBoxInfoList []*GameBoxInfo

func (GameBoxInfoList) Len

func (g GameBoxInfoList) Len() int

func (GameBoxInfoList) Less

func (g GameBoxInfoList) Less(i, j int) bool

func (GameBoxInfoList) Swap

func (g GameBoxInfoList) Swap(i, j int)

type GameBoxesStore

type GameBoxesStore interface {
	// Create creates a new game box and persists to database.
	// It returns the game box ID when game box created.
	Create(ctx context.Context, opts CreateGameBoxOptions) (uint, error)
	// BatchCreate creates game boxes in batch.
	// It returns the game boxes after they are created.
	BatchCreate(ctx context.Context, opts []CreateGameBoxOptions) ([]*GameBox, error)
	// Get returns the game boxes with the given options.
	Get(ctx context.Context, opts GetGameBoxesOption) ([]*GameBox, error)
	// GetByID returns the game box with given id.
	// It returns ErrGameBoxNotExists when not found.
	GetByID(ctx context.Context, id uint) (*GameBox, error)
	// Count returns the total count of game boxes.
	Count(ctx context.Context) (int64, error)
	// Update updates the game box with given id.
	Update(ctx context.Context, id uint, opts UpdateGameBoxOptions) error
	// SetScore updates the game box score with given id.
	SetScore(ctx context.Context, id uint, score float64) error
	// CountScore counts the game box total scores with the given options.
	CountScore(ctx context.Context, opts GameBoxCountScoreOptions) (float64, error)
	// SetVisible sets the game box visibility with given id.
	SetVisible(ctx context.Context, id uint, isVisible bool) error
	// SetDown activates the game box down status.
	SetDown(ctx context.Context, id uint) error
	// SetCaptured activates the game box captured status.
	SetCaptured(ctx context.Context, id uint) error
	// CleanStatus cleans the given game box's status.
	CleanStatus(ctx context.Context, id uint) error
	// CleanAllStatus sets all the game boxes' status to `GameBoxStatusUp`.
	CleanAllStatus(ctx context.Context) error
	// DeleteByIDs deletes the game box with given ids.
	DeleteByIDs(ctx context.Context, ids ...uint) error
	// DeleteAll deletes all the game boxes.
	DeleteAll(ctx context.Context) error
}

GameBoxesStore is the persistent interface for game boxes.

var GameBoxes GameBoxesStore

GameBoxes is the default instance of the GameBoxesStore.

func NewGameBoxesStore

func NewGameBoxesStore(db *gorm.DB) GameBoxesStore

NewGameBoxesStore returns a GameBoxesStore instance with the given database connection.

type GetActionOptions

type GetActionOptions struct {
	ActionID       uint
	Type           ActionType
	TeamID         uint
	ChallengeID    uint
	GameBoxID      uint
	AttackerTeamID uint
	Round          uint
}

type GetFlagOptions

type GetFlagOptions struct {
	Page        int
	PageSize    int
	TeamID      uint
	ChallengeID uint
	GameBoxID   uint
	Round       uint
}

type GetGameBoxesOption

type GetGameBoxesOption struct {
	TeamID      uint
	ChallengeID uint
	Visible     bool // If Visible is `false`, it returns the visible and invisible game boxes.
	IsDown      bool
	IsCaptured  bool
}

type GetTeamsOptions

type GetTeamsOptions struct {
	OrderBy  string
	Order    string
	Page     int
	PageSize int
}

type Log

type Log struct {
	gorm.Model

	Level LogLevel
	Type  LogType
	Body  string
}

Log represents the log.

type LogLevel

type LogLevel int
const (
	LogLevelNormal LogLevel = iota
	LogLevelWarning
	LogLevelImportant
)

type LogType

type LogType string
const (
	LogTypeHealthCheck    LogType = "health_check"
	LogTypeManagerOperate LogType = "manager_operate"
	LogTypeSSH            LogType = "ssh"
	LogTypeSystem         LogType = "system"
)

type LogsStore

type LogsStore interface {
	// Create creates a new log and persists to database.
	Create(ctx context.Context, opts CreateLogOptions) error
	// Get returns all the logs.
	Get(ctx context.Context) ([]*Log, error)
	// DeleteAll deletes all the logs.
	DeleteAll(ctx context.Context) error
}

LogsStore is the persistent interface for logs.

var Logs LogsStore

Logs is the default instance of the LogsStore.

func NewLogsStore

func NewLogsStore(db *gorm.DB) LogsStore

NewLogsStore returns a LogsStore instance with the given database connection.

type Manager

type Manager struct {
	gorm.Model

	Name           string
	Password       string
	Salt           string
	IsCheckAccount bool
}

Manager represents the manager.

func (*Manager) EncodePassword

func (m *Manager) EncodePassword()

EncodePassword encodes password to safe format.

func (*Manager) ValidatePassword

func (m *Manager) ValidatePassword(password string) bool

ValidatePassword checks if given password matches the one belongs to the manager.

type ManagersStore

type ManagersStore interface {
	// Authenticate validates name and password.
	// It returns ErrBadCredentials when validate failed.
	// The check account can't log in.
	Authenticate(ctx context.Context, name, password string) (*Manager, error)
	// Create creates a new manager and persists to database.
	// It returns the manager when it created.
	Create(ctx context.Context, opts CreateManagerOptions) (*Manager, error)
	// Get returns all the managers.
	Get(ctx context.Context) ([]*Manager, error)
	// GetByID returns the manager with given id.
	// It returns ErrManagerNotExists when not found.
	GetByID(ctx context.Context, id uint) (*Manager, error)
	// ChangePassword changes the manager's password with given id.
	ChangePassword(ctx context.Context, id uint, newPassword string) error
	// Update updates the manager with given id.
	Update(ctx context.Context, id uint, opts UpdateManagerOptions) error
	// DeleteByID deletes the manager with given id.
	DeleteByID(ctx context.Context, id uint) error
	// DeleteAll deletes all the managers.
	DeleteAll(ctx context.Context) error
}

ManagersStore is the persistent interface for managers.

var Managers ManagersStore

Managers is the default instance of the ManagersStore.

func NewManagersStore

func NewManagersStore(db *gorm.DB) ManagersStore

NewManagersStore returns a ManagersStore instance with the given database connection.

type RankItem

type RankItem struct {
	TeamID    uint
	TeamName  string
	Rank      uint
	Score     float64
	GameBoxes GameBoxInfoList // Ordered by challenge ID.
}

RankItem represents a single row of the ranking list.

type RankListOptions

type RankListOptions struct {
	ShowGameBoxScore bool
}

type RanksStore

type RanksStore interface {
	// List returns the ranking list.
	List(ctx context.Context) ([]*RankItem, error)
	// VisibleChallengeTitle returns the titles of the visible challenges.
	VisibleChallengeTitle(ctx context.Context) ([]string, error)
}

RanksStore is the persistent interface for ranks.

var Ranks RanksStore

Ranks is the default instance of the RanksStore.

func NewRanksStore

func NewRanksStore(db *gorm.DB) RanksStore

NewRanksStore returns a RanksStore instance with the given database connection.

type SSHConfig

type SSHConfig struct {
	Port     uint
	User     string
	Password string
}

type ScoresStore

type ScoresStore interface {
	Calculate(ctx context.Context, round uint) error
	RefreshAttackScore(ctx context.Context, round uint, replaces ...bool) error
	RefreshCheckScore(ctx context.Context, round uint, replaces ...bool) error
	RefreshGameBoxScore(ctx context.Context) error
	RefreshTeamScore(ctx context.Context) error
}

ScoresStore is the persistent interface for scores.

var Scores ScoresStore

Scores is the default instance of the ScoresStore.

func NewScoresStore

func NewScoresStore(db *gorm.DB) ScoresStore

NewScoresStore returns a ScoresStore instance with the given database connection.

type SetActionScoreOptions

type SetActionScoreOptions struct {
	ActionID  uint
	Round     uint
	GameBoxID uint
	Score     float64

	Replace bool
}

type Team

type Team struct {
	gorm.Model

	Name     string
	Password string `json:"-"`
	Salt     string `json:"-"`
	Score    float64
	Rank     uint `gorm:"-:migration"` // Ignore in migration.
	Token    string
}

Team represents the team.

func (*Team) EncodePassword

func (t *Team) EncodePassword()

EncodePassword encodes password to safe format.

func (*Team) ValidatePassword

func (t *Team) ValidatePassword(password string) bool

ValidatePassword checks if given password matches the one belongs to the team.

type TeamsStore

type TeamsStore interface {
	// Authenticate validates name and password.
	// It returns ErrBadCredentials when validate failed.
	Authenticate(ctx context.Context, name, password string) (*Team, error)
	// Create creates a new team and persists to database.
	// It returns the team when it created.
	Create(ctx context.Context, opts CreateTeamOptions) (*Team, error)
	// BatchCreate creates teams in batch.
	// It returns the teams after they are created.
	BatchCreate(ctx context.Context, opts []CreateTeamOptions) ([]*Team, error)
	// Get returns the team list.
	Get(ctx context.Context, opts GetTeamsOptions) ([]*Team, error)
	// GetByID returns the team with given id.
	// It returns ErrTeamNotExists when not found.
	GetByID(ctx context.Context, id uint) (*Team, error)
	// GetByName returns the team with given name.
	// It returns ErrTeamNotExists when not found.
	GetByName(ctx context.Context, name string) (*Team, error)
	// GetByToken returns the team with given token.
	GetByToken(ctx context.Context, token string) (*Team, error)
	// ChangePassword changes the team's password with given id.
	ChangePassword(ctx context.Context, id uint, newPassword string) error
	// Update updates the team with given id.
	Update(ctx context.Context, id uint, opts UpdateTeamOptions) error
	// SetScore sets the team score with given id.
	SetScore(ctx context.Context, id uint, score float64) error
	// DeleteByID deletes the team with given id.
	DeleteByID(ctx context.Context, id uint) error
	// DeleteAll deletes all the teams.
	DeleteAll(ctx context.Context) error
}

TeamsStore is the persistent interface for teams.

var Teams TeamsStore

Teams is the default instance of the TeamsStore.

func NewTeamsStore

func NewTeamsStore(db *gorm.DB) TeamsStore

NewTeamsStore returns a TeamsStore instance with the given database connection.

type UpdateBulletinOptions

type UpdateBulletinOptions struct {
	Title string
	Body  string
}

type UpdateChallengeOptions

type UpdateChallengeOptions struct {
	Title            string
	BaseScore        float64
	AutoRenewFlag    bool
	RenewFlagCommand string
}

type UpdateGameBoxOptions

type UpdateGameBoxOptions struct {
	IPAddress   string
	Port        uint
	Description string
	InternalSSH SSHConfig
}

type UpdateManagerOptions

type UpdateManagerOptions struct {
	IsCheckAccount bool
}

type UpdateTeamOptions

type UpdateTeamOptions struct {
	Name  string
	Token string
}

Jump to

Keyboard shortcuts

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