vbcore

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2018 License: Apache-2.0 Imports: 19 Imported by: 6

README

vbcore

Common core features for all vikebot applications written in go. Including time caches, formatting, users, logging, ...

Build Status codecov Go Report Card GoDoc

Documentation

Index

Constants

View Source
const (
	// EmailLinked defines that the user has added this email, but not verified
	// he has controll over it
	EmailLinked = 0
	// EmailVerified defines that the user has added this email and verfied that
	// he has controll over it
	EmailVerified = 1
	// EmailPrimary defines that the user has set this email as primary address
	// for his account. Also the one we show publicly.
	EmailPrimary = 2
)
View Source
const (
	// EmailLinkedString is the string representation for EmailLinked
	EmailLinkedString = "linked"
	// EmailVerifiedString is the string representation for EmailVerified
	EmailVerifiedString = "verified"
	// EmailPrimaryString is the string representation for EmailPrimary
	EmailPrimaryString = "primary"
)
View Source
const (
	OAuthProviderGithub = "github"
	OAuthProviderGoogle = "google"
)
View Source
const (
	// PermissionBanned defines that the user cannot access any vikebot
	// resources any more
	PermissionBanned = 0
	// PermissionDefault defines the initial permission-set given at the
	// users registration
	PermissionDefault = 1
	// PermissionVerified defines a state for profiles which where
	// controlled by a team member of vikebot manually
	PermissionVerified = 2
	// PermissionTeam defines that the user is working in any way for
	// vikebot and has supporting rights (e.g. set users to PermissionBanned,
	// PermissionDefault or PermissionVerified)
	PermissionTeam = 3
	// PermissionAdmin defines that the user is in vikebot's administration
	// board (e.g. director of ...)
	PermissionAdmin = 4
)
View Source
const (
	// PermissionBannedString is the string representation for PermissionBanned
	PermissionBannedString = "banned"
	// PermissionDefaultString is the string representation for PermissionDefault
	PermissionDefaultString = "default"
	// PermissionVerifiedString is the string representation for PermissionVerified
	PermissionVerifiedString = "verified"
	// PermissionTeamString is the string representation for PermissionTeam
	PermissionTeamString = "team"
	// PermissionAdminString is the string representation for PermissionAdmin
	PermissionAdminString = "admin"
)
View Source
const (
	RoundStatusOpen     = 1
	RoundStatusClosed   = 2
	RoundStatusRunning  = 3
	RoundStatusFinished = 4
)

Variables

View Source
var CryptoGenThreshold = 10

CryptoGenThreshold defines the maximum number N to retry generating cryptographically secure random bytes inside CryptoGenBytes, if previous ones fail

Functions

func CryptoCmpBytes

func CryptoCmpBytes(x, y []byte) bool

CryptoCmpBytes performs a constant-time-compare on byte slices to prevent from side-channel attacks (especiall timing attacks). If the slices are not of the same length, they are passed through SHA512 to normalize their length.

func CryptoCmpStr

func CryptoCmpStr(x, y string) bool

CryptoCmpStr performs a constant-time-compare on strings to prevent from side-channel attacks (especiall timing attacks). If the strings are not of the same length, they are passed through SHA512 to normalize their length.

func CryptoGen

func CryptoGen() (key string, err error)

CryptoGen generates a random 32 bytes long AES key and return's it's base64 equivalent

func CryptoGenBytes

func CryptoGenBytes(len int) (buf []byte, err error)

CryptoGenBytes uses CSPRNGs or HSMs to generate `len` cryptographically random bytes that can be used in any security specific context. In the rare event that no secure random values could be generated this func will retry it N-times (`n` defined as `CryptoGenThreshold` - defaults to `10`). If after N tries no crypo randoms are found the error will be returned and the slice will be empty.

func CryptoGenString

func CryptoGenString(n int) (string, error)

CryptoGenString generates a n-long random string that can be used in any security specific context. Internally CryptoGenBytes it used (read func- docs for more info).

func CryptoPwd

func CryptoPwd(password string) (hash, salt string, err error)

CryptoPwd performs length normalization and password hashing to the passed string and returns the final hash and salt encoded in a hex string

func CryptoPwdVerify

func CryptoPwdVerify(hash, salt, password string) (ok bool, err error)

CryptoPwdVerify compares the already hashed password and it's salt against the unhashed given password. This function is resitent from side-channel attacks and uses constant-time-comparison methods.

func EmailAtoI

func EmailAtoI(status string) int

EmailAtoI converts a status string representation to it's equivalent real integer value. If the string value isn't defined EmailLinked will be returned.

func EmailItoA

func EmailItoA(status int) string

EmailItoA converts a status integer to it's equivalent string representation. If the value is lesser than EmailLinked "linked" will be returned. If the value is bigger than EmailPrimary "primary" will be returned.

func FastRandomString

func FastRandomString(n int) string

FastRandomString provides a simple function to generate `n` long random strings. This package uses a `PRNG`. Don't use for cryptocraphically secure contexts.

func ItoNumberUnity

func ItoNumberUnity(value int) string

ItoNumberUnity converts an int to a shortend string representation with it's unity. Example: 1000-1999 will be converted to 1K. Works will K, M and B. Everything below 1000 will be returned as normal number

func MaxInt

func MaxInt(x, y int) int

MaxInt returns the bigger of the two passed integer

func MinInt

func MinInt(x, y int) int

MinInt returns the smaller of the two passed integer

func PermissionAtoI

func PermissionAtoI(permission string) int

PermissionAtoI converts a permission string representation to it's equivalent real integer value. If the string value isn't defined PermissionAdmin will be returned.

func PermissionItoA

func PermissionItoA(permission int) string

PermissionItoA converts an integer permission to value to it's equivalent string representation. If the value is lesser than PermissionBanned "banned" will be returned. If the value is bigger than PermissionAdmin "admin" will be returned.

func StrMask

func StrMask(str string) string

StrMask replaces the later half of the passed string with *.

func StrMaskIdx

func StrMaskIdx(str string, idx int) string

StrMaskIdx replaces all characters with * starting at index idx.

func TernaryOperatorA

func TernaryOperatorA(condition bool, trueValue string, falseValue string) string

TernaryOperatorA behaves like a ternary operator on a string

func TernaryOperatorI

func TernaryOperatorI(condition bool, trueValue int, falseValue int) int

TernaryOperatorI behaves like a ternary operator on a int

Types

type CryptoService

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

CryptoService provides a clean interface to encrypt data

func NewCryptoService

func NewCryptoService(key []byte) (cs *CryptoService, err error)

NewCryptoService generates a new `CryptoService` instance used to perform cryptographically secure encryption and decryption processes using `AES256` in `GCM` (Galois-Counter-Mode).

func (CryptoService) Decrypt

func (cs CryptoService) Decrypt(cipher []byte) (plain []byte, err error)

Decrypt takes the cipher content, decrypts it and returns the plain text

func (CryptoService) DecryptBase64

func (cs CryptoService) DecryptBase64(base64Cipher []byte) (plain []byte, err error)

DecryptBase64 works like `Decrypt`, but decodes the cipher to it's non `base64` equivalent before decrypting.

func (CryptoService) Encrypt

func (cs CryptoService) Encrypt(plain []byte) (cipher []byte, err error)

Encrypt takes the plain content, encrypts it and returns the cipher already including the used iv

func (CryptoService) EncryptBase64

func (cs CryptoService) EncryptBase64(plain []byte) (base64Cipher []byte, err error)

EncryptBase64 works like `Encrypt`, but encodes the cipher to it's `base64` equivalent before returning.

type Email

type Email struct {
	Email  string
	Status int
	Public bool
}

Email defines a single email entry of a user

func (Email) IsLinked

func (e Email) IsLinked() bool

IsLinked indicates if the `Status` is `EmailLinked`

func (Email) IsPrimary

func (e Email) IsPrimary() bool

IsPrimary indicates if the `Status` is `EmailPrimary`

func (Email) IsVerified

func (e Email) IsVerified() bool

IsVerified indicates if the `Status` is `EmailVerified`

type Endpoint

type Endpoint struct {
	Host string
	Port int
}

Endpoint defines the network identification for a party

func NewEndpoint

func NewEndpoint(host string, port int) *Endpoint

NewEndpoint creates a new endpoint struct ready to use in SSHTunnels

func NewEndpointAddr

func NewEndpointAddr(addr string) *Endpoint

NewEndpointAddr creates a new endpoint struct ready to use in SSHTunnels. The format of addr has to be Host:Port where Port is a valid int as described by strconv.Atoi

func (*Endpoint) String

func (ep *Endpoint) String() string

String returns the the endpoint in format Host:Port

type FCRNG

type FCRNG struct {
	Seed      uint64
	Size      uint64
	Increment uint64
	// contains filtered or unexported fields
}

FCRNG implements a full-cyclic-random-number-generator

func NewFCRNG

func NewFCRNG(size uint64) *FCRNG

func (*FCRNG) Next32

func (f *FCRNG) Next32() int32

func (*FCRNG) Next64

func (f *FCRNG) Next64() int64

func (*FCRNG) NextU32

func (f *FCRNG) NextU32() uint32

func (*FCRNG) NextU64

func (f *FCRNG) NextU64() uint64

type GoogleUser

type GoogleUser struct {
	Sub           string `json:"sub"`
	Name          string `json:"name"`
	GivenName     string `json:"given_name"`
	FamilyName    string `json:"family_name"`
	Profile       string `json:"profile"`
	Picture       string `json:"picture"`
	Email         string `json:"email"`
	EmailVerified bool   `json:"email_verified"`
	Gender        string `json:"gender"`
}

type Round

type Round struct {
	ID          int       `json:"id"`
	Name        string    `json:"name"`
	Wallpaper   string    `json:"wallpaper"`
	Joined      int       `json:"joined"`
	Min         int       `json:"min"`
	Max         int       `json:"max"`
	Starttime   time.Time `json:"starttime"`
	RoundStatus int       `json:"status"`
}

type Roundentry

type Roundentry struct {
	Round
	Authtoken  string `json:"authtoken"`
	Watchtoken string `json:"watchtoken"`
}

type RoundentryConnectinfo

type RoundentryConnectinfo struct {
	Roundticket string `json:"ticket"`
	AESKey      string `json:"aes_key"`
	IPv4        string `json:"ipv4"`
	IPv6        string `json:"ipv6"`
	Port        int    `json:"port"`
}

type RoundentryVerification

type RoundentryVerification struct {
	UserID  int     `json:"user_id"`
	RoundID int     `json:"round_id"`
	AESKey  *string `json:"aes_key,omitempty"`
}

type SSHTunnel

type SSHTunnel struct {
	Local  *Endpoint
	Server *Endpoint
	Remote *Endpoint
	// contains filtered or unexported fields
}

SSHTunnel is a wrapper for a secure encrypted tcp tunnel based the ssh protocol

func NewSSHTunnel

func NewSSHTunnel(user string, password string, local *Endpoint, server *Endpoint, remote *Endpoint, errorHandler func(error)) *SSHTunnel

NewSSHTunnel initializes a new instance of SSHTunnel

func (*SSHTunnel) Bind

func (tunnel *SSHTunnel) Bind() error

Bind tries to initialize a new listener on the local address. It doesn't start to listen for connections.

func (*SSHTunnel) Start

func (tunnel *SSHTunnel) Start(tunnelReady chan bool) error

Start will accept new clients and forward them into new go routines

type SafeUser

type SafeUser struct {
	ID               int               `json:"id"`
	Permission       int               `json:"permission"`
	PermissionString string            `json:"permission_string"`
	Username         string            `json:"username"`
	Name             string            `json:"name"`
	Emails           []Email           `json:"emails"`
	Bio              string            `json:"bio"`
	Location         string            `json:"location"`
	Web              []string          `json:"web"`
	Company          string            `json:"company"`
	Social           map[string]string `json:"social"`
	OAuth            map[string]string `json:"-"`
}

SafeUser equals to User itself with one exception: all variables are already value fields (and not pointers) and there aren't any json declarations.

func (*SafeUser) MakePublic

func (su *SafeUser) MakePublic()

MakePublic converts the user into it's public version. Everyone is allowed to access this version without authentication. Currently only emails which are ether private or not verified are stripped away.

func (*SafeUser) PrimaryEmail

func (su *SafeUser) PrimaryEmail() *Email

PrimaryEmail returns the primary email of this user. If there isn't anyone `nil` is returned.

func (*SafeUser) User

func (su *SafeUser) User() *User

User converts the SafeUser struct to a User struct.

type StringCache

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

StringCache defines a simple to use cache for string values

func NewStringCache

func NewStringCache() *StringCache

NewStringCache creates the internally used storages

func (*StringCache) Add

func (c *StringCache) Add(key string, intervalSeconds float64, refresh StringCacheRefreshFunc)

Add registers a new cache item that can be received with Get(). All cache items will automatically be updated in the specified intervals. Interval values should be in second unity

func (*StringCache) Get

func (c *StringCache) Get(key string) (value string)

Get returns the last fetched value of the cache item. If in this Get cycle the cache detects that an refresh is needed you will get the old value and a refresh will be executed in another go rountine.

type StringCacheItem

type StringCacheItem struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

StringCacheItem is one single object of the Cache

type StringCacheRefreshFunc

type StringCacheRefreshFunc func() (value string)

StringCacheRefreshFunc defines a func that can used to update the value of an Item

type User

type User struct {
	ID               *int
	Permission       *int
	PermissionString *string
	Username         *string
	Name             *string
	Emails           []Email
	Bio              *string
	Location         *string
	Web              []string
	Company          *string
	Social           map[string]string
	OAuth            map[string]string
}

User defines a user with all it's properties. All vikebot code should be able to access all information from the database through this struct

func (*User) SafeUser

func (u *User) SafeUser() *SafeUser

SafeUser converts a User to a SafeUser struct. All properties that aren't set in the User struct will have the type's default value in the SafeUser struct.

func (*User) Validate

func (u *User) Validate() (safeUser *SafeUser, valid bool)

Validate checks whether a `vbcore.User` struct, passed from clients, is in a valid state or not.

Jump to

Keyboard shortcuts

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