diff --git a/Dockerfile b/Dockerfile index f329e50..84b1b05 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,8 +1,10 @@ FROM alpine:20231219 + # Set the appropriate timezone ENV TZ="Europe/Lisbon" + # Install the required packages RUN apk --no-cache add bash zsh go make sqlite \ && rm -rf /tmp/* @@ -13,7 +15,6 @@ COPY ./src /frontend-src # Add the entrypoint -USER $UNAME COPY ./container/start.sh /start.sh STOPSIGNAL SIGTERM ENTRYPOINT [ "/start.sh" ] diff --git a/src/.gitignore b/src/.gitignore index 567609b..865f78f 100644 --- a/src/.gitignore +++ b/src/.gitignore @@ -1 +1,2 @@ build/ +data.db diff --git a/src/cmd/root.go b/src/cmd/root.go new file mode 100644 index 0000000..f80651b --- /dev/null +++ b/src/cmd/root.go @@ -0,0 +1,51 @@ +/* +Copyright © 2024 NAME HERE +*/ +package cmd + +import ( + "os" + "thermalFax/config" + "thermalFax/server" + + "github.com/spf13/cobra" +) + +func rootCmdAction(cmd *cobra.Command, args []string) { + cfgPath, _ := cmd.Flags().GetString("config") + // Initialize configuration + // This runs a sync.Once + config.GetInstance(cfgPath, nil) + + server.Server() +} + +// rootCmd represents the base command when called without any subcommands +var rootCmd = &cobra.Command{ + Use: "thermalPrinter", + Short: "", + Long: ``, + Run: rootCmdAction, +} + +// Execute adds all child commands to the root command and sets flags appropriately. +// This is called by main.main(). It only needs to happen once to the rootCmd. +func Execute() { + err := rootCmd.Execute() + if err != nil { + os.Exit(1) + } +} + +func init() { + // Here you will define your flags and configuration settings. + // Cobra supports persistent flags, which, if defined here, + // will be global for your application. + + /* rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.thermalPrinter.yaml)") */ + + // Cobra also supports local flags, which will only run + // when this action is called directly. + /* rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") */ + rootCmd.Flags().StringP("config", "c", "", "Config file path") +} diff --git a/src/config/config.go b/src/config/config.go index a1ad49e..89b38df 100644 --- a/src/config/config.go +++ b/src/config/config.go @@ -38,27 +38,20 @@ type Configuration struct { } func findConfigFile() (string, error) { - log.Println("Trying XDG path") - XDGPATH := "~/.config/fax/config.yml" - if _, err := os.Stat(XDGPATH); err == nil { - log.Println("Found XDG config file.") - return XDGPATH, nil + configLocations := map[string]string{ + "XDG": "~/.config/fax/config.yml", + "RUNTIME": "~/.config.yml", + "ETC": "/etc/fax/config.yml", } - log.Println("Trying RUNTIME path") - RUNTIMEPATH := "./config.yml" - if _, err := os.Stat(RUNTIMEPATH); err == nil { - log.Println("Found runtime config file.") - return RUNTIMEPATH, nil - } - - log.Println("Trying ETC path") - ETCPATH := "/etc/fax/config.yml" - if _, err := os.Stat(ETCPATH); err == nil { - log.Println("Found etc config file.") - return ETCPATH, nil + for name, path := range configLocations { + if _, err := os.Stat(path); err == nil { + log.Printf("Found %s config file\n", name) + return path, nil + } } + log.Println("No default config file found.") return "", errors.New("could not find viable config file") } @@ -67,10 +60,12 @@ func GetInstance(path string, data []byte) *Configuration { instance = &Configuration{} if path == "" { + log.Println("No configuration file provided... Searching in default locations") var err error path, err = findConfigFile() if err != nil { - log.Fatal("Could not find a configuration file.") + log.Fatal("Could not find a configuration file. Terminating") + // We could print the correct places to add a configuration file here } } @@ -82,7 +77,6 @@ func GetInstance(path string, data []byte) *Configuration { } func (c *Configuration) loadConfiguration(data []byte) { - // Instead of opening this file we should be trying other paths first var file []byte if data != nil { file = data diff --git a/src/go.mod b/src/go.mod index bf673a6..bb1ac5f 100644 --- a/src/go.mod +++ b/src/go.mod @@ -4,8 +4,13 @@ go 1.22.2 require ( github.com/golang-jwt/jwt/v4 v4.5.0 - github.com/google/go-cmp v0.6.0 github.com/mattn/go-sqlite3 v1.14.22 + github.com/spf13/cobra v1.8.0 golang.org/x/crypto v0.22.0 gopkg.in/yaml.v2 v2.4.0 ) + +require ( + github.com/inconshreveable/mousetrap v1.1.0 // indirect + github.com/spf13/pflag v1.0.5 // indirect +) diff --git a/src/go.sum b/src/go.sum index ad1ad94..625f04f 100644 --- a/src/go.sum +++ b/src/go.sum @@ -1,12 +1,19 @@ +github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/golang-jwt/jwt/v4 v4.5.0 h1:7cYmW1XlMY7h7ii7UhUyChSgS5wUJEnm9uZVTGqOWzg= github.com/golang-jwt/jwt/v4 v4.5.0/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= -github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= -github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= +github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU= github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0= +github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho= +github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= +github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= golang.org/x/crypto v0.22.0 h1:g1v0xeRhjcugydODzvb3mEM9SQ0HGp9s/nh3COQ/C30= golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/src/main.go b/src/main.go index 0bc222c..9801fb9 100644 --- a/src/main.go +++ b/src/main.go @@ -1,53 +1,14 @@ package main import ( - "fmt" - "log" - "net/http" - "thermalFax/config" - "thermalFax/controllers" + "thermalFax/cmd" ) -func checkMethod(method string, r *http.Request) bool { - return r.Method == method -} - +/* +This works by calling the root command of cobra-cli. +That will handle the command-line flags we might want to pass. +On that root command we will do the initial setups and then launch the server. +*/ func main() { - // Initialize configuration - _ = config.GetInstance("", nil) - - // GET calls - http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - if !checkMethod(http.MethodGet, r) { - w.WriteHeader(http.StatusMethodNotAllowed) - return - } - - controllers.EditorPage(w, r) - }) - - // POST calls - http.HandleFunc("/send-fax", func(w http.ResponseWriter, r *http.Request) { - if !checkMethod(http.MethodPost, r) { - w.WriteHeader(http.StatusMethodNotAllowed) - return - } - - controllers.SendFax(w, r) - }) - - http.HandleFunc("/send-login", func(w http.ResponseWriter, r *http.Request) { - if !checkMethod(http.MethodPost, r) { - w.WriteHeader(http.StatusMethodNotAllowed) - return - } - - controllers.Authenticate(w, r) - }) - - // Serve the CSS and JS files, we might have to change this - http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir("assets")))) - - fmt.Println("Starting server on port 8083") - log.Fatal(http.ListenAndServe(":8083", nil)) + cmd.Execute() } diff --git a/src/models/basicAuth.go b/src/models/basicAuth.go deleted file mode 100644 index 6b002ba..0000000 --- a/src/models/basicAuth.go +++ /dev/null @@ -1,37 +0,0 @@ -package models - -// This isn't used anymore, will keep it here for a while, for reasons, its mine - -// pass -> $2y$08$ZBb/RxlrNHcA.YNasvGlhOeUmJVZe/clNelP4jwBpkpq/r4mE.lze -// func (a *Authentication) isAuthorised(user string, pass string) bool { -// p, ok := DATABASE[user] -// if !ok { -// return false -// } - -// err := bcrypt.CompareHashAndPassword([]byte(p), []byte(pass)) - -// return err == nil -// } - -// func (a *Authentication) Authenticate(w http.ResponseWriter, r *http.Request) bool { -// username, password, ok := r.BasicAuth() -// if !ok { -// log.Println("Log in failed") -// w.Header().Add("WWW-Authenticate", `Basic realm="Give username and password"`) -// w.WriteHeader(http.StatusUnauthorized) -// w.Write([]byte(`{"message": "No basic auth present"}`)) -// return false -// } - -// if !a.isAuthorised(username, password) { -// log.Printf("Log in failed: %s:%s", username, password) -// w.Header().Add("WWW-Authenticate", `Basic realm="Give username and password"`) -// w.WriteHeader(http.StatusUnauthorized) -// w.Write([]byte(`{"message": "Invalid username or password"}`)) -// return false -// } - -// log.Printf("User %s logged in successfully", username) -// return true -// } diff --git a/src/models/dbAccess.go b/src/models/dbAccess.go index a55c4c4..f21904f 100644 --- a/src/models/dbAccess.go +++ b/src/models/dbAccess.go @@ -6,15 +6,6 @@ import ( _ "github.com/mattn/go-sqlite3" ) -type DBAccess interface { - // I should make a query struct so that I can make generic structs - // And then slap them into different types of DBs - createq(query string) error - selectq(query string) error - deleteq(query string) error - updateq(query string) error -} - type Database struct { DB *sql.DB Path string diff --git a/src/server/server.go b/src/server/server.go new file mode 100644 index 0000000..91bb4c6 --- /dev/null +++ b/src/server/server.go @@ -0,0 +1,48 @@ +package server + +import ( + "log" + "net/http" + "thermalFax/controllers" +) + +func checkMethod(method string, r *http.Request) bool { + return r.Method == method +} + +func Server() { + // GET calls + http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + if !checkMethod(http.MethodGet, r) { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + + controllers.EditorPage(w, r) + }) + + // POST calls + http.HandleFunc("/send-fax", func(w http.ResponseWriter, r *http.Request) { + if !checkMethod(http.MethodPost, r) { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + + controllers.SendFax(w, r) + }) + + http.HandleFunc("/send-login", func(w http.ResponseWriter, r *http.Request) { + if !checkMethod(http.MethodPost, r) { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + + controllers.Authenticate(w, r) + }) + + // Serve the CSS and JS files, we might have to change this + http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir("assets")))) + + log.Println("Starting server on port 8083") + log.Fatal(http.ListenAndServe(":8083", nil)) +}