common

package
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2019 License: BSD-3-Clause Imports: 23 Imported by: 14

Documentation

Index

Constants

View Source
const ContentTypeJSON = "application/json; charset=utf-8"
View Source
const (
	// TimeFormat standard for the application
	TimeFormat string = "2006-01-02 15:04"
)

Variables

View Source
var (
	DatabaseTableNames = []string{
		"blacklist",
		"device",
		"lease",
		"lease_history",
		"sessions",
		"settings",
		"user",
	}

	BlacklistTableCols = []string{
		"id",
		"value",
		"comment",
	}

	DeviceTableRows = []string{
		"id",
		"mac",
		"username",
		"registered_from",
		"platform",
		"expires",
		"date_registered",
		"user_agent",
		"blacklisted",
		"description",
		"last_seen",
	}

	LeaseTableCols = []string{
		"id",
		"ip",
		"mac",
		"network",
		"start",
		"end",
		"hostname",
		"abandoned",
		"registered",
	}

	UserTableCols = []string{
		"id",
		"username",
		"password",
		"device_limit",
		"default_expiration",
		"expiration_type",
		"can_manage",
		"can_autoreg",
		"valid_start",
		"valid_end",
		"valid_forever",
		"ui_group",
		"api_group",
		"allow_status_api",
	}

	SessionTableCols = []string{
		"id",
		"session_data",
		"created_on",
		"modified_on",
	}

	SettingTableCols = []string{
		"id",
		"value",
	}
)

Database table and column names for enumeration and misc use.

View Source
var PageSize = 30

PageSize is the number of items per page

View Source
var SystemVersion string

SystemVersion is the current version of the software.

Functions

func ConvertToInt

func ConvertToInt(s string) int

ConvertToInt converts s to an int and ignores errors

func FileExists

func FileExists(file string) bool

FileExists tests if a file exists

func FindConfigFile added in v0.8.0

func FindConfigFile() string

FindConfigFile searches for a configuration file. The order of search is environment, current dir, home dir, and /etc.

func FormatMacAddress

func FormatMacAddress(mac string) (net.HardwareAddr, error)

FormatMacAddress will attempt to format and parse a string as a MAC address

func GetIPFromContext added in v0.14.0

func GetIPFromContext(r *http.Request) net.IP

GetIPFromContext retrieves the IP address from the current request.

func LoadPolicyText added in v0.8.0

func LoadPolicyText(file string) []template.HTML

LoadPolicyText loads a file and wraps it in a template type to ensure custom HTML is allowed. The file should be secured so unauthorized HTML/JS isn't allowed.

func ParseTime

func ParseTime(time string) (int64, error)

ParseTime return the number of seconds represented by the string. Valid input looks like "HH:mm". HH must be between 0-24 inclusive and mm must be between 0-59 inclusive.

func RegisterSystemInitFunc added in v1.3.0

func RegisterSystemInitFunc(f SystemInitFunc)

RegisterSystemInitFunc registers a function to be run on system init.

func RunSystemInits added in v1.3.0

func RunSystemInits(e *Environment) error

RunSystemInits executes the registered init functions in the order they were registered.

func SetEnvironmentToContext

func SetEnvironmentToContext(r *http.Request, e *Environment) *http.Request

SetEnvironmentToContext sets an Environment for the current request.

func SetIPToContext added in v0.14.0

func SetIPToContext(r *http.Request) *http.Request

SetIPToContext sets an IP address for the current request.

func SetSessionToContext

func SetSessionToContext(r *http.Request, s *Session) *http.Request

SetSessionToContext sets an Session for the current request.

func StringInSlice

func StringInSlice(a string, list []string) bool

StringInSlice searches a slice for a string

Types

type APIResponse

type APIResponse struct {
	Message string
	Data    interface{}
}

A APIResponse is returned as a JSON struct to the client.

func NewAPIResponse

func NewAPIResponse(m string, d interface{}) *APIResponse

NewAPIResponse creates an APIResponse object with status c, message m, and data d.

func NewEmptyAPIResponse

func NewEmptyAPIResponse() *APIResponse

NewEmptyAPIResponse returns an APIResponse with no message or data.

func (*APIResponse) Encode

func (a *APIResponse) Encode() []byte

Encode the APIResponse into JSON.

func (*APIResponse) WriteResponse

func (a *APIResponse) WriteResponse(w http.ResponseWriter, code int) (int, error)

WriteResponse encodes and writes a response back to the client.

type Config

type Config struct {
	Core struct {
		SiteTitle          string
		SiteCompanyName    string
		SiteDomainName     string
		SiteFooterText     string
		JobSchedulerWakeUp string
		PageSize           int
	}
	Logging struct {
		Enabled    bool
		EnableHTTP bool
		Level      string
		Path       string
	}
	Database struct {
		Type         string
		Address      string
		Port         int
		Username     string
		Password     string
		Name         string
		Retry        int
		RetryTimeout string
	}
	Registration struct {
		RegistrationPolicyFile      string
		AllowManualRegistrations    bool
		DefaultDeviceLimit          int
		DefaultDeviceExpirationType string
		RollingExpirationLength     string
		DefaultDeviceExpiration     string
		ManualRegPlatforms          []string
	}
	Guest struct {
		Enabled              bool
		GuestOnly            bool
		DeviceLimit          int
		DeviceExpirationType string
		DeviceExpiration     string
		Checker              string
		VerifyCodeExpiration int
		DisableCaptcha       bool
		RegPageHeader        string

		Email struct {
		}

		Twilio struct {
			AccountSID  string
			AuthToken   string
			PhoneNumber string
		}

		Smseagle struct {
			Address      string
			Username     string
			Password     string
			HighPriority int
			FlashMsg     int
		}
	}
	Webserver struct {
		Address             string
		HTTPPort            int
		HTTPSPort           int
		TLSCertFile         string
		TLSKeyFile          string
		RedirectHTTPToHTTPS bool
		SessionStore        string
		SessionName         string
		SessionsDir         string
		SessionsAuthKey     string
		SessionsEncryptKey  string
		CustomDataDir       string
	}
	Auth struct {
		AuthMethod        []string
		AdminUsers        []string
		HelpDeskUsers     []string
		ReadOnlyUsers     []string
		APIReadOnlyUsers  []string
		APIReadWriteUsers []string
		APIStatusUsers    []string

		LDAP struct {
			Server             string
			Port               int
			UseSSL             bool
			InsecureSkipVerify bool
			SkipTLS            bool
			DomainName         string
		}
		Radius struct {
			Servers []string
			Port    int
			Secret  string
		}
		CAS struct {
			Server string
		}
		Openid struct {
			Server           string
			ClientID         string
			ClientSecret     string
			AuthorizeEndoint string `toml:"-"`
			TokenEndoint     string `toml:"-"`
			UserinfoEndpoint string `toml:"-"`
		}
	}
	DHCP struct {
		ConfigFile string
	}
	Email struct {
		Address     string
		Port        int
		Username    string
		Password    string
		FromAddress string
		ToAddresses []string
	}
	// contains filtered or unexported fields
}

Config defines the configuration struct for the application

func NewConfig

func NewConfig(configFile string) (conf *Config, err error)

NewConfig reads the given filename into a Config. If filename is empty, the config is looked for in the documented order.

func NewEmptyConfig

func NewEmptyConfig() *Config

NewEmptyConfig returns an empty config with type defaults only.

type DataFunc added in v1.6.0

type DataFunc func(*http.Request) interface{}

type DatabaseAccessor

type DatabaseAccessor struct {
	*sql.DB
	Driver string
}

DatabaseAccessor wraps an sql.DB with a driver string.

func (*DatabaseAccessor) SchemaVersion added in v1.3.0

func (d *DatabaseAccessor) SchemaVersion() int

SchemaVersion queries the database and returns the current version.

type Environment

type Environment struct {
	Sessions *SessionStore
	DB       *DatabaseAccessor
	Config   *Config
	Views    *Views
	Env      EnvironmentEnv
	Log      *Logger
	// contains filtered or unexported fields
}

Environment holds "global" application information such as a database connection, logging, the config, sessions, etc.

func GetEnvironmentFromContext

func GetEnvironmentFromContext(r *http.Request) *Environment

GetEnvironmentFromContext retrieves the Environment from the current request.

func NewEnvironment

func NewEnvironment(t EnvironmentEnv) *Environment

NewEnvironment creates an environment.

func NewTestEnvironment

func NewTestEnvironment() *Environment

NewTestEnvironment creates and environment setup for testing.

func (*Environment) IsDev added in v0.8.0

func (e *Environment) IsDev() bool

IsDev checks if the current environment is development

func (*Environment) IsProd added in v0.8.0

func (e *Environment) IsProd() bool

IsProd checks if the current environment is production

func (*Environment) IsTesting added in v0.8.0

func (e *Environment) IsTesting() bool

IsTesting checks if the current environment is testing

func (*Environment) SubscribeShutdown added in v1.1.0

func (e *Environment) SubscribeShutdown() <-chan bool

SubscribeShutdown returns a channel that the caller can block on. The channel will receive a value when the application receives a shutdown signal.

type EnvironmentEnv added in v0.8.0

type EnvironmentEnv string

EnvironmentEnv is an environment type

const (
	EnvTesting EnvironmentEnv = "testing"
	EnvProd    EnvironmentEnv = "production"
	EnvDev     EnvironmentEnv = "development"
)

Indicates what environment the software is running in

type Key

type Key int

Key is for contexts

const (
	SessionKey     Key = 0
	SessionUserKey Key = 1
	SessionEnvKey  Key = 2
	SessionIPKey   Key = 3
)

Session values keys

type Logger

type Logger struct {
	*verbose.Logger
	// contains filtered or unexported fields
}

Logger wraps a verbose.Logger with a config and timer.

var SystemLogger *Logger

SystemLogger application wide logger.

func NewEmptyLogger

func NewEmptyLogger() *Logger

NewEmptyLogger creates a null logger.

func NewLogger

func NewLogger(c *Config, name string) *Logger

NewLogger creates a standard logger with console and file logging.

func (*Logger) GetLogger

func (l *Logger) GetLogger(name string) *Logger

GetLogger returns a new Logger based on its parent but with a new name This can be used to separate logs from different sub-systems.

func (*Logger) StartTimer added in v0.8.0

func (l *Logger) StartTimer(name string)

StartTimer starts a named timer on this logger.

func (*Logger) StopTimer added in v0.8.0

func (l *Logger) StopTimer(name string)

StopTimer stops a named timer on this logger.

type Options added in v1.0.0

type Options struct {
	Path      string
	Domain    string
	MaxAge    int
	Secure    bool
	HTTPOnly  bool
	TableName string
}

Options to control the session cookie

type Session

type Session struct {
	*sessions.Session
}

Session is a wrapper around Gorilla sessions to provide access methods

func GetSessionFromContext

func GetSessionFromContext(r *http.Request) *Session

GetSessionFromContext retrieves the Session from the current request.

func NewTestSession

func NewTestSession() *Session

NewTestSession creates a session for testing.

func (*Session) Delete

func (s *Session) Delete(r *http.Request, w http.ResponseWriter) error

Delete a session.

func (*Session) Get

func (s *Session) Get(key interface{}, def ...interface{}) interface{}

Get a value from the session object

func (*Session) GetBool

func (s *Session) GetBool(key interface{}, def ...bool) bool

GetBool takes the same arguments as Get but def must be a bool type.

func (*Session) GetInt

func (s *Session) GetInt(key interface{}, def ...int) int

GetInt takes the same arguments as Get but def must be an int type.

func (*Session) GetInt64 added in v0.8.0

func (s *Session) GetInt64(key interface{}, def ...int64) int64

GetInt64 takes the same arguments as Get but def must be an int type.

func (*Session) GetString

func (s *Session) GetString(key interface{}, def ...string) string

GetString takes the same arguments as Get but def must be a string type.

func (*Session) Set

func (s *Session) Set(key, val interface{})

Set a value to the session object

type SessionStore

type SessionStore struct {
	sessions.Store
	// contains filtered or unexported fields
}

SessionStore wraps a Gorilla session and adds extra functionality.

func NewSessionStore

func NewSessionStore(e *Environment) (*SessionStore, error)

NewSessionStore creates a new store based the application configuration.

func (*SessionStore) GetSession

func (s *SessionStore) GetSession(r *http.Request) *Session

GetSession returns a session based on the http request.

type SystemInitFunc added in v1.3.0

type SystemInitFunc func(*Environment) error

SystemInitFunc is a function to be run at the start of the application.

type TestStore

type TestStore struct{}

TestStore is a mock session store for testing.

func (*TestStore) Get

func (t *TestStore) Get(r *http.Request, name string) (*sessions.Session, error)

Get session

func (*TestStore) New

func (t *TestStore) New(r *http.Request, name string) (*sessions.Session, error)

New session

func (*TestStore) Save

Save session

type View

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

View represents a template associated with a specific request.

func (*View) Render

func (v *View) Render(w http.ResponseWriter, data map[string]interface{})

Render executes the template and writes it to w. This function will also save a web session to the client if "username" is set in the current session.

type Views

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

Views is a collection of templates

func NewViews

func NewViews(e *Environment, basepath string) (v *Views, err error)

NewViews reads a set of templates from a directory and loads them into a Views. Custom functions are injected into the templates.

func (*Views) InjectData added in v1.6.0

func (v *Views) InjectData(key string, val interface{})

InjectData will always inject a specific key, value pair into every template

func (*Views) InjectDataFunc added in v1.6.0

func (v *Views) InjectDataFunc(key string, fn DataFunc)

InjectData will always inject a specific key, value pair into every template

func (*Views) NewView

func (v *Views) NewView(file string, r *http.Request) *View

NewView returns a template associated with a request.

func (*Views) Reload

func (v *Views) Reload() error

Reload replaces the Views object with a new one using the same source directory. DO NOT call this function in production. This functions should only be called in a development environment. This functions is very susceptible to race conditions.

func (*Views) RenderError

func (v *Views) RenderError(w http.ResponseWriter, r *http.Request, data map[string]interface{})

RenderError renders an error template with the given data. If data is nil, the generic "error" template is used. If data is not nil, "custom-error" is used.

Jump to

Keyboard shortcuts

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