backend

package module
v1.6.1 Latest Latest
Warning

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

Go to latest
Published: Apr 18, 2024 License: MIT Imports: 23 Imported by: 0

README

backend

Easily integrate admin to your fiber application.

Usage

Set database connection
import (
	"github.com/gopsql/backend"
	"github.com/gopsql/logger"
	"github.com/gopsql/pq"
)

conn := pq.MustOpen("postgres://localhost:5432/mydb?sslmode=disable")
backend.Default.SetConnection(conn)
backend.Default.SetLogger(logger.StandardLogger)
backend.Default.CheckAdmin()
Set ErrorHandler
app := fiber.New(fiber.Config{
	ErrorHandler: func(c *fiber.Ctx, err error) error {
		status, content := backend.Default.HandleError(err)
		return c.Status(status).JSON(content)
	},
})
Set JWTSession
import (
	"github.com/gopsql/goconf"
	"github.com/gopsql/jwt"
)

type Configs struct {
	AdminSession *jwt.Session
}

var configs Configs
goconf.Unmarshal([]byte(configFileContent), &c)
backend.Default.JWTSession = configs.AdminSession
Set fiber routes:
import (
	"github.com/gofiber/fiber/v2"
	"github.com/gopsql/backend"
)

type Ctx = fiber.Ctx

func Group(g fiber.Router) {
	sc := backend.Default.NewFiberSessionsCtrl()
	g.Post("/sign-in", convert(sc.SignIn))
	g.Get("/me", convert(sc.Me))
	// routes below need authentication
	g.Use(convert(sc.Authenticate))
	g.Post("/sign-out", convert(sc.SignOut))

	ac := backend.Default.NewFiberAdminsCtrl()
	g.Get("/admins", convert(ac.List))
	g.Get("/admins/:id", convert(ac.Show))
	g.Post("/admins", convert(ac.Create))
	g.Put("/admins/:id", convert(ac.Update))
	g.Delete("/admins/:id", convert(ac.Destroy))
	g.Post("/admins/:id", convert(ac.Restore))
}

func convert(f backend.FiberHandler) fiber.Handler {
	return func(c *Ctx) error {
		return f(c)
	}
}
Others
// new model:
var Orders = backend.Default.NewModel(Order{})

// validate:
backend.Default.MustValidateStruct(foobar)

Documentation

Index

Constants

View Source
const (
	NoCreateAdmin flagUsageOption = iota
	NoCreateConfig
	NoCreateMigration
	NoMigrate
	NoRollback
)

Variables

View Source
var Default = newDefaultBackend()

Default backend contains Admin, AdminSession.

Functions

func ParseSSHConnStr added in v1.2.4

func ParseSSHConnStr(connStr string) (local, ssh, remote string)

ParseSSHConnStr parses strings like this: 127.0.0.1:8080::root:~/.ssh/id_rsa@remote-host:22::127.0.0.1:9999

func SetEnvFromArgs added in v1.2.2

func SetEnvFromArgs()

Types

type Admin

type Admin struct {
	Id        int
	Name      string          `validate:"gt=0,lte=30,uniqueness"`
	Password  bcrypt.Password `validate:"required"`
	CreatedAt time.Time
	UpdatedAt time.Time
	DeletedAt *time.Time
}

Simple admin with name and password.

func (Admin) AfterCreateSchema

func (Admin) AfterCreateSchema(m psql.Model) string

func (Admin) DataType added in v1.3.1

func (Admin) DataType(m psql.Model, fieldName string) (dataType string)

func (Admin) GetCreatedAt added in v1.5.0

func (a Admin) GetCreatedAt() time.Time

func (Admin) GetDeletedAt added in v1.5.0

func (a Admin) GetDeletedAt() *time.Time

func (Admin) GetId added in v1.5.0

func (a Admin) GetId() int

func (Admin) GetName added in v1.5.0

func (a Admin) GetName() string

func (Admin) GetPassword added in v1.5.0

func (a Admin) GetPassword() bcrypt.Password

func (Admin) GetUpdatedAt added in v1.5.0

func (a Admin) GetUpdatedAt() time.Time

func (Admin) IsUnique

func (a Admin) IsUnique(backend *Backend, field string) bool

func (Admin) Serialize added in v1.5.0

func (a Admin) Serialize(typ string, data ...interface{}) interface{}

func (*Admin) SetCreatedAt added in v1.5.0

func (a *Admin) SetCreatedAt(createdAt time.Time)

func (*Admin) SetDeletedAt added in v1.5.0

func (a *Admin) SetDeletedAt(deletedAt *time.Time)

func (*Admin) SetId added in v1.5.0

func (a *Admin) SetId(id int)

func (*Admin) SetName added in v1.5.0

func (a *Admin) SetName(name string)

func (*Admin) SetPassword added in v1.5.0

func (a *Admin) SetPassword(password string) error

func (*Admin) SetUpdatedAt added in v1.5.0

func (a *Admin) SetUpdatedAt(updatedAt time.Time)

type AdminSession

type AdminSession struct {
	Id        int
	AdminId   int
	SessionId string
	IpAddress string
	UserAgent string
	CreatedAt time.Time
	UpdatedAt time.Time
}

Admin session contains session ID, IP address and user-agent.

func (AdminSession) AfterCreateSchema

func (AdminSession) AfterCreateSchema(m psql.Model) string

func (AdminSession) DataType added in v1.3.1

func (AdminSession) DataType(m psql.Model, fieldName string) (dataType string)

func (AdminSession) GetAdminId added in v1.5.3

func (a AdminSession) GetAdminId() int

func (AdminSession) GetCreatedAt added in v1.5.3

func (a AdminSession) GetCreatedAt() time.Time

func (AdminSession) GetId added in v1.5.3

func (a AdminSession) GetId() int

func (AdminSession) GetIpAddress added in v1.5.3

func (a AdminSession) GetIpAddress() string

func (AdminSession) GetSessionId added in v1.5.3

func (a AdminSession) GetSessionId() string

func (AdminSession) GetUpdatedAt added in v1.5.3

func (a AdminSession) GetUpdatedAt() time.Time

func (AdminSession) GetUserAgent added in v1.5.3

func (a AdminSession) GetUserAgent() string

func (*AdminSession) SetAdminId added in v1.5.3

func (a *AdminSession) SetAdminId(adminId int)

func (*AdminSession) SetCreatedAt added in v1.5.3

func (a *AdminSession) SetCreatedAt(createdAt time.Time)

func (*AdminSession) SetId added in v1.5.3

func (a *AdminSession) SetId(id int)

func (*AdminSession) SetIpAddress added in v1.5.3

func (a *AdminSession) SetIpAddress(ipAddress string)

func (*AdminSession) SetSessionId added in v1.5.3

func (a *AdminSession) SetSessionId(sessionId string)

func (*AdminSession) SetUpdatedAt added in v1.5.3

func (a *AdminSession) SetUpdatedAt(updatedAt time.Time)

func (*AdminSession) SetUserAgent added in v1.5.3

func (a *AdminSession) SetUserAgent(userAgent string)

type Backend

type Backend struct {
	Name      string
	Validator *validator.Validate
	// contains filtered or unexported fields
}

Backend instance.

func NewBackend

func NewBackend() *Backend

Create new backend instance.

func (*Backend) AddModelAdmin added in v1.2.3

func (backend *Backend) AddModelAdmin()

func (*Backend) AddModelAdminSession added in v1.2.3

func (backend *Backend) AddModelAdminSession()

func (*Backend) AddModels

func (backend *Backend) AddModels(models ...*psql.Model)

AddModels adds one or multiple psql.Model instances to backend.

func (Backend) BindLocalToRemoteOverSSH added in v1.2.4

func (backend Backend) BindLocalToRemoteOverSSH(local, sshStr, remote string) error

BindLocalToRemoteOverSSH connects to remote server over SSH, bind local port to remote port. The local and remote string should contain IP address and port number like this: 127.0.0.1:8080. The SSH string should contain user name, identity file path, remote host and port. For example: root:~/.ssh/id_rsa@remote-host:22.

func (Backend) CheckAdmin

func (backend Backend) CheckAdmin(callbacks ...func(name, password string, updated bool))

CheckAdmin prints a warning if database contains no admins. If CREATE_ADMIN=1 environment variable is set, creates new admin or resets existing admin's password. Optional callback is called when admin is created or updated.

func (Backend) CheckMigrations added in v1.1.0

func (backend Backend) CheckMigrations()

CheckMigrations prints a warning if there are migrations not yet run. If CREATE_MIGRATION=1 environment variable is set, create new migrationn file. If MIGRATE=1 environment variable is set, executes the up SQL for all the migrations that have not yet been run. If ROLLBACK=1 environment variable is set, rollback last migration.

func (Backend) CreateAdmin added in v1.3.1

func (backend Backend) CreateAdmin(adminName, adminPassword string) (name, password string, updated bool)

Create new admin with adminName and adminPassword (random password if empty) or reset password of admin with adminName to adminPassword. If adminName is empty, only name of first admin in database is returned.

func (Backend) FiberDeleteSession

func (backend Backend) FiberDeleteSession(c FiberCtx) error

FiberDeleteSession deletes a session in the database.

func (Backend) FiberGetAdminAndSessionId

func (backend Backend) FiberGetAdminAndSessionId(c FiberCtx) (adminId int, sessionId string, ok bool)

FiberGetAdminAndSessionId returns the admin and session ID from the Authorization header of a fiber context.

func (Backend) FiberGetCurrentAdmin

func (backend Backend) FiberGetCurrentAdmin(c FiberCtx) interface{}

FiberGetCurrentAdmin finds admin in the database and updates the admin session if IP address or user-agent has been changed, given the Authorization header of a fiber context. The returned admin is then cached in the current request, so subsequent calls of this function will not cause new database queries.

func (Backend) FiberNewSession

func (backend Backend) FiberNewSession(c FiberCtx, adminId int) (token string, err error)

FiberNewSession creates new session for adminId and returns a new JWT string.

func (*Backend) FlagUsage added in v1.2.1

func (backend *Backend) FlagUsage(options ...flagUsageOption) func()

func (Backend) HandleError

func (backend Backend) HandleError(err error) (status int, json interface{})

HandleError returns status code and error message struct according to the given error.

func (Backend) IsErrNoRows added in v1.2.3

func (backend Backend) IsErrNoRows(err error) bool

Check if given error equals to ErrNoRows() of the database connection.

func (*Backend) Logger added in v1.5.6

func (backend *Backend) Logger() logger.Logger

func (*Backend) Migrator added in v1.3.1

func (backend *Backend) Migrator() *migrator.Migrator

func (*Backend) MigratorNewMigration added in v1.3.1

func (backend *Backend) MigratorNewMigration() (migrator.Migrations, error)

func (*Backend) ModelByName

func (backend *Backend) ModelByName(name string) *psql.Model

ModelByName finds psql.Model by name.

func (Backend) MustBindLocalToRemoteOverSSH added in v1.2.4

func (backend Backend) MustBindLocalToRemoteOverSSH(local, sshStr, remote string)

func (Backend) MustFiberDeleteSession

func (backend Backend) MustFiberDeleteSession(c FiberCtx)

MustFiberDeleteSession is like FiberDeleteSession but panics if session deletion fails.

func (Backend) MustFiberNewSession

func (backend Backend) MustFiberNewSession(c FiberCtx, adminId int) string

MustFiberNewSession is like FiberNewSession but panics if session creations fails.

func (Backend) MustFiberValidateNewSession

func (backend Backend) MustFiberValidateNewSession(c FiberCtx) string

func (Backend) MustValidateStruct

func (backend Backend) MustValidateStruct(i interface{})

MustValidateStruct is like ValidateStruct but panics if validation fails.

func (*Backend) NewFiberAdminsCtrl

func (backend *Backend) NewFiberAdminsCtrl() *fiberAdminsCtrl

NewFiberAdminsCtrl creates a simple admins controller for fiber.

func (*Backend) NewFiberSessionsCtrl

func (backend *Backend) NewFiberSessionsCtrl() *fiberSessionsCtrl

NewFiberSessionsCtrl creates a simple admin sessions controller for fiber.

func (*Backend) NewModel

func (backend *Backend) NewModel(object interface{}, options ...interface{}) *psql.Model

NewModel creates and returns a new psql.Model. See github.com/gopsql/psql.

func (Backend) ReadConfigFile added in v1.3.4

func (backend Backend) ReadConfigFile(configFile string, target interface{}) error

ReadConfigFile uses github.com/gopsql/goconf to read config file into target config struct.

func (Backend) ReadConfigs added in v1.2.0

func (backend Backend) ReadConfigs(configFile string, target interface{})

ReadConfigs uses github.com/gopsql/goconf to read config file into target config struct. This will create or update config file if environment variable CREATE_CONFIG is set to 1.

func (*Backend) SetConnection

func (backend *Backend) SetConnection(dbConn db.DB)

SetConnection sets database connection.

func (*Backend) SetJWTSession added in v1.2.1

func (backend *Backend) SetJWTSession(jwtSession jwtSession)

func (*Backend) SetLogger

func (backend *Backend) SetLogger(logger logger.Logger)

SetLogger sets logger.

func (*Backend) SetMigrations added in v1.1.0

func (backend *Backend) SetMigrations(migrations interface{})

func (*Backend) SetName added in v1.2.1

func (backend *Backend) SetName(name string)

func (Backend) ValidateStruct

func (backend Backend) ValidateStruct(i interface{}) error

ValidateStruct validates struct or slice of structs with the validator (github.com/go-playground/validator/v10). If slice of struct is provided, each struct will be validated and nil or ValidatorFieldErrors is returned. ValidatorFieldErrors contains the indexes of the erroneous structs.

func (Backend) WriteConfigFile added in v1.3.4

func (backend Backend) WriteConfigFile(configFile string, target interface{}) error

WriteConfigFile uses github.com/gopsql/goconf to write config file with target config struct.

type DeleteSQL added in v1.2.8

type DeleteSQL = psql.DeleteSQL

type FiberCtx

type FiberCtx interface {
	Body() []byte
	BodyParser(out interface{}) error
	Get(key string, defaultValue ...string) string
	IP() string
	JSON(data interface{}, ctype ...string) error
	Locals(key interface{}, value ...interface{}) (val interface{})
	Next() (err error)
	Params(key string, defaultValue ...string) string
	Query(key string, defaultValue ...string) string
	QueryParser(out interface{}) error
	SendStatus(status int) error
}

Interface for github.com/gofiber/fiber/v2.Ctx

type FiberHandler

type FiberHandler func(FiberCtx) error

type HasParams added in v1.5.1

type HasParams interface {
	Params(string) []string
}

type InputError

type InputError struct {
	FullName string
	Name     string
	Kind     string
	Type     string
	Param    string
}

InputError contains field name and error type.

func NewInputError

func NewInputError(name, errType string) InputError

func (InputError) Error

func (err InputError) Error() string

type InputErrorWithIndex added in v1.3.5

type InputErrorWithIndex struct {
	InputError
	Index int
}

InputErrorWithIndex contains InputError and struct index in a slice.

type InputErrors

type InputErrors []InputError

InputError collection.

func NewInputErrors

func NewInputErrors(name, errType string) InputErrors

func (InputErrors) Error

func (errs InputErrors) Error() string

func (InputErrors) PanicIfPresent

func (errs InputErrors) PanicIfPresent()

type InsertSQL added in v1.2.8

type InsertSQL = psql.InsertSQL

type IsAdmin added in v1.5.0

type IsAdmin interface {
	GetId() int
	GetName() string
	GetPassword() bcrypt.Password
	GetCreatedAt() time.Time
	GetUpdatedAt() time.Time
	GetDeletedAt() *time.Time
	SetId(int)
	SetName(string)
	SetPassword(string) error
	SetCreatedAt(time.Time)
	SetUpdatedAt(time.Time)
	SetDeletedAt(*time.Time)
}

type IsAdminSession added in v1.5.3

type IsAdminSession interface {
	GetId() int
	GetAdminId() int
	GetSessionId() string
	GetIpAddress() string
	GetUserAgent() string
	GetCreatedAt() time.Time
	GetUpdatedAt() time.Time
	SetId(int)
	SetAdminId(int)
	SetSessionId(string)
	SetIpAddress(string)
	SetUserAgent(string)
	SetCreatedAt(time.Time)
	SetUpdatedAt(time.Time)
}

type Model added in v1.3.2

type Model = psql.Model

These types are copied from the psql package, so that code that imports "github.com/gopsql/backend" does not also have to import "github.com/gopsql/psql".

type SQL added in v1.2.8

type SQL = psql.SQL

type SelectSQL added in v1.2.8

type SelectSQL = psql.SelectSQL

type Serializable added in v1.5.0

type Serializable interface {
	Serialize(typ string, data ...interface{}) interface{}
}

type UpdateSQL added in v1.2.8

type UpdateSQL = psql.UpdateSQL

type ValidatorFieldError added in v1.3.5

type ValidatorFieldError struct {
	FieldError validator.FieldError
	Index      int
}

ValidatorFieldError contains the FieldError of the validator (github.com/go-playground/validator/v10) and index of the struct in the slice.

func (ValidatorFieldError) Error added in v1.3.5

func (v ValidatorFieldError) Error() string

type ValidatorFieldErrors added in v1.3.5

type ValidatorFieldErrors []ValidatorFieldError

ValidatorFieldErrors can be returned when validating a slice of struct using ValidateStruct().

func (ValidatorFieldErrors) Error added in v1.3.5

func (errs ValidatorFieldErrors) Error() string

Jump to

Keyboard shortcuts

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