diff --git a/.env b/.env new file mode 100644 index 0000000..d9b7d1a --- /dev/null +++ b/.env @@ -0,0 +1 @@ +export PROJ=/home/esilva/Desktop/projetos/fax diff --git a/schemaDiagram.drawio b/schemaDiagram.drawio new file mode 100644 index 0000000..0b61b5f --- /dev/null +++ b/schemaDiagram.drawio @@ -0,0 +1,207 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Makefile b/src/Makefile index 43c7156..688bad2 100644 --- a/src/Makefile +++ b/src/Makefile @@ -6,6 +6,11 @@ build: clean clean: rm -rf ./build +db: + rm -f data.db + touch data.db + sqlite3 data.db < ./usefulQueries.sql + test: rm -f coverage.html go test -v -coverprofile coverage.html ./... diff --git a/src/assets/htmx/history.html b/src/assets/htmx/history.html index 4a2c281..f6d5932 100644 --- a/src/assets/htmx/history.html +++ b/src/assets/htmx/history.html @@ -1 +1,9 @@ -Hello, there! \ No newline at end of file +
+ {{ range .faxList }} +
+ {{ .Id }} +
Text: {{ .Text }}
+
Date: {{ .DateString }}
+
+ {{ end }} +
\ No newline at end of file diff --git a/src/cmd/root.go b/src/cmd/root.go index 0a3148e..9a400af 100644 --- a/src/cmd/root.go +++ b/src/cmd/root.go @@ -17,9 +17,14 @@ func rootCmdAction(cmd *cobra.Command, args []string) { cfgPath, _ := cmd.Flags().GetString("config") var cfg *config.Configuration - _, err := cfg.GetInstance(cfgPath, nil) + err := cfg.Setup() if err != nil { - log.Println("Failed to load configuration instance: ", err) + log.Println("failed to setup configuration environment") + return + } + _, err = cfg.GetInstance(cfgPath, nil) + if err != nil { + log.Println("failed to load configuration instance: ", err) return } scache.GetInstance() diff --git a/src/config/config.go b/src/config/config.go index 3f7c436..b4eb061 100644 --- a/src/config/config.go +++ b/src/config/config.go @@ -3,21 +3,19 @@ package config import ( "errors" "fmt" - "io" "log" "os" - "slices" "sync" - - "gopkg.in/yaml.v2" ) var ( + cparser IConfigParser = nil cfgPath string bytesCfg []byte instance *Configuration once sync.Once validUseValues = []string{ + "fake", "socket", "usb", "network", @@ -25,6 +23,8 @@ var ( onceErr error ) +type fakeDev struct{} + type usbDev struct { Path string `yaml:"path"` } @@ -44,24 +44,12 @@ type Configuration struct { Use string `yaml:"use"` Usb *usbDev `yaml:"usb"` Network *networkDev `yaml:"network"` + Fake *fakeDev `yaml:"fake"` } -func findConfigFile() (string, error) { - configLocations := map[string]string{ - "XDG": "~/.config/fax/config.yml", - "RUNTIME": "~/.config.yml", - "ETC": "/etc/fax/config.yml", - } - - 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") +func (c *Configuration) Setup() error { + cparser = &ConfigParser{} + return nil } func (c *Configuration) GetInstance(path string, data []byte) (*Configuration, error) { @@ -69,58 +57,31 @@ func (c *Configuration) GetInstance(path string, data []byte) (*Configuration, e instance = &Configuration{} if path == "" { - log.Println("no configuration file provided... Searching in default locations") - cfgPath, onceErr = findConfigFile() + onceErr = cparser.resolveFilePath() if onceErr != nil { - log.Println("could not find a configuration file. Terminating") + log.Println("unable to resolve config file") return - // We could print the correct places to add a configuration file here } } instance.Path = path + onceErr = instance.loadConfiguration(data) if onceErr != nil { return } }) if onceErr != nil { + log.Println("failed to get configuration instance") return nil, onceErr } return instance, nil } -func readFile(reader io.Reader) ([]byte, error) { - file, err := io.ReadAll(reader) - if err != nil { - log.Println("failed to read contents of file") - return nil, err - } - - return file, nil -} - -type ConfigParser struct{} - -func (p *ConfigParser) parseConfigFile(f []byte) error { - err := yaml.Unmarshal(f, &instance) - if err != nil { - log.Printf("error parsing config file: %s", err.Error()) - return errors.New("error parsing config file") - } - - if !slices.Contains(validUseValues, instance.Use) { - log.Println("unusual value for `Use`") - errString := fmt.Sprintf("bad `Use` value: %s", instance.Use) - return errors.New(errString) - } - - return nil -} - func (c *Configuration) loadConfiguration(data []byte) error { var contents []byte + if data != nil { contents = data } else { @@ -132,15 +93,14 @@ func (c *Configuration) loadConfiguration(data []byte) error { return errors.New(errStr) } - contents, err = readFile(file) + contents, err = cparser.readFile(file) if err != nil { errStr := fmt.Sprintf("failed to read file: %s", err) return errors.New(errStr) } } - var parser *ConfigParser - err := parser.parseConfigFile(contents) + err := cparser.parseConfigFile(contents) if err != nil { return err } diff --git a/src/config/configParser.go b/src/config/configParser.go new file mode 100644 index 0000000..65f8b8d --- /dev/null +++ b/src/config/configParser.go @@ -0,0 +1,78 @@ +package config + +import ( + "errors" + "fmt" + "io" + "log" + "os" + "slices" + + "gopkg.in/yaml.v2" +) + +var ( + configLocations = map[string]string{ + "XDG": "~/.config/fax/config.yml", + "RUNTIME": "~/.config.yml", + "ETC": "/etc/fax/config.yml", + } +) + +type IConfigParser interface { + readFile(io.Reader) ([]byte, error) + parseConfigFile([]byte) error + resolveFilePath() error + findConfigFile() (string, error) +} + +type ConfigParser struct{} + +func (c *ConfigParser) readFile(reader io.Reader) ([]byte, error) { + file, err := io.ReadAll(reader) + if err != nil { + log.Println("failed to read contents of file") + return nil, err + } + + return file, nil +} + +func (p *ConfigParser) parseConfigFile(f []byte) error { + err := yaml.Unmarshal(f, &instance) + if err != nil { + log.Printf("error parsing config file: %s", err.Error()) + return errors.New("error parsing config file") + } + + if !slices.Contains(validUseValues, instance.Use) { + log.Println("unusual value for `Use`") + errString := fmt.Sprintf("bad `Use` value: %s", instance.Use) + return errors.New(errString) + } + + return nil +} + +func (c *ConfigParser) findConfigFile() (string, error) { + 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") +} + +func (c *ConfigParser) resolveFilePath() error { + log.Println("no configuration file provided... Searching in default locations") + cfgPath, onceErr = c.findConfigFile() + if onceErr != nil { + log.Println("could not find a configuration file. Terminating") + return onceErr + // We could print the correct places to add a configuration file here + } + return nil +} diff --git a/src/config/configParser_test.go b/src/config/configParser_test.go new file mode 100644 index 0000000..872c9c5 --- /dev/null +++ b/src/config/configParser_test.go @@ -0,0 +1,52 @@ +package config + +import ( + "errors" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" +) + +type errorReader struct{ mock.Mock } + +func (e *errorReader) Read(p []byte) (int, error) { + args := e.Called() + return args.Int(0), args.Error(1) +} + +func TestReadFile_FailsToRead(t *testing.T) { + // Arrange + parser := &ConfigParser{} + + var readerMOCK ConfigParserMOCK + readerMOCK.On("readFile").Return(0, errors.New("We failed, yo")) + cparser = &readerMOCK + + inputMOCK := errorReader{} + inputMOCK.On("Read").Return(0, errors.New("We failed")) + + // Act + _, err := parser.readFile(&inputMOCK) + + // Assert + assert.Error(t, err) +} + +func TestParseConfigFile_FailsToUnmarshal(t *testing.T) { +} + +func TestFindConfigFile_FailsToFindAny(t *testing.T) { +} + +func TestFindConfigFile_FindsFile(t *testing.T) { + // Create my own map of files and then create them and remove them and check if I find them +} + +func TestResolveFilePath_Success(t *testing.T) { + // Create my own map of files and then create them and remove them and check if I find them +} + +func TestResolveFilePath_FailsToFindConfigFile(t *testing.T) { + // Create my own map of files and then create them and remove them and check if I find them +} diff --git a/src/config/config_test.go b/src/config/config_test.go index 97a4bf8..9dfe2d0 100644 --- a/src/config/config_test.go +++ b/src/config/config_test.go @@ -1,11 +1,16 @@ package config import ( + "errors" + "io" + "os" + "path" "sync" "testing" "github.com/google/go-cmp/cmp" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" ) func reset() { @@ -29,6 +34,7 @@ encoding: // Act var cfg Configuration + cfg.Setup() _, err := cfg.GetInstance("./test_config.yml", []byte(configYml)) // Assert @@ -62,6 +68,7 @@ encoding: // Act var cfg Configuration + cfg.Setup() result, err := cfg.GetInstance("./test_config.yml", []byte(configYml)) assert.NoError(t, err) @@ -75,6 +82,7 @@ func TestLoadConfiguration_NoFileErrorWithoutParams(t *testing.T) { cfg := Configuration{ Path: "./test_config.yml", } + cfg.Setup() // Act err := cfg.loadConfiguration(nil) @@ -86,9 +94,57 @@ func TestLoadConfiguration_NoFileErrorWithoutParams(t *testing.T) { func TestLoadConfiguration_ReadFileSuccecssWithoutParams(t *testing.T) { reset() // Arrange + gp := os.Getenv("PROJ") + cpath := path.Join(gp, "src/assets/testing/config/test_config.yml") cfg := Configuration{ - Path: "./test_config.yml", + Path: cpath, } + cfg.Setup() + + // Act + err := cfg.loadConfiguration(nil) + + // Assert + assert.NoError(t, err) +} + +type ConfigParserMOCK struct { + mock.Mock +} + +func (c *ConfigParserMOCK) readFile(_ io.Reader) ([]byte, error) { + args := c.Called() + return args.Get(0).([]byte), args.Error(1) +} + +func (c *ConfigParserMOCK) parseConfigFile(_ []byte) error { + args := c.Called() + return args.Error(1) +} + +func (c *ConfigParserMOCK) resolveFilePath() error { + args := c.Called() + return args.Error(0) +} + +func (c *ConfigParserMOCK) findConfigFile() (string, error) { + args := c.Called() + return args.String(0), args.Error(0) +} + +func TestLoadConfiguration_ReadFileFailsWithoutParams(t *testing.T) { + reset() + // Arrange + gp := os.Getenv("PROJ") + cpath := path.Join(gp, "src/assets/testing/config/test_config.yml") + cfg := Configuration{ + Path: cpath, + } + cfg.Setup() + + var cfgParserMOCK ConfigParserMOCK + cfgParserMOCK.On("readFile").Return([]byte("Hello"), errors.New("We failed, yo")) + cparser = &cfgParserMOCK // Act err := cfg.loadConfiguration(nil) @@ -96,3 +152,21 @@ func TestLoadConfiguration_ReadFileSuccecssWithoutParams(t *testing.T) { // Assert assert.Error(t, err) } + +func TestGetInstance_NoParams(t *testing.T) { + reset() + // Arrange + var cfg *Configuration + cfg.Setup() + + var cfgParserMOCK ConfigParserMOCK + cfgParserMOCK.On("resolveFilePath").Return(errors.New("We failed, yo")) + cfgParserMOCK.On("findConfigFile").Return("", errors.New("We failed, yo")) + cparser = &cfgParserMOCK + + // Act + _, err := cfg.GetInstance("", nil) + + // Assert + assert.Error(t, err) +} diff --git a/src/controllers/authentication.go b/src/controllers/authentication.go index 8a35af1..20dcb3c 100644 --- a/src/controllers/authentication.go +++ b/src/controllers/authentication.go @@ -34,6 +34,18 @@ func isAuthenticated(r *http.Request) (bool, string) { return false, "" } + var dacc models.DB + m, err := models.NewModel(&dacc) + if err != nil { + log.Fatalln("unable to access the models") + } + + _, err = m.GetAuth(token.Value) + if err != nil { + log.Println("token provided by browser isn't in the database, return") + return false, "" + } + expirationTime := time.Now() return expirationTime.Unix() >= token.Expires.Unix(), token.Value } @@ -139,13 +151,13 @@ func updateSession(w http.ResponseWriter, u *models.User, sessionCookie *http.Co func Authenticate(w http.ResponseWriter, r *http.Request) { // DELETE THIS AFTER TESTING AND SO ON - time.Sleep(1 * time.Second) + // time.Sleep(1 * time.Second) // Create the model access var dacc models.DB m, err := models.NewModel(&dacc) if err != nil { - fmt.Println("| controllers | authentication | unable to access the models") + fmt.Println("unable to access the models") } // first we have to verify if this request brings any login data @@ -156,6 +168,7 @@ func Authenticate(w http.ResponseWriter, r *http.Request) { } if !m.ValidateCredentials(&loginForm) { + log.Println("Trigerring wrongCredentials") w.Header().Add("HX-Trigger", `{"wrongCredentials":"Wrong Credentials"}`) return } @@ -166,7 +179,11 @@ func Authenticate(w http.ResponseWriter, r *http.Request) { sessionCookie := getToken(r, "fax-session") userReqSession := false if sessionCookie != nil { - userReqSession = true + // Check if this is available on our side + _, err = m.GetAuth(sessionCookie.Value) + if err == nil { + userReqSession = true + } } // If there is an active session we update the current session @@ -208,3 +225,35 @@ func relogin(w http.ResponseWriter, r *http.Request) { saveSessionState(r) views.LoginPage(w, r) } + +// THIS SHOULD GO SOMEWHERE ELSE +func resolveUser(r *http.Request) *models.User { + // COPY + authToken := getToken(r, "token") + if authToken == nil { + log.Fatalln("authToken is nil. Shouldn't be") + } + + // Create the model access + var dacc models.DB + m, err := models.NewModel(&dacc) + if err != nil { + fmt.Println("unable to access the models") + } + + sessionData, err := m.GetAuth(authToken.Value) + if err != nil { + log.Fatalln("failed to retrieve session data: ", err) + } + if sessionData == nil { + log.Fatalln("sessionData cannot be nil") + } + + user := m.GetUserData(sessionData.User) + if user == nil { + log.Fatalln("user cannot be nil") + } + // COPY + + return user +} diff --git a/src/controllers/history.go b/src/controllers/history.go index a268fa8..5ae74d2 100644 --- a/src/controllers/history.go +++ b/src/controllers/history.go @@ -1,10 +1,33 @@ package controllers import ( + "fmt" + "log" "net/http" + "thermalFax/models" "thermalFax/views" + "time" ) +func getUserFaxlist(userId int) []models.Fax { + var dacc models.DB + m, err := models.NewModel(&dacc) + if err != nil { + fmt.Println("unable to access the models") + } + + faxList, err := models.SelectAllFax(m.DB, userId) + if err != nil { + log.Fatalf("Cannot be nil yo. Error: %s", err) + } + + for k := range faxList { + faxList[k].DateString = time.Unix(faxList[k].Date, 0).Format("2006-01-02 15:04:05") + } + + return faxList +} + func History(w http.ResponseWriter, r *http.Request) { authd, _ := isAuthenticated(r) if !authd { @@ -12,7 +35,10 @@ func History(w http.ResponseWriter, r *http.Request) { return } - views.HistoryPage(w, r) + user := resolveUser(r) + faxList := getUserFaxlist(user.Id) + + views.HistoryPage(w, faxList) } func HistoryPOST(w http.ResponseWriter, r *http.Request) { @@ -22,5 +48,8 @@ func HistoryPOST(w http.ResponseWriter, r *http.Request) { return } - views.HistoryPagePOST(w, r) + user := resolveUser(r) + faxList := getUserFaxlist(user.Id) + + views.HistoryPagePOST(w, faxList) } diff --git a/src/controllers/sendFax.go b/src/controllers/sendFax.go index 047c264..dd7ea73 100644 --- a/src/controllers/sendFax.go +++ b/src/controllers/sendFax.go @@ -35,6 +35,12 @@ func sendRequestToPrinter(msg string) (PrintServerResponse, error) { var c *config.Configuration cfg, _ := c.GetInstance("", nil) + if cfg.Use == "fake" { + return PrintServerResponse{ + Message: "success", + }, nil + } + // Send the request to the actual printer server req, err := http.NewRequest( http.MethodPost, @@ -69,8 +75,10 @@ func sendRequestToPrinter(msg string) (PrintServerResponse, error) { // sendFax is a function that receives the data from the fronted and // sends it to the print server func SendFax(w http.ResponseWriter, r *http.Request) { + log.Println("Are we logged in?") authd, token := isAuthenticated(r) if !authd { + log.Println("User is not logged in") // We don't do a reauth here so we do a simple refresh and let the /editor controller // take care of it on the following request // - We will have to make it be clear that the message was not sent tho @@ -79,7 +87,7 @@ func SendFax(w http.ResponseWriter, r *http.Request) { } // REMOVE THIS YO - time.Sleep(3 * time.Second) + // time.Sleep(3 * time.Second) // Create the model access var dacc models.DB @@ -88,7 +96,13 @@ func SendFax(w http.ResponseWriter, r *http.Request) { log.Fatalln("unable to access the models") } - session, _ := m.GetAuth(token) + session, err := m.GetAuth(token) + if err != nil { + log.Fatalf("user token is not in the database") + w.Header().Set("HX-Refresh", "true") + return + } + user := m.GetUserData(session.User) log.Printf("user %s requested a fax", user.Name) @@ -98,12 +112,31 @@ func SendFax(w http.ResponseWriter, r *http.Request) { Message: r.FormValue("fax-message"), } - msg := signMessage(formData.Message, user.Name, time.Now().Format("2006-01-02 15:04:05")) + mDate := time.Now() + message := &models.Fax{ + User: user.Id, + Date: int64(mDate.Unix()), + Text: formData.Message, + } + + msg := signMessage(message.Text, user.Name, mDate.Format("2006-01-02 15:04:05")) _, err = sendRequestToPrinter(msg) if err != nil { - log.Println("printer failed to process fax:", err) - w.Write([]byte("{\"state\":\"failed\"}")) - return + // When we have our history table working we can set the state of it here + // log.Println("printer failed to process fax:", err) + // w.Write([]byte("{\"state\":\"failed\"}")) + // return + } + + /* + Another workflow to add here is to send the message into the DB right away + Then do the rest of the process and mark its state or something like that + #parallelization + */ + // Store the message we just sent into the DB + err = message.InsertMessage(m.DB) + if err != nil { + log.Println("failed to insert message in database") } w.Header().Set("Content-Type", "text/json") diff --git a/src/go.mod b/src/go.mod index 691a022..737aff9 100644 --- a/src/go.mod +++ b/src/go.mod @@ -4,7 +4,6 @@ go 1.22.2 require ( github.com/DATA-DOG/go-sqlmock v1.5.2 - github.com/go-playground/assert/v2 v2.2.0 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 @@ -12,16 +11,13 @@ require ( github.com/stretchr/testify v1.9.0 golang.org/x/crypto v0.22.0 gopkg.in/yaml.v2 v2.4.0 - honnef.co/go/tools v0.4.7 ) require ( - github.com/BurntSushi/toml v1.2.1 // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/spf13/pflag v1.0.5 // indirect github.com/stretchr/objx v0.5.2 // indirect - golang.org/x/tools v0.12.1-0.20230825192346-2191a27a6dc5 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/src/go.sum b/src/go.sum index 18a93bc..d46fb47 100644 --- a/src/go.sum +++ b/src/go.sum @@ -1,12 +1,8 @@ -github.com/BurntSushi/toml v1.2.1 h1:9F2/+DoOYIOksmaJFPw1tGFy1eDnIJXg+UHjuD8lTak= -github.com/BurntSushi/toml v1.2.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= github.com/DATA-DOG/go-sqlmock v1.5.2 h1:OcvFkGmslmlZibjAjaHm3L//6LiuBgolP7OputlJIzU= github.com/DATA-DOG/go-sqlmock v1.5.2/go.mod h1:88MAG/4G7SMwSE3CeA0ZKzrT5CiOU3OJ+JlNzwDqpNU= github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= -github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= 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= @@ -29,13 +25,9 @@ github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsT github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= golang.org/x/crypto v0.22.0 h1:g1v0xeRhjcugydODzvb3mEM9SQ0HGp9s/nh3COQ/C30= golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M= -golang.org/x/tools v0.12.1-0.20230825192346-2191a27a6dc5 h1:Vk4mysSz+GqQK2eqgWbo4zEO89wkeAjJiFIr9bpqa8k= -golang.org/x/tools v0.12.1-0.20230825192346-2191a27a6dc5/go.mod h1:Sc0INKfu04TlqNoRA1hgpFZbhYXHPr4V5DzpSBTPqQM= 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 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -honnef.co/go/tools v0.4.7 h1:9MDAWxMoSnB6QoSqiVr7P5mtkT9pOc1kSxchzPCnqJs= -honnef.co/go/tools v0.4.7/go.mod h1:+rnGS1THNh8zMwnd2oVOTL9QF6vmfyG6ZXBULae2uc0= diff --git a/src/models/authentication.go b/src/models/authentication.go index c43539f..d9944ef 100644 --- a/src/models/authentication.go +++ b/src/models/authentication.go @@ -17,11 +17,6 @@ type Authenticator interface { } type Authentication struct{} -type LoginForm struct { - Username string `json:"username"` - Password string `json:"password"` -} - type Claims struct { jwt.RegisteredClaims } @@ -32,6 +27,17 @@ type SessionData struct { ExpirationTime int64 } +type LoginForm struct { + Username string `json:"username"` + Password string `json:"password"` +} + +// func (lf *LoginForm) Parse(r *http.Request) { +// r.ParseForm() +// lf.Username = r.FormValue("login-user") +// lf.Password = r.FormValue("login-pass") +// } + // Private functions // insertToken will insert the token generated by a successful authentication func insertToken(db *sql.DB, token string, user int, expirationDate int64) error { @@ -79,23 +85,10 @@ func getSessionData(db *sql.DB, token string) (*SessionData, error) { SELECT user, token, expires FROM sessions WHERE token='` + token + `'; ` - rows, err := db.Query(query) - if err != nil { - log.Fatal("failed to get user data: ", err) - return nil, err - } - defer rows.Close() - var p SessionData - for rows.Next() { - if err := rows.Scan(&p.User, &p.Token, &p.ExpirationTime); err != nil { - log.Fatal("failed to read row.", err) - } - } - - // No password found (user doesn't exist?) - if len(p.Token) == 0 { - return nil, nil + err := db.QueryRow(query).Scan(&p.User, &p.Token, &p.ExpirationTime) + if err != nil { + return nil, err } return &p, nil diff --git a/src/models/fax.go b/src/models/fax.go new file mode 100644 index 0000000..c2caf5b --- /dev/null +++ b/src/models/fax.go @@ -0,0 +1,83 @@ +package models + +import ( + "database/sql" + "log" + "strconv" +) + +type Fax struct { + Id int + User int + Date int64 + DateString string + Text string +} + +func (f *Fax) InsertMessage(db *sql.DB) error { + query := ` + INSERT INTO + fax(user, date, text) + values( + '` + strconv.Itoa(f.User) + `', + '` + strconv.FormatInt(f.Date, 10) + `', + '` + f.Text + `'); + ` + + _, err := db.Exec(query) + if err != nil { + log.Printf("failed to execute query:\n%s", query) + return err + } + + return nil +} + +func SelectAllFax(db *sql.DB, user int) ([]Fax, error) { + query := `SELECT id,text,date FROM fax WHERE user=` + strconv.Itoa(user) + `;` + + rows, err := db.Query(query) + if err != nil { + log.Printf("failed to execute query:\n%s", query) + return nil, err + } + defer rows.Close() + + var faxList []Fax + for rows.Next() { + var curFax Fax + if err := rows.Scan(&curFax.Id, &curFax.Text, &curFax.Date); err != nil { + log.Println("failed to read row.", err) + return nil, err + } + faxList = append(faxList, curFax) + } + + return faxList, nil +} + +// func readMessage(db *sql.DB, message *Message) (*Message, error) { +// query := ` +// INSERT INTO +// sessions(date, text) +// values( +// '` + strconv.Itoa(message.Date) + `', +// '` + message.Text + `'); +// ` + +// _, err := db.Exec(query) +// if err != nil { +// log.Fatal("failed to insert data: ", err) +// return err +// } + +// return nil +// } + +// func updateMessage(db *sql.DB, message *Message) error { +// return nil +// } + +// func deleteMessage(db *sql.DB, message *Message) error { +// return nil +// } diff --git a/src/models/users.go b/src/models/users.go index a5bf80c..339b1bd 100644 --- a/src/models/users.go +++ b/src/models/users.go @@ -9,7 +9,7 @@ import ( type User struct { Id int Name string - Email string + Email sql.NullString Role string Plafond float32 } diff --git a/src/models/users_test.go b/src/models/users_test.go index 8c503ad..dcde6d6 100644 --- a/src/models/users_test.go +++ b/src/models/users_test.go @@ -1,6 +1,7 @@ package models import ( + "database/sql" "errors" "strconv" "testing" @@ -31,9 +32,12 @@ func TestGetUserDataById_Success(t *testing.T) { // Assert the returned user expectedUser := &User{ - Id: userID, - Name: "John Doe", - Email: "john@example.com", + Id: userID, + Name: "John Doe", + Email: sql.NullString{ + String: "john@example.com", + Valid: true, + }, Role: "admin", Plafond: 1000.0, } diff --git a/src/usefulQueries.sql b/src/usefulQueries.sql index 56c033b..1812c57 100644 --- a/src/usefulQueries.sql +++ b/src/usefulQueries.sql @@ -4,9 +4,9 @@ CREATE TABLE IF NOT EXISTS users( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL UNIQUE, - email TEXT UNIQUE DEFAULT "", - role TEXT DEFAULT "USER", - plafond REAL DEFAULT 0.0, + email TEXT UNIQUE DEFAULT NULL, + role TEXT NOT NULL DEFAULT "USER", + plafond REAL NOT NULL DEFAULT 0.0, password TEXT NOT NULL ); @@ -18,6 +18,14 @@ CREATE TABLE IF NOT EXISTS sessions( FOREIGN KEY (user) REFERENCES users (id) ); +CREATE TABLE IF NOT EXISTS fax( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user INTEGER, + text TEXT NOT NULL, + date INTEGER NOT NULL, + FOREIGN KEY (user) REFERENCES users (id) +); + -- user/pass INSERT INTO users(name, password) diff --git a/src/views/editorPage.go b/src/views/editorPage.go index e9fcb46..e6a3fb0 100644 --- a/src/views/editorPage.go +++ b/src/views/editorPage.go @@ -1,29 +1,37 @@ package views -import "net/http" +import ( + "html/template" + "net/http" +) -func EditorPage(w http.ResponseWriter, r *http.Request) { +func editorContents() *template.HTML { + return HtmlTemplate("./assets/htmx/editor.html", nil) +} + +func editorPage(w http.ResponseWriter, r *http.Request, fullPage bool) { w.WriteHeader(http.StatusOK) - mainPage := HtmlTemplate("./assets/htmx/terminal.html", map[string]interface{}{ - "content": HtmlTemplate("./assets/htmx/editor.html", nil), - "renderNavBar": true, - "page": "editor", - }) + page := editorContents() + if fullPage { + page = HtmlTemplate("./assets/htmx/terminal.html", map[string]interface{}{ + "content": page, + "renderNavBar": true, + "page": "editor", + }) + } - _, err := w.Write([]byte(mainPage)) + _, err := w.Write([]byte(*page)) if err != nil { http.Error(w, "Internal error", http.StatusInternalServerError) return } } +func EditorPage(w http.ResponseWriter, r *http.Request) { + editorPage(w, r, true) +} + func EditorPagePOST(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - - _, err := w.Write([]byte(HtmlTemplate("./assets/htmx/editor.html", nil))) - if err != nil { - http.Error(w, "Internal error", http.StatusInternalServerError) - return - } + editorPage(w, r, false) } diff --git a/src/views/historyPage.go b/src/views/historyPage.go index 52dfbda..97a7c0e 100644 --- a/src/views/historyPage.go +++ b/src/views/historyPage.go @@ -1,29 +1,43 @@ package views -import "net/http" +import ( + "html/template" + "net/http" + "thermalFax/models" +) -func HistoryPagePOST(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - - _, err := w.Write([]byte(HtmlTemplate("./assets/htmx/history.html", nil))) - if err != nil { - http.Error(w, "Internal error", http.StatusInternalServerError) - return - } -} - -func HistoryPage(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - - mainPage := HtmlTemplate("./assets/htmx/terminal.html", map[string]interface{}{ - "content": HtmlTemplate("./assets/htmx/history.html", nil), - "renderNavBar": true, - "page": "history", +func historyContents(fList []models.Fax) *template.HTML { + hContent := HtmlTemplate("./assets/htmx/history.html", map[string]interface{}{ + "faxList": fList, }) - _, err := w.Write([]byte(mainPage)) + return hContent +} + +func historyPage(w http.ResponseWriter, fList []models.Fax, fullPage bool) { + w.WriteHeader(http.StatusOK) + + page := historyContents(fList) + + if fullPage { + page = HtmlTemplate("./assets/htmx/terminal.html", map[string]interface{}{ + "content": page, + "renderNavBar": true, + "page": "history", + }) + } + + _, err := w.Write([]byte(*page)) if err != nil { http.Error(w, "Internal error", http.StatusInternalServerError) return } } + +func HistoryPagePOST(w http.ResponseWriter, fList []models.Fax) { + historyPage(w, fList, false) +} + +func HistoryPage(w http.ResponseWriter, fList []models.Fax) { + historyPage(w, fList, true) +} diff --git a/src/views/loginPage.go b/src/views/loginPage.go index ec83c91..e629980 100644 --- a/src/views/loginPage.go +++ b/src/views/loginPage.go @@ -12,7 +12,7 @@ func LoginPage(w http.ResponseWriter, r *http.Request) { "renderNavBar": false, }) - _, err := w.Write([]byte(loginPage)) + _, err := w.Write([]byte(*loginPage)) if err != nil { http.Error(w, "Internal error", http.StatusInternalServerError) return diff --git a/src/views/personalDataPage.go b/src/views/personalDataPage.go index 3f23d54..f9a839c 100644 --- a/src/views/personalDataPage.go +++ b/src/views/personalDataPage.go @@ -1,46 +1,44 @@ package views import ( + "html/template" "net/http" "thermalFax/models" ) -func PersonalDataPagePOST(w http.ResponseWriter, r *http.Request, u *models.User) { - w.WriteHeader(http.StatusOK) - +func personalDataContents(u *models.User) *template.HTML { userData := map[string]interface{}{ "id": u.Id, "name": u.Name, "role": u.Role, "plafond": u.Plafond, } + return HtmlTemplate("./assets/htmx/personalData.html", userData) +} - _, err := w.Write([]byte(HtmlTemplate("./assets/htmx/personalData.html", userData))) +func personalDataPage(w http.ResponseWriter, r *http.Request, u *models.User, fp bool) { + w.WriteHeader(http.StatusOK) + + page := personalDataContents(u) + if fp { + page = HtmlTemplate("./assets/htmx/terminal.html", map[string]interface{}{ + "content": page, + "renderNavBar": true, + "page": "personalData", + }) + } + + _, err := w.Write([]byte(*page)) if err != nil { http.Error(w, "Internal error", http.StatusInternalServerError) return } } +func PersonalDataPagePOST(w http.ResponseWriter, r *http.Request, u *models.User) { + personalDataPage(w, r, u, false) +} + func PersonalDataPage(w http.ResponseWriter, r *http.Request, u *models.User) { - w.WriteHeader(http.StatusOK) - - userData := map[string]interface{}{ - "id": u.Id, - "name": u.Name, - "role": u.Role, - "plafond": u.Plafond, - } - - mainPage := HtmlTemplate("./assets/htmx/terminal.html", map[string]interface{}{ - "content": HtmlTemplate("./assets/htmx/personalData.html", userData), - "renderNavBar": true, - "page": "personalData", - }) - - _, err := w.Write([]byte(mainPage)) - if err != nil { - http.Error(w, "Internal error", http.StatusInternalServerError) - return - } + personalDataPage(w, r, u, true) } diff --git a/src/views/templating.go b/src/views/templating.go index 6a4db8c..580ba78 100644 --- a/src/views/templating.go +++ b/src/views/templating.go @@ -7,7 +7,7 @@ import ( "path" ) -func HtmlTemplate(file string, data map[string]interface{}) template.HTML { +func HtmlTemplate(file string, data map[string]interface{}) *template.HTML { // Process the given path templateName := path.Base(file) tmpl, err := template.New(templateName).ParseFiles(file) @@ -23,5 +23,6 @@ func HtmlTemplate(file string, data map[string]interface{}) template.HTML { } // Now, renderedOutput holds the rendered template - return template.HTML(renderedOutput.String()) + result := template.HTML(renderedOutput.String()) + return &result }