gostp

package module
v0.0.0-...-75cd005 Latest Latest
Warning

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

Go to latest
Published: Sep 28, 2020 License: MIT Imports: 40 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var CachedPages = make(map[string]CachedPage)

CachedPages contains rendered page

View Source
var Db *gorm.DB

Db - gorm db

View Source
var Err error

Err - error variable

View Source
var FunctionsMap = map[string]interface{}{
	"hashpwd": HashPassword,
}

FunctionsMap - map of functions

View Source
var JwtMiddleware = jwtmiddleware.New(jwtmiddleware.Options{
	ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
		return []byte(Settings.SigningKey), nil
	},
	SigningMethod: jwt.SigningMethodHS256,
	ErrorHandler:  CustomJWTError,
})

JwtMiddleware - middleware which validates token

View Source
var Models []interface{}

Models - all app models

View Source
var RegexMap = map[string]RegexAndDescription{
	"username": RegexAndDescription{Regex: "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$", Description: "email isn't valid"},
	"password": RegexAndDescription{Regex: `^.{6,}$`, Description: "password is less than 6 symbols"}}

RegexMap - map of regexes

View Source
var Settings = struct {
	Port                          string `yaml:"port"`
	WorkDir                       string `yaml:"work_dir"`       // WorkDir - is a directory address where program has been launched (default - directory where program stored)
	SigningKey                    string `yaml:"signing_key"`    // SigningKey - key for signing JWT (default - "")
	SSRMillisecondWait            int64  `yaml:"ssr_wait"`       // Time to wait after page loaded in ms (default - 1000 ms)
	SSRexpiration                 int64  `yaml:"ssr_expiration"` // Time after page will be deleted from cache in s (default - 86400 s)
	SSRhost                       string `yaml:"ssr_host"`       // Host for headless chrome rendering (default - "http://localhost:7777")
	SSRdevtools                   string `yaml:"ssr_devtools"`   // Headless Chrome Devtools address (default - "http://localhost:9222")
	SQLtype                       string `yaml:"sql_type"`       // SQLtype - type of gorm SQL (default - "sqlite3")
	SQLfilename                   string `yaml:"sql_filename"`   // SQLfilename - filename of sqlite db (default "app.db")
	SQLhost                       string `yaml:"sql_host"`       // SQLhost - host of remote or local db (defatult - "127.0.0.1")
	SQLport                       string `yaml:"sql_port"`       // SQLport - port of remote or local db (default - "5432")
	SQLdbname                     string `yaml:"sql_dbname"`     // SQLdbname - database name of remote or local db (default - "app")
	SQLuser                       string `yaml:"sql_user"`       // SQLuser - database username (default - "admin")
	SQLpassword                   string `yaml:"sql_password"`   // SQLpassword - database password (default - "admin")
	SQLsslmode                    string `yaml:"sql_sslmode"`    // SQLsslmode - database sslmode (default - "disabled")
	ServerName                    string `yaml:"server_name"`
	ContentType                   string `yaml:"content_type"`
	AccessControlAllowOrigin      string `yaml:"access_control_allow_origin"`
	AccessControlAllowMethods     string `yaml:"access_control_allow_methods"`
	AccessControlAllowHeaders     string `yaml:"access_control_allow_headers"`
	AccessControlAllowCredentials string `yaml:"access_control_allow_credentials"`
	JWTaccessExpiration           int64  `yaml:"jwt_access_expiration"`
	JWTrefreshExpiration          int64  `yaml:"jwt_refresh_expiration"`
	VAPIDPublicKey                string `yaml:"vapid_public_key"`  // you can generate GenerateVAPIDKeys
	VAPIDPrivateKey               string `yaml:"vapid_private_key"` // by webpush.GenerateVAPIDKeys()
}{
	":7777",
	CurrentFolder(),
	"1234",
	1000,
	86400,
	"http://localhost:7777",
	"http://localhost:9222",
	"sqlite3",
	"app.db",
	"127.0.0.1",
	"5432",
	"app",
	"admin",
	"admin",
	"disable",
	"Gostp",
	"application/json",
	"*",
	"GET,PUT,POST,DELETE,OPTIONS",
	"Accept, Accept-Language, Content-Language, Content-Type, x-xsrf-token, authorization",
	"true",
	10080,
	43800,
	"BLyVkijm-gZ4C3NGk7VzM1_cEr8Jek94KvkyFicTsiUwmkWwxHWytNs0kUC3u8y05OTYDLvzOi3o07_7czkEmYw",

	"2dY6qzlzIF3rmye94U49WNvoEWYfit6jr2-2U_jekXg"} // you can generate GenerateVAPIDKeys by webpush.GenerateVAPIDKeys()

Settings - structure for gostp settings

Functions

func CheckAccess

func CheckAccess(r *http.Request, accesses []string, accessStruct interface{}, isAdmin *bool) bool

CheckAccess gets user by him token and checks accesses by struct fieldnames

func CheckBelonging

func CheckBelonging(r *http.Request, target string, isAdmin bool, path []string, models ...interface{}) bool

CheckBelonging checks if user's some struct belogns to another through several structs.

func CheckCurrentUser

func CheckCurrentUser(r *http.Request, URLUserID string) bool

CheckCurrentUser - checks current user by id from url

func CheckPasswordHash

func CheckPasswordHash(password, hash string) bool

CheckPasswordHash returns if hash is valid

func CurrentFolder

func CurrentFolder() string

CurrentFolder shows folder where binary file of program located

func CustomJWTError

func CustomJWTError(w http.ResponseWriter, r *http.Request, err string)

CustomJWTError - returns error if validation fails

func DeleteFile

func DeleteFile(filename string) error

DeleteFile deletes file from disk

func DropTables

func DropTables()

DropTables drops all data. Be careful!

func Encode

func Encode(modelToFill interface{}) []byte

Encode - encodes given model by security rules to json

func FileNotExist

func FileNotExist(filename string) error

FileNotExist checks if file exist on disk

func FileServer

func FileServer(r chi.Router, path string, root http.FileSystem)

FileServer conveniently sets up a http.FileServer handler to serve static files from a http.FileSystem.

func Fill

func Fill(r *http.Request, modelToFill interface{}, handlerType string, godMode bool) string

Fill - easily fills given model by json from request

func GenerateToken

func GenerateToken(userID uint, expiresIn int64) string

GenerateToken - generates new token

func GenerateUser

func GenerateUser()

GenerateUser - generates super user

func GetBodyFromContext

func GetBodyFromContext(r *http.Request) ([]byte, error)

GetBodyFromContext gets body from content

func GetFileFromRequest

func GetFileFromRequest(w http.ResponseWriter, r *http.Request, formName string, sizeBytesLimit int64, path string, allowedExtensions []string) (string, error)

GetFileFromRequest saves image to images folder

func GetUserID

func GetUserID(r *http.Request) uint

GetUserID - reutrns current user id

func GetUserIDClaim

func GetUserIDClaim(tokenString string) (float64, error)

GetUserIDClaim returns UserId

func HashPassword

func HashPassword(password *string, functionError *string)

HashPassword returns hashed and salted password

func Header(w http.ResponseWriter)

Header sets header to all of handlers

func Init

func Init(AppRoutes func(r *chi.Mux), functionsMap map[string]interface{}, regexMap map[string]RegexAndDescription, models ...interface{})

Init - initialize of gostp

func JWTHandler

func JWTHandler(h http.Handler) http.Handler

JWTHandler gets http request, checks jwt token (if it's correct and not expired)

func Migrate

func Migrate()

Migrate soft migration for initialized models, data won't be deleted

func RequestBodyToByte

func RequestBodyToByte(next http.Handler) http.Handler

RequestBodyToByte converts request body to byte

func SSR

func SSR(w http.ResponseWriter, r *http.Request)

SSR checks if rendered page exist in memory and not expired

func SendOptions

func SendOptions(w http.ResponseWriter, r *http.Request)

SendOptions to client

func СheckArguments

func СheckArguments(port *string)

СheckArguments - checks cli arguments and do stuff

Types

type Access

type Access struct {
	Common
	UserID uint `json:"user_id" security:"protected" groups:"public"`
	Admin  bool `json:"-"`
	User   bool `json:"-"`
}

Access struct contains all access posibilities on site.

type AppError

type AppError struct {
	Error   error
	Message string
	Code    int
}

AppError error struct

func Login

func Login(w http.ResponseWriter, r *http.Request) *AppError

Login handles login attempts

func RefreshTokens

func RefreshTokens(w http.ResponseWriter, r *http.Request) *AppError

RefreshTokens handles refresh token attempt

type CachedPage

type CachedPage struct {
	HTML           string
	ExpirationTime time.Time
}

CachedPage contains info about rendered page

type Common

type Common struct {
	ID        uint       `gorm:"primary_key" json:"id" security:"protected" groups:"public"`
	CreatedAt time.Time  `json:"-"`
	UpdatedAt time.Time  `json:"-"`
	DeletedAt *time.Time `sql:"index" json:"-"`
}

Common is a base model structure

type ErrorHandler

type ErrorHandler func(w http.ResponseWriter, r *http.Request) *AppError

ErrorHandler - handles http error

func (ErrorHandler) ServeHTTP

func (ah ErrorHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

type JWT

type JWT struct {
	*jwt.Token
}

JWT token struct

func JWTParse

func JWTParse(t string) (JWT, error)

JWTParse - parses jwt token

func (*JWT) GetUserID

func (token *JWT) GetUserID() (float64, error)

GetUserID - gets user id from jwt token

func (*JWT) IsExpired

func (token *JWT) IsExpired() bool

IsExpired - checks if token is expired

type JWTMiddleware

type JWTMiddleware struct {
	Options jwtmiddleware.Options
}

JWTMiddleware struct

type RegexAndDescription

type RegexAndDescription struct {
	Regex       string // Regex - regular expression rule to validate string
	Description string // Description - description why string is not valid
}

RegexAndDescription struct which contains regexes and description of error

type User

type User struct {
	Common
	Username string `json:"username" gorm:"type:varchar(100);unique_index" security:"create_only" regex:"username" groups:"public"`
	Password string `json:"password" security:"hidden_out" regex:"password" function:"hashpwd"`
}

User contains minimal information about user

type UserTokens

type UserTokens struct {
	AccessToken     string `json:"access_token" groups:"public"`
	RefreshToken    string `json:"refresh_token" groups:"public"`
	AccessExpiresIn int64  `json:"access_expires_in" groups:"public"`
}

UserTokens contains info about access tokens. Will not be saved in Db

func RefreshUserTokens

func RefreshUserTokens(userID uint) UserTokens

RefreshUserTokens - refreshes user tokens

Jump to

Keyboard shortcuts

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