Added some unittests and therefore changed some of the code

Also formatted the logging, for now its good, we will add analytics to
it later tho
This commit is contained in:
2024-06-13 15:55:31 +01:00
parent 56c20edd73
commit 65baa4469b
17 changed files with 482 additions and 210 deletions
+5 -3
View File
@@ -2,9 +2,11 @@ build: clean
mkdir build
go build -o build/frontend
cp -r ./assets build
# cp ./config.yml build/config.yml
# touch build/data.db
# sqlite3 build/data.db < ./usefulQueries.sql
clean:
rm -rf ./build
test:
rm -f coverage.html
go test -v -coverprofile coverage.html ./...
go tool cover -html coverage.html -o coverage.html
@@ -0,0 +1,8 @@
use: "network"
network:
host: "esilva-printer-container"
port: "9099"
usb:
path: "/dev/usb/lp0"
encoding:
capabilities-file: ./capabilities.json
+9 -1
View File
@@ -4,6 +4,7 @@ Copyright © 2024 NAME HERE <EMAIL ADDRESS>
package cmd
import (
"log"
"os"
"thermalFax/config"
"thermalFax/scache"
@@ -15,9 +16,16 @@ import (
func rootCmdAction(cmd *cobra.Command, args []string) {
cfgPath, _ := cmd.Flags().GetString("config")
config.GetInstance(cfgPath, nil)
var cfg *config.Configuration
_, err := cfg.GetInstance(cfgPath, nil)
if err != nil {
log.Println("Failed to load configuration instance: ", err)
return
}
scache.GetInstance()
log.SetFlags(log.LstdFlags | log.Llongfile)
server.Serve()
}
+76 -30
View File
@@ -2,6 +2,8 @@ package config
import (
"errors"
"fmt"
"io"
"log"
"os"
"slices"
@@ -11,6 +13,8 @@ import (
)
var (
cfgPath string
bytesCfg []byte
instance *Configuration
once sync.Once
validUseValues = []string{
@@ -18,6 +22,7 @@ var (
"usb",
"network",
}
onceErr error
)
type usbDev struct {
@@ -29,6 +34,10 @@ type networkDev struct {
Port string `yaml:"port"`
}
type IConfiguration interface {
GetInstance(string, []byte) *Configuration
}
type Configuration struct {
Path string
DBPath string `yaml:"dbpath"`
@@ -46,58 +55,95 @@ func findConfigFile() (string, error) {
for name, path := range configLocations {
if _, err := os.Stat(path); err == nil {
log.Printf("Found %s config file\n", name)
log.Printf("found %s config file\n", name)
return path, nil
}
}
log.Println("No default config file found.")
log.Println("no default config file found")
return "", errors.New("could not find viable config file")
}
func GetInstance(path string, data []byte) *Configuration {
func (c *Configuration) GetInstance(path string, data []byte) (*Configuration, error) {
once.Do(func() {
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. Terminating")
log.Println("no configuration file provided... Searching in default locations")
cfgPath, onceErr = findConfigFile()
if onceErr != nil {
log.Println("could not find a configuration file. Terminating")
return
// We could print the correct places to add a configuration file here
}
}
instance.Path = path
instance.loadConfiguration(data)
})
return instance
}
func (c *Configuration) loadConfiguration(data []byte) {
var file []byte
if data != nil {
file = data
} else {
confPath := c.Path
f, err := os.ReadFile(confPath)
if err != nil {
log.Fatalf("Unable to open configuration file [%s]: %s", confPath,
err.Error())
onceErr = instance.loadConfiguration(data)
if onceErr != nil {
return
}
file = f
})
if onceErr != nil {
return nil, onceErr
}
err := yaml.Unmarshal(file, &instance)
return instance, nil
}
func readFile(reader io.Reader) ([]byte, error) {
file, err := io.ReadAll(reader)
if err != nil {
log.Fatalf("Error parsing config file: %s", err.Error())
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.Fatalf("Unusual value for `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 {
confPath := c.Path
file, err := os.Open(confPath)
if err != nil {
errStr := fmt.Sprintf("failed to open file: %s", err)
return errors.New(errStr)
}
contents, err = 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)
if err != nil {
return err
}
return nil
}
+89 -55
View File
@@ -1,64 +1,98 @@
package config
// func TestConfiguration_BadUse(t *testing.T) {
// // Arrange
// expect := &Configuration{
// Path: "./test_config.yml",
// Use: "network",
// Network: &networkDev{
// Host: "esilva-printer-container",
// Port: "9099",
// },
// }
import (
"sync"
"testing"
// configYml := `
// use: "use_that_does_not_exist"
// network:
// host: "esilva-printer-container"
// port: "9099"
// usb:
// path: "/dev/usb/lp0"
// encoding:
// capabilities-file: ./capabilities.json`
"github.com/google/go-cmp/cmp"
"github.com/stretchr/testify/assert"
)
// // Act
// result := GetInstance("./test_config.yml", []byte(configYml))
func reset() {
once = sync.Once{}
instance = nil
onceErr = nil
}
// // Assert
// if cmp.Equal(expect, result) {
// t.Errorf("Expected:\n%v\nGot:\n%v", expect, result)
// }
// }
func TestConfiguration_BadUse(t *testing.T) {
reset()
// Arrange
configYml := `
use: "use_that_does_not_exist"
network:
host: "esilva-printer-container"
port: "9099"
usb:
path: "/dev/usb/lp0"
encoding:
capabilities-file: ./capabilities.json`
// func TestConfiguration_IntegralNetwork(t *testing.T) {
// // Arrange
// expect := &Configuration{
// Path: "./test_config.yml",
// Use: "network",
// Network: &networkDev{
// Host: "esilva-printer-container",
// Port: "9099",
// },
// Usb: &usbDev{
// Path: "/dev/usb/lp0",
// },
// }
// Act
var cfg Configuration
_, err := cfg.GetInstance("./test_config.yml", []byte(configYml))
// configYml := `
// use: "network"
// network:
// host: "esilva-printer-container"
// port: "9099"
// usb:
// path: "/dev/usb/lp0"
// encoding:
// capabilities-file: ./capabilities.json`
// Assert
assert.Error(t, err)
}
// // Act
// result := GetInstance("./test_config.yml", []byte(configYml))
func TestConfiguration_IntegralNetwork(t *testing.T) {
reset()
// Arrange
expect := &Configuration{
Path: "./test_config.yml",
Use: "network",
Network: &networkDev{
Host: "esilva-printer-container",
Port: "9099",
},
Usb: &usbDev{
Path: "/dev/usb/lp0",
},
}
// // Assert
// if !cmp.Equal(expect, result) {
// t.Errorf("Expected:\n%v\nGot:\n%v", expect, result)
// }
// }
configYml := `
use: "network"
network:
host: "esilva-printer-container"
port: "9099"
usb:
path: "/dev/usb/lp0"
encoding:
capabilities-file: ./capabilities.json`
// Act
var cfg Configuration
result, err := cfg.GetInstance("./test_config.yml", []byte(configYml))
assert.NoError(t, err)
// Assert
assert.True(t, cmp.Equal(expect, result))
}
func TestLoadConfiguration_NoFileErrorWithoutParams(t *testing.T) {
reset()
// Arrange
cfg := Configuration{
Path: "./test_config.yml",
}
// Act
err := cfg.loadConfiguration(nil)
// Assert
assert.Error(t, err)
}
func TestLoadConfiguration_ReadFileSuccecssWithoutParams(t *testing.T) {
reset()
// Arrange
cfg := Configuration{
Path: "./test_config.yml",
}
// Act
err := cfg.loadConfiguration(nil)
// Assert
assert.Error(t, err)
}
+33 -12
View File
@@ -75,7 +75,7 @@ func createSessionCookie(token string) *http.Cookie {
func createNewSession(w http.ResponseWriter, u *models.User) {
authCookie, err := createAuthCookie(u)
if err != nil {
log.Printf("Error: %s", err)
log.Printf("error: %s", err)
return
}
http.SetCookie(w, authCookie)
@@ -83,27 +83,41 @@ func createNewSession(w http.ResponseWriter, u *models.User) {
sessionCookie := createSessionCookie(authCookie.Value)
http.SetCookie(w, sessionCookie)
// Store the auth token in the database
err = models.StoreAuthToken(authCookie.Value, u.Id, authCookie.Expires.Unix())
// Create the model access
var dacc models.DB
m, err := models.NewModel(&dacc)
if err != nil {
log.Println("Failed to store auth token: ", err)
log.Fatalln("unable to access the models")
}
// Store the auth token in the database
err = m.StoreAuthToken(authCookie.Value, u.Id, authCookie.Expires.Unix())
if err != nil {
log.Println("failed to store auth token: ", err)
return
}
// Store the session token in the cache
err = models.StoreSessionToken(authCookie.Value)
err = m.StoreSessionToken(authCookie.Value)
if err != nil {
log.Println("Failed to store session token: ", err)
log.Println("failed to store session token: ", err)
return
}
log.Printf(`| {"user": %s, "time": %d}`, u.Name, time.Now().Unix())
log.Printf(`{"user": %s, "time": %d}`, u.Name, time.Now().Unix())
w.Header().Add("HX-Redirect", "/editor")
}
func updateSession(w http.ResponseWriter, u *models.User, sessionCookie *http.Cookie) {
localUserSession := models.GetSession(sessionCookie.Value)
// Create the model access
var dacc models.DB
m, err := models.NewModel(&dacc)
if err != nil {
fmt.Println("| controllers | updateSessions | unable to access the models")
}
localUserSession := m.GetSession(sessionCookie.Value)
if localUserSession == nil {
// Just create a new session in this case
createNewSession(w, u)
@@ -118,7 +132,7 @@ func updateSession(w http.ResponseWriter, u *models.User, sessionCookie *http.Co
}
http.SetCookie(w, &cookie)
models.UpdateAuthToken(sessionCookie.Value, sessionCookie.Value, expirationTime.Unix())
m.UpdateAuthToken(sessionCookie.Value, sessionCookie.Value, expirationTime.Unix())
w.Header().Set("HX-Redirect", localUserSession.Wants)
}
@@ -127,6 +141,13 @@ func Authenticate(w http.ResponseWriter, r *http.Request) {
// DELETE THIS AFTER TESTING AND SO ON
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")
}
// first we have to verify if this request brings any login data
r.ParseForm()
loginForm := models.LoginForm{
@@ -134,12 +155,12 @@ func Authenticate(w http.ResponseWriter, r *http.Request) {
Password: r.FormValue("login-pass"),
}
if !models.ValidateCredentials(&loginForm) {
if !m.ValidateCredentials(&loginForm) {
w.Header().Add("HX-Trigger", `{"wrongCredentials":"Wrong Credentials"}`)
return
}
user := models.GetUserDataByName(loginForm.Username)
user := m.GetUserDataByName(loginForm.Username)
// First check if there is an active session
sessionCookie := getToken(r, "fax-session")
@@ -162,7 +183,7 @@ func saveSessionState(r *http.Request) {
cache := scache.GetInstance()
cookie := getToken(r, "fax-session")
if cookie == nil {
log.Println("The cookie is nil. It should not be")
log.Println("the cookie is nil. It should not be")
}
if cookie != nil {
+27 -14
View File
@@ -1,6 +1,7 @@
package controllers
import (
"fmt"
"log"
"net/http"
"thermalFax/models"
@@ -14,25 +15,31 @@ func PersonalData(w http.ResponseWriter, r *http.Request) {
return
}
// Create the model access
var dacc models.DB
m, err := models.NewModel(&dacc)
if err != nil {
log.Fatalln("unable to access the models")
}
// COPY
authToken := getToken(r, "token")
if authToken == nil {
log.Fatalln("| controllers | PersonalData | authToken is nil. Shouldn't be")
log.Fatalln("authToken is nil. Shouldn't be")
}
sessionData, err := models.GetAuth(authToken.Value)
sessionData, err := m.GetAuth(authToken.Value)
if err != nil {
log.Fatalln("| controllers | PersonalData | failed to retrieve session data: ", err)
log.Fatalln("failed to retrieve session data: ", err)
}
if sessionData == nil {
log.Fatalln("| controllers | PersonalData | sessionData cannot be nil")
log.Fatalln("sessionData cannot be nil")
}
user := models.GetUserData(sessionData.User)
user := m.GetUserData(sessionData.User)
if user == nil {
log.Fatalln("| controllers | PersonalData | user cannot be nil")
log.Fatalln("user cannot be nil")
}
log.Println(user)
// COPY
views.PersonalDataPage(w, r, user)
@@ -48,22 +55,28 @@ func PersonalDataPOST(w http.ResponseWriter, r *http.Request) {
// COPY
authToken := getToken(r, "token")
if authToken == nil {
log.Fatalln("| controllers | PersonalData | authToken is nil. Shouldn't be")
log.Fatalln("authToken is nil. Shouldn't be")
}
sessionData, err := models.GetAuth(authToken.Value)
// Create the model access
var dacc models.DB
m, err := models.NewModel(&dacc)
if err != nil {
log.Fatalln("| controllers | PersonalData | failed to retrieve session data: ", err)
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("| controllers | PersonalData | sessionData cannot be nil")
log.Fatalln("sessionData cannot be nil")
}
user := models.GetUserData(sessionData.User)
user := m.GetUserData(sessionData.User)
if user == nil {
log.Fatalln("| controllers | PersonalData | user cannot be nil")
log.Fatalln("user cannot be nil")
}
log.Println(user)
// COPY
views.PersonalDataPagePOST(w, r, user)
+14 -6
View File
@@ -32,7 +32,8 @@ type WebFrontendResponse struct {
// to print the message.
// It should be able to send the requests both via http/https or sockets
func sendRequestToPrinter(msg string) (PrintServerResponse, error) {
cfg := config.GetInstance("", nil)
var c *config.Configuration
cfg, _ := c.GetInstance("", nil)
// Send the request to the actual printer server
req, err := http.NewRequest(
@@ -80,9 +81,16 @@ func SendFax(w http.ResponseWriter, r *http.Request) {
// REMOVE THIS YO
time.Sleep(3 * time.Second)
session, _ := models.GetAuth(token)
user := models.GetUserData(session.User)
log.Printf("| User %s requested a fax", user.Name)
// Create the model access
var dacc models.DB
m, err := models.NewModel(&dacc)
if err != nil {
log.Fatalln("unable to access the models")
}
session, _ := m.GetAuth(token)
user := m.GetUserData(session.User)
log.Printf("user %s requested a fax", user.Name)
// Parse the data that comes from the "form"
r.ParseForm()
@@ -91,9 +99,9 @@ func SendFax(w http.ResponseWriter, r *http.Request) {
}
msg := signMessage(formData.Message, user.Name, time.Now().Format("2006-01-02 15:04:05"))
_, err := sendRequestToPrinter(msg)
_, err = sendRequestToPrinter(msg)
if err != nil {
log.Println("| Printer failed to process fax:", err)
log.Println("printer failed to process fax:", err)
w.Write([]byte("{\"state\":\"failed\"}"))
return
}
+6
View File
@@ -4,18 +4,24 @@ 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
github.com/spf13/cobra v1.8.0
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
)
+12
View File
@@ -1,10 +1,16 @@
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=
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/kisielk/sqlstruct v0.0.0-20201105191214-5f3e10d3ab46/go.mod h1:yyMNCyc/Ib3bDTKd379tNMpB/7/H5TjM2Y9QJ5THLbE=
@@ -17,13 +23,19 @@ 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=
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
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=
+25 -32
View File
@@ -1,6 +1,7 @@
package models
import (
"database/sql"
"log"
"net/http"
"strconv"
@@ -33,9 +34,7 @@ type SessionData struct {
// Private functions
// insertToken will insert the token generated by a successful authentication
func insertToken(token string, user int, expirationDate int64) error {
d := OpenDB()
func insertToken(db *sql.DB, token string, user int, expirationDate int64) error {
query := `
INSERT INTO
sessions(user, token, expires)
@@ -46,9 +45,9 @@ func insertToken(token string, user int, expirationDate int64) error {
);
`
_, err := d.DB.Exec(query)
_, err := db.Exec(query)
if err != nil {
log.Fatal("Failed to insert data: ", err)
log.Fatal("failed to insert data: ", err)
return err
}
@@ -56,9 +55,7 @@ func insertToken(token string, user int, expirationDate int64) error {
}
// updateAuthToken will update an old auth token
func updateAuthToken(old string, new string, expirationDate int64) error {
d := OpenDB()
func updateAuthToken(db *sql.DB, old string, new string, expirationDate int64) error {
query := `
UPDATE sessions
SET
@@ -67,9 +64,9 @@ func updateAuthToken(old string, new string, expirationDate int64) error {
WHERE
token='` + old + `';`
_, err := d.DB.Exec(query)
_, err := db.Exec(query)
if err != nil {
log.Fatal("Failed to insert data: ", err)
log.Fatal("failed to insert data: ", err)
return err
}
@@ -77,16 +74,14 @@ func updateAuthToken(old string, new string, expirationDate int64) error {
}
// getSessionData returns the data of a session for a given token
func getSessionData(token string) (*SessionData, error) {
d := OpenDB()
func getSessionData(db *sql.DB, token string) (*SessionData, error) {
query := `
SELECT user, token, expires FROM sessions WHERE token='` + token + `';
`
rows, err := d.DB.Query(query)
rows, err := db.Query(query)
if err != nil {
log.Fatal("| getSessionData | Failed to get user data: ", err)
log.Fatal("failed to get user data: ", err)
return nil, err
}
defer rows.Close()
@@ -94,12 +89,10 @@ func getSessionData(token string) (*SessionData, error) {
var p SessionData
for rows.Next() {
if err := rows.Scan(&p.User, &p.Token, &p.ExpirationTime); err != nil {
log.Fatal("| getSessionData | Failed to read row.", err)
log.Fatal("failed to read row.", err)
}
}
log.Println("| getSessionData | ", p)
// No password found (user doesn't exist?)
if len(p.Token) == 0 {
return nil, nil
@@ -109,10 +102,10 @@ func getSessionData(token string) (*SessionData, error) {
}
// Public functions
func ValidateCredentials(lf *LoginForm) bool {
passwd, err := getUserPass(lf.Username)
func (m *Model) ValidateCredentials(lf *LoginForm) bool {
passwd, err := getUserPass(m.DB, lf.Username)
if err != nil {
log.Fatal("Failed to get password from DB: ", err)
log.Fatal("failed to get password from DB: ", err)
}
err = bcrypt.CompareHashAndPassword([]byte(passwd), []byte(lf.Password))
@@ -120,15 +113,15 @@ func ValidateCredentials(lf *LoginForm) bool {
return err == nil
}
func StoreAuthToken(token string, u int, expirationDate int64) error {
err := insertToken(token, u, expirationDate)
func (m *Model) StoreAuthToken(token string, u int, expirationDate int64) error {
err := insertToken(m.DB, token, u, expirationDate)
if err != nil {
log.Fatal("Unable to insert token into DB: ", err)
log.Fatal("unable to insert token into DB: ", err)
}
return nil
}
func StoreSessionToken(token string) error {
func (m *Model) StoreSessionToken(token string) error {
cache := scache.GetInstance()
if _, activeSession := cache.Data[token]; !activeSession {
session := &scache.Session{
@@ -136,22 +129,22 @@ func StoreSessionToken(token string) error {
}
cache.Data[token] = session
} else {
log.Println("| Session token is ALREADY in use and it SHOULDN'T be")
log.Println("session token is ALREADY in use and it SHOULDN'T be")
// Is it an error? It is but I do not know how to handle it any better for now
}
return nil
}
func UpdateAuthToken(oldToken string, newToken string, expirationDate int64) error {
err := updateAuthToken(oldToken, newToken, expirationDate)
func (m *Model) UpdateAuthToken(oldToken string, newToken string, expirationDate int64) error {
err := updateAuthToken(m.DB, oldToken, newToken, expirationDate)
if err != nil {
log.Fatal("Unable to update auth token: ", err)
log.Fatal("unable to update auth token: ", err)
}
return nil
}
func GetSession(token string) *scache.Session {
func (m *Model) GetSession(token string) *scache.Session {
cache := scache.GetInstance()
if session, ok := cache.Data[token]; ok {
return session
@@ -160,6 +153,6 @@ func GetSession(token string) *scache.Session {
return nil
}
func GetAuth(token string) (*SessionData, error) {
return getSessionData(token)
func (m *Model) GetAuth(token string) (*SessionData, error) {
return getSessionData(m.DB, token)
}
-38
View File
@@ -1,38 +0,0 @@
package models
import (
"database/sql"
"log"
"thermalFax/config"
_ "github.com/mattn/go-sqlite3"
)
type Database struct {
DB *sql.DB
Path string
}
func OpenDB() *Database {
cfg := config.GetInstance("", nil)
var d Database
err := d.Initialize(cfg.DBPath)
if err != nil {
log.Fatal("Failed to get into DB: ", err)
}
return &d
}
func (s *Database) Initialize(path string) error {
db, err := sql.Open("sqlite3", path)
if err != nil {
return err
}
s.Path = path
s.DB = db
return nil
}
+47
View File
@@ -0,0 +1,47 @@
package models
import (
"database/sql"
"errors"
"log"
"thermalFax/config"
_ "github.com/mattn/go-sqlite3"
)
type Model struct {
DB *sql.DB
}
type DBAccess interface {
openDB() (*sql.DB, error)
}
type DB struct{}
func NewModel(dacc DBAccess) (*Model, error) {
m := new(Model)
// Try to load the DB
db, err := dacc.openDB()
if err != nil {
log.Println("failed to create new model instance: ", err)
return nil, errors.New("failed to create model instance")
}
// Store the values
m.DB = db
return m, nil
}
func (d *DB) openDB() (*sql.DB, error) {
var c *config.Configuration
cfg, _ := c.GetInstance("", nil)
db, err := sql.Open("sqlite3", cfg.DBPath)
if err != nil {
return nil, err
}
return db, nil
}
+58
View File
@@ -0,0 +1,58 @@
package models
import (
"database/sql"
"errors"
"testing"
"github.com/DATA-DOG/go-sqlmock"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)
type mockDB struct{ mock.Mock }
func newMockDB() *mockDB {
return &mockDB{}
}
func (d *mockDB) openDB() (*sql.DB, error) {
args := d.Called()
return args.Get(0).(*sql.DB), args.Error(1)
}
func TestNewModel_Success(t *testing.T) {
// Arrange
db, _, err := sqlmock.New()
assert.NoError(t, err)
defer db.Close()
var mock mockDB
mock.On("openDB").Return(db, nil)
// Act
m, err := NewModel(&mock)
// Assert
assert.NoError(t, err)
assert.NotNil(t, m)
}
func TestNewModel_FailOnOpenDB(t *testing.T) {
// Arrange
db, _, err := sqlmock.New()
assert.NoError(t, err)
defer db.Close()
var mock mockDB
mock.On("openDB").Return(db, errors.New("failed to open db"))
// Act
_, err = NewModel(&mock)
// Assert
assert.Error(t, err)
}
func TestOpenDB_Success(t *testing.T) {
}
+23 -17
View File
@@ -14,18 +14,23 @@ type User struct {
Plafond float32
}
func (u *User) PtrFields() []any {
return []any{&u.Id, &u.Name, &u.Email, &u.Role, &u.Plafond}
}
// TODO
// Replace Query with QueryRow when looking for a single entry
// private
// getUserPass will return the password (encrypted) of the user that is trying to log in
func getUserPass(user string) (string, error) {
d := OpenDB()
func getUserPass(db *sql.DB, user string) (string, error) {
query := `
SELECT password FROM users WHERE name='` + user + `';
`
rows, err := d.DB.Query(query)
rows, err := db.Query(query)
if err != nil {
log.Fatal("Failed to get user data: ", err)
log.Println("failed to get user data: ", err)
return "", err
}
defer rows.Close()
@@ -33,7 +38,7 @@ func getUserPass(user string) (string, error) {
var p string
for rows.Next() {
if err := rows.Scan(&p); err != nil {
log.Fatal(" | getUserPass | Failed to read row ->", err)
log.Fatal("failed to read row ->", err)
}
}
@@ -45,6 +50,7 @@ func getUserPass(user string) (string, error) {
return p, nil
}
// getUserDataById returns a *User from the DB given the ID
func getUserDataById(db *sql.DB, id int) (*User, error) {
query := `
SELECT id,name,email,role,plafond FROM users WHERE id='` + strconv.Itoa(id) + `';
@@ -52,15 +58,16 @@ func getUserDataById(db *sql.DB, id int) (*User, error) {
rows, err := db.Query(query)
if err != nil {
log.Fatal("| models | getUserDataById | Failed to get user data: ", err)
log.Println("failed to get user data: ", err)
return nil, err
}
defer rows.Close()
var user User
for rows.Next() {
if err := rows.Scan(&user.Id, &user.Name, &user.Email, &user.Role, &user.Plafond); err != nil {
log.Fatal("| getUserDataById | Failed to read row.", err)
if err := rows.Scan(user.PtrFields()...); err != nil {
log.Println("failed to read row.", err)
return nil, err
}
}
@@ -74,7 +81,7 @@ func getUserDataByName(db *sql.DB, name string) (*User, error) {
rows, err := db.Query(query)
if err != nil {
log.Fatal("Failed to get user data: ", err)
log.Fatal("failed to get user data: ", err)
return nil, err
}
defer rows.Close()
@@ -82,7 +89,8 @@ func getUserDataByName(db *sql.DB, name string) (*User, error) {
var user User
for rows.Next() {
if err := rows.Scan(&user.Id, &user.Name, &user.Email, &user.Role, &user.Plafond); err != nil {
log.Fatal("| getUserDataByName | Failed to read row.", err)
log.Println("failed to read row.", err)
return nil, err
}
}
@@ -90,14 +98,12 @@ func getUserDataByName(db *sql.DB, name string) (*User, error) {
}
// public
func GetUserData(id int) *User {
db := OpenDB()
data, _ := getUserDataById(db.DB, id)
func (m *Model) GetUserData(id int) *User {
data, _ := getUserDataById(m.DB, id)
return data
}
func GetUserDataByName(name string) *User {
db := OpenDB()
data, _ := getUserDataByName(db.DB, name)
func (m *Model) GetUserDataByName(name string) *User {
data, _ := getUserDataByName(m.DB, name)
return data
}
+49 -1
View File
@@ -1,6 +1,7 @@
package models
import (
"errors"
"strconv"
"testing"
@@ -8,7 +9,7 @@ import (
"github.com/stretchr/testify/assert"
)
func TestGetUser(t *testing.T) {
func TestGetUserDataById_Success(t *testing.T) {
// Create a new sqlmock database connection and mock
db, mock, err := sqlmock.New()
assert.NoError(t, err)
@@ -43,3 +44,50 @@ func TestGetUser(t *testing.T) {
err = mock.ExpectationsWereMet()
assert.NoError(t, err)
}
func TestGetUserDataById_QueryFails(t *testing.T) {
// Create a new sqlmock database connection and mock
db, mock, err := sqlmock.New()
assert.NoError(t, err)
defer db.Close()
// Define the expected query and result set
userID := 3
query := `SELECT id,name,email,role,plafond FROM users WHERE id='` + strconv.Itoa(userID) + `';`
mock.ExpectQuery(query).WillReturnError(errors.New("stuff"))
// Call the function
user, err := getUserDataById(db, userID)
assert.Error(t, err)
assert.Nil(t, user)
// Ensure all expectations were met
err = mock.ExpectationsWereMet()
assert.NoError(t, err)
}
func TestGetUserDataById_ScanFails(t *testing.T) {
// Create a new sqlmock database connection and mock
db, mock, err := sqlmock.New()
assert.NoError(t, err)
defer db.Close()
// Define the expected query and result set
userID := 3
query := `SELECT id,name,email,role,plafond FROM users WHERE id='` + strconv.Itoa(userID) + `';`
rows := sqlmock.NewRows([]string{"id", "name", "email", "role", "plafond"}).
AddRow("NotAnID", "John Doe", "john@example.com", "admin", 1000.0)
mock.ExpectQuery(query).WillReturnRows(rows)
// Call the function
user, err := getUserDataById(db, userID)
assert.Error(t, err)
assert.Nil(t, user)
// Ensure all expectations were met
err = mock.ExpectationsWereMet()
assert.NoError(t, err)
}
+1 -1
View File
@@ -86,6 +86,6 @@ func Serve() {
// 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.Println("starting server on port 8083")
log.Fatal(http.ListenAndServe(":8083", nil))
}