webmgmt

package module
v0.0.0-...-4650de8 Latest Latest
Warning

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

Go to latest
Published: May 23, 2022 License: Apache-2.0 Imports: 31 Imported by: 0

README

WebMgmt

This library provides an easy way to embed a command execution shell to an existing service application. The execution shell is access via a web browser at a specific url path. Authentication can be implemented or bypassed to allow all to access. Configuration can set UI features such as prompt can be configured. Command functions can be defined so that when the client sends a command with arguments the function is invoked with the parsed command line.

Command func

This is example of using flags to set a field, if the command is invoked with the -help flag, then the help output is displayed.


func lines(client webmgmt.Client, args *webmgmt.CommandArgs, out io.Writer) (err error) {
	cnt := args.FlagSet.Int("cnt", 5, "number of lines to print")
	err = args.Parse()
	if err != nil {
		return
	}

	client.Send(webmgmt.AppendText(fmt.Sprintf("lines invoke"), "green"))
	log.Printf("lines invoked")
	for i := 0; i < *cnt; i++ {
		client.Send(webmgmt.AppendText(fmt.Sprintf("line[%d]", i), "green"))
	}
	return
}

Here the command is defined in the Map of Commands. Within the Command struct Help along with the ExecLevel can be set.

	cmd = &webmgmt.Command{Exec: lines, ExecLevel:webmgmt.ALL, Help: "Displays N lines of text"}
	webmgmt.Commands["lines"] = cmd

Details

this project will allow for a web admin service to be embedded into a service. This will allow clients to open a browser to the access port and login to the service. Commands can be developed to access the server.

Web

html terminal assets borrowed from https://github.com/tautvilas/termpage

Building & Running

There is a sample web terminal that is embedded in a test application. The source resides in ./example. To build the project You can follow the steps below.


make binaries            - make bianries into bin dir
cd bin
./example

open browser to:  http://localhost:1099

You can login with username: alex password: bambam

Commands to try to enter

help                     - display the commands available.
user                     - display user info
http                     - display http headers/cookies
prompt                   - chanmge prompt
link                     - respond with a link that can be clicked on in terminal window
ticker                   - display a ticker that updates info to window periodically
image                    - display an image in the terminal window
raw                      - dsiplay an image along with a command tool bar of commands that can be clicked on
commands                 - display command tool bar of commands that can be clicked on
history                  - display history of commands executed


Initialization

  1. Create a Config struct and set the template path to ./web
  2. Set the DefaultPrompt
  3. Set the Webpath that will be used to access the terminal via a browser
   config := &webmgmt.Config{StaticHtmlDir: "./web"}
    config.DefaultPrompt = "$"
    config.WebPath = "/admin/"

ClientInitialization

The Client initialization func is invoked when a client connects to the system. The handler func can access and modify the client state. It has access the Misc() which is a Map available to save data for the client session.


    config.ClientInitializer = func(client webmgmt.Client) {
        client.Misc()["aa"] = 112
    }

WelcomeUser

The WelcomeUser func is invoked when the client connects. The Server has the ability to send ServerMessages to the client terminal. In the example below we send

  1. A welcome banner
  2. Set the Prompt
  3. The the authenticated state to the client
  4. Toggle the history mode for text sent from client to server to off.
  5. Toggle the echo text state for the client to true.

    config.WelcomeUser = func(client webmgmt.Client) {
        client.Send(webmgmt.AppendText("Welcome to the machine", "red"))
        client.Send(webmgmt.SetPrompt("Enter Username: "))
        client.Send(webmgmt.SetAuthenticated(false))
        client.Send(webmgmt.SetHistoryMode(false))
        client.Send(webmgmt.SetEchoOn(true))

    }

Authentication

  1. Set the User Auth function, This function will have access to the Client interface, where you can access the IP, http Request etc. The submitted username and password will also be passed to validate the session. Function returns the state of authentication

    config.UserAuthenticator = func(client webmgmt.Client, username string, password string) bool {
        return username == "alex" && password == "bambam"
    }

Post Authentication

The NotifyClientAuthenticated func is invoked when a client is authenticated. This can be used for logging purposes.

    config.NotifyClientAuthenticated= func(client webmgmt.Client) {

        client.Send(webmgmt.SetPrompt("$ "))
        loge.Info("New user authenticated on system: %v", client.Username())
    }

Post Authentication Failure

The NotifyClientAuthenticatedFailed func is invoked when a client fails authentication. It will be invoked after the client is disconnected. . This can be used for logging purposes.

    config.NotifyClientAuthenticatedFailed= func(client webmgmt.Client) {
        loge.Info("user auth failed on system: %v - %v", client.Username(), client.Ip())
    }

Client command handling

Below is adding of commands that will be available to be executed. A webmgmt.Command struct is used to store a reference to the func To be executed, The Help text, along with the ExecRights needed to execute the command. Several commands are added by default such as help or cls. The help command with look at the clients ExecRights to see if they have access to exec that command. The func that is defined for the command has access to the client, to send them ServerMessages.

	cmd = &webmgmt.Command{Exec: func(client webmgmt.Client, args *webmgmt.CommandArgs, out io.Writer) (err error) {
		client.Send(webmgmt.AppendRawText(webmgmt.Image(200, 200, "https://avatars1.githubusercontent.com/u/174203?s=200&v=4", "me"), nil))
		return
	}, Help: "Returns raw html to display image in terminal"}
	webmgmt.Commands["image"] = cmd

	cmd = &webmgmt.Command{Exec: func(client webmgmt.Client, args *webmgmt.CommandArgs, out io.Writer) (err error) {
		client.Send(webmgmt.AppendRawText(webmgmt.Link("http://www.slashdot.org", webmgmt.Color("orange", "slashdot")), nil))
		return
	}, Help: "Displays clickable link in terminal"}
	webmgmt.Commands["link"] = cmd

	cmd = &webmgmt.Command{Exec: func(client webmgmt.Client, args *webmgmt.CommandArgs, out io.Writer) (err error) {
		client.Send(webmgmt.SetPrompt(webmgmt.Color("red", client.Username()) + "@" + webmgmt.Color("green", "myserver") + ":&nbsp;"))
		return
	}, Help: "Updates the prompt to a multi colored prompt"}
	webmgmt.Commands["prompt"] = cmd

Client Disconnect

The Unregister function is invoked when a client websocket is broken, such as when the client is shut down, or navigates away from the web terminal.

    config.UnregisterUser = func(client webmgmt.Client) {
        loge.Info("user logged off system: %v", client.Username())
    }

Creation

The NewMgmtApp func will create a new web terminal with the Config supplied and attach it to the http.Router passed in. The Name and instanceId are used to set the "X-Server-Name" and "X-Server-Id" headers on the http server. This can be useful to identifying servers behind a load balancer. An error will be returned if initialization fails.


    mgmtApp, err = webmgmt.NewMgmtApp("testapp", "1", config, router)

Config

The following fields are used to initialize the WebMgmt command server.


// Config struct  is used to configure a WebMgmt admin handler.
type Config struct {
	StaticHtmlDir                   string
	DefaultPrompt                   string
	WebPath                         string
	UserAuthenticator               func(client Client, username string, password string) bool
	HandleCommand                   func(c Client, cmd string)
	NotifyClientAuthenticated       func(client Client)
	NotifyClientAuthenticatedFailed func(client Client)
	WelcomeUser                     func(client Client)
	UnregisterUser                  func(client Client)
	ClientInitializer               func(client Client)
}
StaticHtmlDir       Used to define where assets are located. If the field is not set or not a directory, then the 
                    embedded assets are used.
                    
DefaultPrompt       prompt that should be displayed in the terminal.
WebPath             http routing path to access the web terminal
UserAuthenticator   function to be invoked to authorize a user. The return value is the authenticated state
HandleCommand       function to be invoked when a command is submitted to the server. By default a handler function
                    that validates the clients ExecLevel. If the client does not have access to a command then the
                    client will receive a response indicating they do not have rights to execute.  If a command is
                    not available then an error is sent. Otherwise the command is executed. Commands are case sensitive.
                    This can be set if the developer needed additional functionality such as logging etc.
NotifyClientAuthenticated This is invoked when a client is authenticated. Can be used for logging this information etc.
notifyClientAuthenticatedFailed This is invoked when a client has failed 3 password attempts for a username. The client 
                    is already disconnected. This can be used for logging etc.

Html Assets

The webmgmt uses several html and js resources that are delivered to the client. They are embedded into the webmgmt library with the use of embed that can mimic a filesystem, while the assets are encoded into a go file via the packr command. Users of the library can set a directory to be used instead of the embedded assets. There is a utility method
func webmgmt.SaveAssets(outputDir string) error This will save all assets into a directory specified. Then a developer can customize the assets. In webmgmt.Config the field StaticHtmlDir if defined and it exists will be used to serve assets from. If that field is not set or does not exist the embedded assets will be used.

Example App

In this snippet we use a flag passed to the app to write out assets so that they can be customized.

    var saveTemplateDir string

	flag.StringVar(&saveTemplateDir, "save", "", "save assets to directory")

	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "Usage: %s [options] \n", os.Args[0])
		flag.PrintDefaults()
	}

	flag.Parse()


	if saveTemplateDir != "" {
		err = webmgmt.SaveAssets(saveTemplateDir)
		if err != nil {
			loge.Printf("Error writing assets: %v", err)
			os.Exit(-1)
		}
	}

ServerMessages

Server sends json payloads via the websocket to the client terminal. The Client terminal will process the ServerMessages to trigger begaviors within the client terminal. Such as display text, clear screen, render html, eval javascript code etc.

// TextMessaage is the json for the server message that is sent to the client to tell the client to display text in the terminal window.
{
	type="text",
	text="Hello World",
	color="red"
}


// RawTextMessage is the struct for the server message that is sent to the client to tell the client to display text as raw text in the terminal window.
{
	type="rawtext",
	text="<a href=....",
}

// Prompt is the struct for the server message that is sent to the client to tell the client what the prompt should be
{
	type="prompt",
	prompt=" > $ "
}


// HistoryMode is the struct for the server message that is sent to the client to tell the client to turn history saving on and off.
{
	type="history",
	val=true
}


// Authenticated is the struct for the server message that is sent to the client to tell the client that is has been authenticated or not.
{
	type="authenticated",
	val=true
}


// Echo is the struct for the server message that is sent to the client to tell the client to turn echo on or off.
{
	type="echo",
	val=true
}


// Status is the struct for the server message that is sent to the client to tell the client to set the status bar to the text defined in the message.
{
	type="status",
	text="Custom Status Text"
}


// cls is the struct for the server message that is sent to the client to tell the client to set the status bar to the text defined in the message.
{
	type="cls",
}

// Eval is the struct for the server message that is sent to the client to tell the client to call js.eval on the val set.
{
	type="eval",
	text="alert('hello world');"
}



The webmgmt has several utility functions that will create the various ServerMessages structs to send to the client.

Acknowledgements

Original inspiration was taken from https://github.com/tautvilas/termpage I hacked upon the js code to add functionality needed to create various ServerMessages to manipulate the web terminal from the server. The original assets are located under [./web]

TODO

Implement a StatusBar within the web ui. The ServerMessage is defined just needs someone with js/css styling skills.

Documentation

Index

Constants

View Source
const ADMIN = ExecLevel(2)

ADMIN level for admin users

View Source
const ALL = ExecLevel(0)

ALL level for all users

View Source
const USER = ExecLevel(1)

USER level for default users

Variables

View Source
var (

	// NormalOutputColor color definition for normal output
	NormalOutputColor = "white"

	// ErrorOutputColor color definition for error output
	ErrorOutputColor = "red"
)
View Source
var ClsCommand = &Command{Use: "cls", Exec: func(client Client, args *CommandArgs) (err error) {
	client.Send(Cls())
	return
}, Short: "send cls event to terminal client", ExecLevel: ALL}

ClsCommand command to clear web screen

View Source
var DefaultCommands = &Command{ExecLevel: ALL}

DefaultCommands main struct for all commands

View Source
var DefaultWebEmbedFS embed.FS

DefaultWebEmbedFS embedded assets

View Source
var EnableCommandSorting = true

EnableCommandSorting controls sorting of the slice of commands, which is turned on by default. To disable sorting, set it to false.

View Source
var ForegroundColor = "white"

ForegroundColor default foreground color definition

View Source
var HistoryCommand = &Command{Use: "history", Exec: displayHistory, Short: "Show the history of commands executed", ExecLevel: ALL}

HistoryCommand command to view history of commands executed

View Source
var HttpCommand = &Command{Use: "http", Exec: displayHttpInfo, Short: "Display http request information", ExecLevel: ALL}

HttpCommand command to view http session details

View Source
var UserCommand = &Command{Use: "user", Exec: displayUserInfo, Short: "Show user details about logged in user", ExecLevel: ALL}

UserCommand command to view user details

View Source
var WebFS fs.FS

Functions

func CheckPasswordHash

func CheckPasswordHash(password, hash string) bool

CheckPasswordHash plain password with hash password

func Color

func Color(color, text string) string

Color is used to a color string and return a string containing the color for a span.

func GenerateHashPassword

func GenerateHashPassword(password string) (string, error)

GenerateHashPassword password as input and generate new hash password from it

func HandleCommands

func HandleCommands(Commands *Command) (handler func(Client, string))

HandleCommands handler function to execute commands

func Image

func Image(width, height int, src, alt string) string

Image is used to take several predefined fields and return a html snippet to display an image.

func InitGin

func InitGin(app *MgmtApp, router *gin.Engine, webPath string, fileSystem fs.FS) error

InitGin will initialize the Router with the admin web app. It registers the webapp and assets file handler to be under the WebPath config field.

func InitMuxRouter

func InitMuxRouter(app *MgmtApp, router *mux.Router, webPath string, fileSystem fs.FS) error

InitMuxRouter will initialize the Router with the admin web app. It registers the webapp and assets file handler to be under the WebPath config field.

func Link(url, text string) string

Link is used to format a string for a href tag

func ServeProxy

func ServeProxy(app *MgmtApp, webPath string, filesProxy http.Handler) gin.HandlerFunc

Types

type Authenticated

type Authenticated struct {
	ServerMessageBase
	Val bool `json:"val"`
}

Authenticated is the struct for the server message that is sent to the client to tell the client that is has been authenticated or not.

func (*Authenticated) Get

func (c *Authenticated) Get() interface{}

Get will return self

type Authentication

type Authentication struct {
	Email    string `json:"email"`
	Password string `json:"password"`
}

Authentication struct

type Authr

type Authr struct {
	SecretKey string "secretkeyjwt"
}

Authr struct

func InitializeAuthGin

func InitializeAuthGin(prefix string, router *gin.Engine) (a *Authr)

InitializeAuthGin all auth routes for gin router

func InitializeAuthMux

func InitializeAuthMux(prefix string, router *mux.Router) (a *Authr)

InitializeAuthMux all auth routes

func (*Authr) AdminIndex

func (a *Authr) AdminIndex(w http.ResponseWriter, r *http.Request)

AdminIndex ROUTE HANDLER

func (*Authr) CloseDatabase

func (a *Authr) CloseDatabase(connection *gorm.DB)

CloseDatabase database connection

func (*Authr) GenerateJWT

func (a *Authr) GenerateJWT(email, role string) (string, error)

GenerateJWT JWT token

func (*Authr) GetDatabase

func (a *Authr) GetDatabase() *gorm.DB

GetDatabase database connection

func (*Authr) Index

func (a *Authr) Index(w http.ResponseWriter, r *http.Request)

Index ROUTE HANDLER

func (*Authr) InitialMigration

func (a *Authr) InitialMigration()

InitialMigration user table in userdb

func (*Authr) IsAuthorized

func (a *Authr) IsAuthorized(handler http.HandlerFunc) http.HandlerFunc

IsAuthorized whether user is authorized or not

func (*Authr) SignIn

func (a *Authr) SignIn(w http.ResponseWriter, r *http.Request)

SignIn ROUTE HANDLER

func (*Authr) SignUp

func (a *Authr) SignUp(w http.ResponseWriter, r *http.Request)

SignUp ROUTE HANDLER

func (*Authr) UserIndex

func (a *Authr) UserIndex(w http.ResponseWriter, r *http.Request)

UserIndex ROUTE HANDLER

type BuildInfo

type BuildInfo struct {
	// AppBuildInfo build information
	BuildDate string

	// LatestCommit build information
	LatestCommit string

	// BuildNumber build information
	BuildNumber string

	// BuiltOnIp build information
	BuiltOnIp string

	// BuiltOnOs build information
	BuiltOnOs string

	// RuntimeVer build information
	RuntimeVer string
}

BuildInfo is used to define the application build info, and inject values into via the build process.

var (
	// AppBuildInfo build information
	AppBuildInfo *BuildInfo
)

type Clickable

type Clickable struct {
	ServerMessageBase
	Commands []string `json:"commands"`
}

Clickable is the struct for the server message that is sent to the client to tell the client to display clickable.

func (*Clickable) Get

func (c *Clickable) Get() interface{}

Get will return self

type Client

type Client interface {
	IsAuthenticated() bool
	IsConnected() bool
	Username() string
	Send(msg ServerMessage)
	History() []string
	HttpReq() *http.Request
	Misc() map[string]interface{}
	Ip() string
	ExecLevel() ExecLevel
	SetExecLevel(level ExecLevel)
	StdOut() io.Writer
	StdErr() io.Writer
}

Client is the interface a WebSocket client will implement. It provides access to the authenticated state as well as ability to send it a ServerMessage to be processed on the MgmtApp.

type ClientMessage

type ClientMessage struct {
	Payload string `json:"payload"`
}

ClientMessage is the struct for the client message that is sent from the client to the server. nThe contents are passed to the HandleCommand func(c Client, cmd string) defined in the Config.

func ConvertBytesToMessage

func ConvertBytesToMessage(payload []byte) (*ClientMessage, error)

ConvertBytesToMessage converts a byte slice to CLientMessage via json unmarshalling

type Command

type Command struct {
	Exec CommandFunc

	// Use is the word to execute the command
	Use string

	// Short is the short description shown in the 'help' output.
	Short string

	// Long is the long message shown in the 'help <this-command>' output.
	Long string

	// Example is examples of how to use the command.
	Example string

	// Hidden defines, if this command is hidden and should NOT show up in the list of available commands.
	Hidden bool
	// Version defines the version for this command. If this value is non-empty and the command does not
	// define a "version" flag, a "version" boolean flag will be added to the command and, if specified,
	// will print content of the "Version" variable.
	Version string

	// Deprecated defines, if this command is deprecated and should print this string when used.
	Deprecated string

	ExecLevel ExecLevel

	// DisableSuggestions disables the suggestions based on Levenshtein distance
	// that go along with 'unknown command' messages.
	DisableSuggestions bool
	// SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions.
	// Must be > 0.
	SuggestionsMinimumDistance int
	// SuggestFor is an array of command names for which this command will be suggested -
	// similar to aliases but only suggests.
	SuggestFor []string

	FlagSet  *flag.FlagSet
	HasFlags bool
	// contains filtered or unexported fields
}

Command is just that, a command for your application. E.g. 'go run ...' - 'run' is the command. Cobra requires you to define the usage and description as part of your command definition to ensure usability.

func (*Command) AddCommand

func (c *Command) AddCommand(cmds ...*Command)

AddCommand adds one or more commands to this parent command.

func (*Command) CommandPath

func (c *Command) CommandPath() string

CommandPath returns the full path to this command.

func (*Command) CommandPathPadding

func (c *Command) CommandPathPadding() int

CommandPathPadding return padding for the command path.

func (*Command) Commands

func (c *Command) Commands() []*Command

Commands returns a sorted slice of child commands.

func (*Command) Execute

func (c *Command) Execute(client Client, cmdLine *CommandArgs)

Execute runs a command thru execution

func (*Command) HasAvailableSubCommands

func (c *Command) HasAvailableSubCommands() bool

HasAvailableSubCommands determines if a command has available sub commands that need to be shown in the usage/help default template under 'available commands'.

func (*Command) HasExample

func (c *Command) HasExample() bool

HasExample determines if the command has example.

func (*Command) HasHelpSubCommands

func (c *Command) HasHelpSubCommands() bool

HasHelpSubCommands determines if a command has any available 'help' sub commands that need to be shown in the usage/help default template under 'additional help topics'.

func (*Command) HasParent

func (c *Command) HasParent() bool

HasParent determines if the command is a child command.

func (*Command) HasSubCommands

func (c *Command) HasSubCommands() bool

HasSubCommands determines if the command has children commands.

func (*Command) Help

func (c *Command) Help(client Client) error

Help puts out the help for the command. Used when a user calls help [command]. Can be defined by user by overriding HelpFunc.

func (*Command) HelpFunc

func (c *Command) HelpFunc() func(*Command, []string, Client)

HelpFunc returns either the function set by SetHelpFunc for this command or a parent, or it returns a function with default help behavior.

func (*Command) HelpTemplate

func (c *Command) HelpTemplate() string

HelpTemplate return help template for the command.

func (*Command) IsAdditionalHelpTopicCommand

func (c *Command) IsAdditionalHelpTopicCommand() bool

IsAdditionalHelpTopicCommand determines if a command is an additional help topic command; additional help topic command is determined by the fact that it is NOT runnable/hidden/deprecated, and has no sub commands that are runnable/hidden/deprecated. Concrete example: https://github.com/spf13/cobra/issues/393#issuecomment-282741924.

func (*Command) IsAvailableCommand

func (c *Command) IsAvailableCommand() bool

IsAvailableCommand determines if a command is available as a non-help command (this includes all non deprecated/hidden commands).

func (*Command) IsSubCommandAvailable

func (c *Command) IsSubCommandAvailable(client Client, cmd string) bool

IsSubCommandAvailable checks if sub command exists

func (*Command) Name

func (c *Command) Name() string

Name returns the command's name: the first word in the use line.

func (*Command) NamePadding

func (c *Command) NamePadding() int

NamePadding returns padding for the name.

func (*Command) Parent

func (c *Command) Parent() *Command

Parent returns a commands parent command.

func (*Command) RemoveCommand

func (c *Command) RemoveCommand(cmds ...*Command)

RemoveCommand removes one or more commands from a parent command.

func (*Command) Runnable

func (c *Command) Runnable() bool

Runnable determines if the command is itself runnable.

func (*Command) SetHelpCommand

func (c *Command) SetHelpCommand(cmd *Command)

SetHelpCommand sets help command.

func (*Command) SetHelpFunc

func (c *Command) SetHelpFunc(f func(*Command, []string, Client))

SetHelpFunc sets help function. Can be defined by Application.

func (*Command) SetHelpTemplate

func (c *Command) SetHelpTemplate(s string)

SetHelpTemplate sets help template to be used. Application can use it to set custom template.

func (*Command) SuggestionsFor

func (c *Command) SuggestionsFor(typedName string) []string

SuggestionsFor provides suggestions for the typedName.

func (*Command) Usage

func (c *Command) Usage(io io.Writer) error

Usage puts out the usage for the command. Used when a user provides invalid input. Can be defined by user by overriding UsageFunc.

func (*Command) UsageFunc

func (c *Command) UsageFunc() (f func(*Command, io.Writer) error)

UsageFunc returns either the function set by SetUsageFunc for this command or a parent, or it returns a default usage function.

func (*Command) UsagePadding

func (c *Command) UsagePadding() int

UsagePadding return padding for the usage.

func (*Command) UsageString

func (c *Command) UsageString() string

UsageString returns usage string.

func (*Command) UsageTemplate

func (c *Command) UsageTemplate() string

UsageTemplate returns usage template for the command.

func (*Command) UseLine

func (c *Command) UseLine() string

UseLine puts out the full usage for a given command (including parents).

func (*Command) VersionTemplate

func (c *Command) VersionTemplate() string

VersionTemplate return version template for the command.

type CommandArgs

type CommandArgs struct {
	CmdLine string
	CmdName string
	Args    []string
	FlagSet *flag.FlagSet
	// contains filtered or unexported fields
}

CommandArgs is a struct that is used to store the contents of a parsed command line string.

func NewCommandArgs

func NewCommandArgs(cmdLine string, output io.Writer) (*CommandArgs, error)

NewCommandArgs will take a raw string and output. The Raw string will be parsed into a CommandArgs structure. If an error is encountered such as empty command string it will be returned and the CommandArgs will be nil.

func (*CommandArgs) Debug

func (c *CommandArgs) Debug() string

Debug will return a string listing the original command line and the parsed arguments and flags

func (*CommandArgs) Parse

func (c *CommandArgs) Parse() error

Parse will use the defined FlagSet parsed and return an error if help is invoked or invalid flags

func (*CommandArgs) PealOff

func (c *CommandArgs) PealOff(pos int) string

PealOff will return a command line string after N commands have been pealed off from the front of the command line.

func (*CommandArgs) Shift

func (c *CommandArgs) Shift() (*CommandArgs, error)

Shift will return a new CommandArgs after shifting the first cmd in the string

func (*CommandArgs) String

func (c *CommandArgs) String() string

String will return the CmdLine the original one that is parsed.

type CommandFunc

type CommandFunc func(client Client, args *CommandArgs) error

CommandFunc function definition for a command

type Config

type Config struct {
	DefaultPrompt string

	UserAuthenticator               func(client Client, username string, password string) bool
	HandleCommand                   func(c Client, cmd string)
	NotifyClientAuthenticated       func(client Client)
	NotifyClientAuthenticatedFailed func(client Client)
	WelcomeUser                     func(client Client)
	UnregisterUser                  func(client Client)
	ClientInitializer               func(client Client)
}

Config struct is used to configure a WebMgmt admin handler.

func (*Config) Display

func (cfg *Config) Display()

Display is used to display the config

type Echo

type Echo struct {
	ServerMessageBase
	Val bool `json:"val"`
}

Echo is the struct for the server message that is sent to the client to tell the client to turn echo on or off.

func (*Echo) Get

func (c *Echo) Get() interface{}

Get will return self

type Error

type Error struct {
	IsError bool   `json:"isError"`
	Message string `json:"message"`
}

Error struct

func SetError

func SetError(err Error, message string) Error

SetError error message in Error struct

type ExecLevel

type ExecLevel int32

ExecLevel type for admin levels

type HistoryMode

type HistoryMode struct {
	ServerMessageBase
	Val bool `json:"val"`
}

HistoryMode is the struct for the server message that is sent to the client to tell the client to turn history saving on and off.

func (*HistoryMode) Get

func (c *HistoryMode) Get() interface{}

Get will return self

type Hub

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

Hub maintains the set of active clients and broadcasts messages to the clients.

func (*Hub) Broadcast

func (h *Hub) Broadcast(msg ServerMessage)

Broadcast sill send a ServerMessage to all users on the System.

type MgmtApp

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

MgmtApp struct is the web admin app.

func NewMgmtApp

func NewMgmtApp(config *Config) (*MgmtApp, error)

NewMgmtApp will create a new web mgmt web handler with the Config passed in, Various funcs can be overwritten for authentication, welcome etc. If an error is encountered, it will be returned

func (*MgmtApp) Broadcast

func (app *MgmtApp) Broadcast(msg ServerMessage)

Broadcast will take a ServerMessage and send to all clients that are currently connected.

type NewPathFS

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

func (*NewPathFS) Open

func (p *NewPathFS) Open(name string) (fs.File, error)

type Prompt

type Prompt struct {
	ServerMessageBase
	Prompt string `json:"prompt"`
}

Prompt is the struct for the server message that is sent to the client to tell the client what the prompt should be

func (*Prompt) Get

func (c *Prompt) Get() interface{}

Get will return self

type RawTextMessage

type RawTextMessage struct {
	ServerMessageBase
	Text string `json:"text"`
}

RawTextMessage is the struct for the server message that is sent to the client to tell the client to display text as raw text in the terminal window.

func (*RawTextMessage) Get

func (c *RawTextMessage) Get() interface{}

Get will return self

type ServerMessage

type ServerMessage interface {
	Get() interface{}
}

ServerMessage is the interface that all messages from the server to client will implement.

func AppendErrorText

func AppendErrorText(format string, a ...interface{}) ServerMessage

AppendErrorText create a ServerMessage for TextMessage error, format and args are used to create the text via Sprintf

func AppendNormalText

func AppendNormalText(format string, a ...interface{}) ServerMessage

AppendNormalText create a ServerMessage for TextMessage normal, format and args are used to create the text via Sprintf

func AppendRawText

func AppendRawText(text string) ServerMessage

AppendRawText will return a command packet that will append the raw text to the bottom of the output in the web terminal

func AppendText

func AppendText(text, color string) ServerMessage

AppendText will return a command packet that will append the text to the bottom of the output in the web terminal. This will format the text message in the color defined.

func ClickableCommands

func ClickableCommands(commands []string) ServerMessage

ClickableCommands will return a command packet that will append the raw text to the bottom of the output in the web terminal

func Cls

func Cls() ServerMessage

Cls will return a command packet that will clear the current browser.

func Eval

func Eval(text string) ServerMessage

Eval will return a command packet that will be evaluated on the client browser. The text is the javascript that will be evaluated.

func SetAuthenticated

func SetAuthenticated(val bool) ServerMessage

SetAuthenticated will return a command packet that will notify the web terminal that the client has authenticated.

func SetEchoOn

func SetEchoOn(val bool) ServerMessage

SetEchoOn will return a command packet that will set the echo state of text that is executed. Useful for disabling the display of the password entry in the auth process.

func SetHistoryMode

func SetHistoryMode(val bool) ServerMessage

SetHistoryMode will return a command packet that will notify the web terminal that should capture/not capture commands entered into the client's history/

func SetPrompt

func SetPrompt(prompt string) ServerMessage

SetPrompt will return a command packet that will set the prompt in the web terminal.

func SetStatus

func SetStatus(text string) ServerMessage

SetStatus will return a command packet that will set the status in the html window. This is yet to be implemented on the client.

type ServerMessageBase

type ServerMessageBase struct {
	Type string `json:"type"`
}

ServerMessageBase is the base structure all server to client messages will use.

func (*ServerMessageBase) Get

func (c *ServerMessageBase) Get() interface{}

Get will return the ServerMessageBase

type Status

type Status struct {
	ServerMessageBase
	Text string `json:"text"`
}

Status is the struct for the server message that is sent to the client to tell the client to set the status bar to the text defined in the message.

func (*Status) Get

func (c *Status) Get() interface{}

Get will return self

type TextMessage

type TextMessage struct {
	ServerMessageBase
	Text  string `json:"text"`
	Color string `json:"color"`
}

TextMessage is the struct for the server message that is sent to the client to tell the client to display text in the terminal window.

func (*TextMessage) Get

func (c *TextMessage) Get() interface{}

Get will return self

type Token

type Token struct {
	Role        string `json:"role"`
	Email       string `json:"email"`
	TokenString string `json:"token"`
}

Token struct

type User

type User struct {
	gorm.Model
	Name     string `json:"name"`
	Email    string `gorm:"unique" json:"email"`
	Password string `json:"password"`
	Role     string `json:"role"`
}

User struct

type WSClient

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

WSClient is a middleman between the websocket connection and the hub.

func (*WSClient) ExecLevel

func (c *WSClient) ExecLevel() ExecLevel

ExecLevel returns exec level for the client

func (*WSClient) History

func (c *WSClient) History() []string

History returns the slice of commands that have been sent from the client to the server, for the existing client connection

func (*WSClient) HttpReq

func (c *WSClient) HttpReq() *http.Request

HttpReq returns Request for the current client to be able to access headers, cookies etc

func (*WSClient) Ip

func (c *WSClient) Ip() string

Ip returns ip for the client

func (*WSClient) IsAuthenticated

func (c *WSClient) IsAuthenticated() bool

IsAuthenticated returns the auth state of the client connection

func (*WSClient) IsConnected

func (c *WSClient) IsConnected() bool

IsConnected returns the auth state of the client connection

func (*WSClient) Misc

func (c *WSClient) Misc() map[string]interface{}

Misc returns the map that can be used to attach data to a client connection

func (*WSClient) Send

func (c *WSClient) Send(msg ServerMessage)

Send push ServerMessage to client

func (*WSClient) SetExecLevel

func (c *WSClient) SetExecLevel(level ExecLevel)

SetExecLevel sets exec level for the client

func (*WSClient) StdErr

func (c *WSClient) StdErr() io.Writer

StdErr returns writer for the client

func (*WSClient) StdOut

func (c *WSClient) StdOut() io.Writer

StdOut returns writer for the client

func (*WSClient) Username

func (c *WSClient) Username() string

Username returns the username of the exiting client connection

func (*WSClient) WriteStdErr

func (c *WSClient) WriteStdErr(p []byte) (n int, err error)

WriteStdErr writes bytes out to client as error text

func (*WSClient) WriteStdOut

func (c *WSClient) WriteStdOut(p []byte) (n int, err error)

WriteStdOut writes bytes out to client as normal text

type WSClientWriter

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

WSClientWriter writer for clients

func (*WSClientWriter) Write

func (c *WSClientWriter) Write(p []byte) (n int, err error)

Write writer for clients

Directories

Path Synopsis
_test

Jump to

Keyboard shortcuts

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