common

package
v0.0.0-...-835025b Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2023 License: MIT Imports: 24 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// - Transport errors
	ErrUnknown            = NewError(fmt.Errorf("error unknown"), 500)
	ErrTooManyRequests    = NewError(fmt.Errorf("error, too many server requests"), 429)
	ErrUnauthorized       = NewError(fmt.Errorf("error, unauthorized"), 401)
	ErrAllFieldsRequired  = NewError(fmt.Errorf("error, all fields required"), 400)
	ErrPasswordsDontMatch = NewError(fmt.Errorf("error, passwords don't match"), 400)
	ErrBindingRequest     = NewError(fmt.Errorf("error binding request"), 400)
	ErrInvalidEmailFormat = NewError(fmt.Errorf("error, invalid email format"), 400)
	ErrInvalidValue       = func(field string) error {
		return NewError(fmt.Errorf("error, invalid value for field %s", field), 400)
	}
	ErrInvalidUsernameLength = func(min, max int) error {
		return NewError(fmt.Errorf("error, username must contain between %d and %d characters", min, max), 400)
	}
	ErrInvalidPasswordLength = func(min, max int) error {
		return NewError(fmt.Errorf("error, password must contain between %d and %d characters", min, max), 400)
	}

	// - Service & Repository errors
	ErrInDBTransaction = NewError(fmt.Errorf("error in database transaction"), 500)

	// --- Users
	ErrCreatingUser                = NewError(fmt.Errorf("error creating user"), 500)
	ErrGettingUser                 = NewError(fmt.Errorf("error getting user"), 500)
	ErrUpdatingUser                = NewError(fmt.Errorf("error updating user"), 500)
	ErrUpdatingUserDetail          = NewError(fmt.Errorf("error updating user detail"), 500)
	ErrDeletingUser                = NewError(fmt.Errorf("error deleting user"), 500)
	ErrSearchingUsers              = NewError(fmt.Errorf("error searching users"), 500)
	ErrUserNotFound                = NewError(fmt.Errorf("error, user not found"), 404)
	ErrUserAlreadyDeleted          = NewError(fmt.Errorf("error, user already deleted"), 404)
	ErrUsernameOrEmailAlreadyInUse = NewError(fmt.Errorf("error, username or email already in use"), 409)
	ErrWrongPassword               = NewError(fmt.Errorf("error, wrong password"), 401)

	// --- User Posts
	ErrCreatingUserPost = NewError(fmt.Errorf("error creating user post"), 500)
)
View Source
var AllModels = []interface{}{
	&User{},
	&UserDetail{},
	&UserPost{},
}

Functions

func Hash

func Hash(data string, salt string) string

func NewCORSConfigMiddleware

func NewCORSConfigMiddleware() gin.HandlerFunc

func NewDatabase

func NewDatabase(config *Config, logger *logrus.Logger) *database

func NewErrorHandlerMiddleware

func NewErrorHandlerMiddleware(logger *logrus.Logger) gin.HandlerFunc

func NewMetric

func NewMetric(m *Metric, subsystem string) (metric prometheus.Collector)

NewMetric associates prometheus.Collector based on Metric.Type

func NewNewRelic

func NewNewRelic(config Monitoring, logger *logrus.Logger) *newrelic.Application

func NewNewRelicMiddleware

func NewNewRelicMiddleware(app *newrelic.Application) gin.HandlerFunc

func NewPrometheusMiddleware

func NewPrometheusMiddleware(p *Prometheus) gin.HandlerFunc

func NewRateLimiter

func NewRateLimiter(requestsPerSecond int) *rate.Limiter

func NewRateLimiterMiddleware

func NewRateLimiterMiddleware(limiter *rate.Limiter) gin.HandlerFunc

func NewTimeoutMiddleware

func NewTimeoutMiddleware(timeoutSeconds int) gin.HandlerFunc

func Wrap

func Wrap(trace string, err error) error

Types

type Auth

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

func NewAuth

func NewAuth(secret string, sessionDurationDays int) *Auth

func (*Auth) GenerateToken

func (auth *Auth) GenerateToken(id int, username, email string, role Role) (string, error)

func (*Auth) ValidateToken

func (auth *Auth) ValidateToken(role Role, shouldMatchUserID bool) gin.HandlerFunc

ValidateToken validates a token for a specific role and sets ID and Email in context

type AuthI

type AuthI interface {
	GenerateToken(id int, username, email string, role Role) (string, error)
	ValidateToken(role Role, shouldMatchUserID bool) gin.HandlerFunc
}

type ChangePasswordRequest

type ChangePasswordRequest struct {
	UserID         int    `json:"user_id"`
	OldPassword    string `json:"old_password"`
	NewPassword    string `json:"new_password"`
	RepeatPassword string `json:"repeat_password"`
}

func (*ChangePasswordRequest) ToUserModel

func (r *ChangePasswordRequest) ToUserModel() User

type ChangePasswordResponse

type ChangePasswordResponse struct {
	User ResponseUser `json:"user"`
}

type Config

type Config struct {
	General
	Database   Database
	Monitoring Monitoring
}

func NewConfig

func NewConfig() *Config

type CreateUserPostRequest

type CreateUserPostRequest struct {
	UserID int    `json:"user_id"`
	Title  string `json:"title"`
	Body   string `json:"body"`
}

func (*CreateUserPostRequest) ToUserPostModel

func (r *CreateUserPostRequest) ToUserPostModel() UserPost

type CreateUserPostResponse

type CreateUserPostResponse struct {
	UserPost ResponseUserPost `json:"user_post"`
}

type CreateUserRequest

type CreateUserRequest struct {
	Username string `json:"username"`
	Email    string `json:"email"`
	Password string `json:"password"`
	IsAdmin  bool   `json:"is_admin"`

	// User Detail
	FirstName string `json:"first_name"`
	LastName  string `json:"last_name"`
}

func (*CreateUserRequest) ToUserModel

func (r *CreateUserRequest) ToUserModel() User

type CreateUserResponse

type CreateUserResponse struct {
	User ResponseUser `json:"user"`
}

type CustomClaims

type CustomClaims struct {
	Username string `json:"username"`
	Email    string `json:"email"`
	Role     Role   `json:"role"`
	jwt.RegisteredClaims
}

type Database

type Database struct {
	Type     string `envconfig:"GO_REST_EXAMPLE_DATABASE_TYPE"`
	Username string `envconfig:"GO_REST_EXAMPLE_DATABASE_USERNAME"`
	Password string `envconfig:"GO_REST_EXAMPLE_DATABASE_PASSWORD"`
	Hostname string `envconfig:"GO_REST_EXAMPLE_DATABASE_HOSTNAME"`
	Port     string `envconfig:"GO_REST_EXAMPLE_DATABASE_PORT"`
	Schema   string `envconfig:"GO_REST_EXAMPLE_DATABASE_SCHEMA"`
}

func (*Database) GetConnectionString

func (dbConfig *Database) GetConnectionString() string

type DeleteUserRequest

type DeleteUserRequest struct {
	UserID int `json:"user_id"`
}

func (*DeleteUserRequest) ToUserModel

func (r *DeleteUserRequest) ToUserModel() User

type DeleteUserResponse

type DeleteUserResponse struct {
	User ResponseUser `json:"user"`
}

type Error

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

func NewError

func NewError(err error, status int) *Error

func (*Error) Error

func (e *Error) Error() string

func (*Error) Status

func (e *Error) Status() int

type General

type General struct {
	AppName   string `envconfig:"GO_REST_EXAMPLE_APP_NAME"`
	Debug     bool   `envconfig:"GO_REST_EXAMPLE_DEBUG"`
	Port      string `envconfig:"GO_REST_EXAMPLE_PORT"`
	JWTSecret string `envconfig:"GO_REST_EXAMPLE_JWT_SECRET"`
	HashSalt  string `envconfig:"GO_REST_EXAMPLE_HASH_SALT"`
}

type GetUserRequest

type GetUserRequest struct {
	UserID int `json:"user_id"`
}

func (*GetUserRequest) ToUserModel

func (r *GetUserRequest) ToUserModel() User

type GetUserResponse

type GetUserResponse struct {
	User ResponseUser `json:"user"`
}

type HTTPResponse

type HTTPResponse struct {
	Success bool        `json:"success"`
	Content interface{} `json:"content"`
	Error   string      `json:"error"`
}

type LoginRequest

type LoginRequest struct {
	UsernameOrEmail string `json:"username_or_email"`
	Password        string `json:"password"`
}

func (*LoginRequest) ToUserModel

func (r *LoginRequest) ToUserModel() User

type LoginResponse

type LoginResponse struct {
	Token string `json:"token"`
}

type Metric

type Metric struct {
	MetricCollector prometheus.Collector // the type of the metric: counter_vec, gauge, etc
	ID              string
	Name            string
	Description     string
	Type            string
	Args            []string
}

prometheus.Collector type (i.e. CounterVec, Summary, etc) of each metric

type Monitoring

type Monitoring struct {
	NewRelicEnabled    bool   `envconfig:"GO_REST_EXAMPLE_MONITORING_NEW_RELIC_ENABLED"`
	NewRelicAppName    string `envconfig:"GO_REST_EXAMPLE_MONITORING_NEW_RELIC_APP_NAME"`
	NewRelicLicenseKey string `envconfig:"GO_REST_EXAMPLE_MONITORING_NEW_RELIC_LICENSE_KEY"`

	PrometheusEnabled bool   `envconfig:"GO_REST_EXAMPLE_MONITORING_PROMETHEUS_ENABLED"`
	PrometheusAppName string `envconfig:"GO_REST_EXAMPLE_MONITORING_PROMETHEUS_APP_NAME"`
}

type Prometheus

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

Prometheus contains the metrics gathered by the instance and its path

func NewPrometheus

func NewPrometheus(cfg Monitoring, logger *logrus.Logger) *Prometheus

func (*Prometheus) HandlerFunc

func (p *Prometheus) HandlerFunc() gin.HandlerFunc

HandlerFunc is the actual middleware, it's where the magic happens

type ResponseUser

type ResponseUser struct {
	ID        int                `json:"id"`
	Username  string             `json:"username"`
	Email     string             `json:"email"`
	IsAdmin   bool               `json:"is_admin,omitempty"`
	Details   ResponseUserDetail `json:"details"`
	Posts     []ResponseUserPost `json:"posts"`
	Deleted   bool               `json:"deleted,omitempty"`
	CreatedAt time.Time          `json:"created_at,omitempty"`
	UpdatedAt time.Time          `json:"updated_at,omitempty"`
}

type ResponseUserDetail

type ResponseUserDetail struct {
	FirstName string `json:"first_name"`
	LastName  string `json:"last_name"`
}

type ResponseUserPost

type ResponseUserPost struct {
	ID    int    `json:"id"`
	Title string `json:"title"`
	Body  string `json:"body"`
}

type Role

type Role string
const (
	AnyRole   Role = "any"
	UserRole  Role = "user"
	AdminRole Role = "admin"
)

type SearchUsersRequest

type SearchUsersRequest struct {
	Username string `json:"username"`
	Page     int    `json:"page"`
	PerPage  int    `json:"per_page"`
}

func (*SearchUsersRequest) ToUserModel

func (r *SearchUsersRequest) ToUserModel() User

type SearchUsersResponse

type SearchUsersResponse struct {
	Users   []ResponseUser `json:"users"`
	Page    int            `json:"page"`
	PerPage int            `json:"per_page"`
}

type SignupRequest

type SignupRequest struct {
	Username       string `json:"username"`
	Email          string `json:"email"`
	Password       string `json:"password"`
	RepeatPassword string `json:"repeat_password"`

	// User Detail
	FirstName string `json:"first_name"`
	LastName  string `json:"last_name"`
}

func (*SignupRequest) ToUserModel

func (r *SignupRequest) ToUserModel() User

type SignupResponse

type SignupResponse struct {
	User ResponseUser `json:"user"`
}

type UpdateUserRequest

type UpdateUserRequest struct {
	UserID   int    `json:"user_id"`
	Username string `json:"username"`
	Email    string `json:"email"`

	// User Detail
	FirstName *string `json:"first_name"`
	LastName  *string `json:"last_name"`
}

func (*UpdateUserRequest) ToUserModel

func (r *UpdateUserRequest) ToUserModel() User

type UpdateUserResponse

type UpdateUserResponse struct {
	User ResponseUser `json:"user"`
}

type User

type User struct {
	ID        int    `gorm:"primaryKey"`
	Username  string `gorm:"unique;not null"`
	Email     string `gorm:"unique;not null"`
	Password  string `gorm:"not null"`
	IsAdmin   bool
	Details   UserDetail
	Posts     UserPosts `gorm:"foreignKey:UserID;references:ID"`
	Deleted   bool
	CreatedAt time.Time
	UpdatedAt time.Time

	// DTOs
	NewPassword string `gorm:"-"`
}

func (*User) GenerateTokenString

func (u *User) GenerateTokenString(a AuthI) (string, error)

func (*User) GetRole

func (u *User) GetRole() Role

func (*User) HashPassword

func (u *User) HashPassword(salt string)

func (*User) OverwriteDetails

func (u *User) OverwriteDetails(firstName, lastName *string)

func (*User) OverwriteFields

func (u *User) OverwriteFields(username, email, password string)

func (*User) PasswordMatches

func (u *User) PasswordMatches(password, salt string) bool

func (User) ToResponseModel

func (u User) ToResponseModel() ResponseUser

type UserDetail

type UserDetail struct {
	ID        int    `gorm:"primaryKey"`
	UserID    int    `gorm:"unique;not null"`
	FirstName string `gorm:"not null"`
	LastName  string `gorm:"not null"`
	CreatedAt time.Time
	UpdatedAt time.Time
}

func (UserDetail) ToResponseModel

func (u UserDetail) ToResponseModel() ResponseUserDetail

type UserPost

type UserPost struct {
	ID     int    `gorm:"primaryKey"`
	Title  string `gorm:"not null"`
	Body   string `gorm:"type:text"`
	UserID int    `gorm:"not null"`
}

func (UserPost) ToResponseModel

func (p UserPost) ToResponseModel() ResponseUserPost

type UserPosts

type UserPosts []UserPost

func (UserPosts) ToResponseModel

func (p UserPosts) ToResponseModel() []ResponseUserPost

type Users

type Users []User

func (Users) ToResponseModel

func (u Users) ToResponseModel() []ResponseUser

Jump to

Keyboard shortcuts

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