diff --git a/faxSrc/go.mod b/faxSrc/go.mod index 55d4866..a38c52a 100644 --- a/faxSrc/go.mod +++ b/faxSrc/go.mod @@ -4,5 +4,6 @@ go 1.22.2 require ( github.com/golang-jwt/jwt/v4 v4.5.0 + github.com/mattn/go-sqlite3 v1.14.22 golang.org/x/crypto v0.22.0 ) diff --git a/faxSrc/go.sum b/faxSrc/go.sum index cac7b02..839f752 100644 --- a/faxSrc/go.sum +++ b/faxSrc/go.sum @@ -1,4 +1,6 @@ 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/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= golang.org/x/crypto v0.22.0 h1:g1v0xeRhjcugydODzvb3mEM9SQ0HGp9s/nh3COQ/C30= golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M= diff --git a/faxSrc/models/authentication.go b/faxSrc/models/authentication.go index cd50699..9c5ddeb 100644 --- a/faxSrc/models/authentication.go +++ b/faxSrc/models/authentication.go @@ -8,50 +8,12 @@ import ( "golang.org/x/crypto/bcrypt" ) -var DATABASE map[string]string = map[string]string{ - "user": "$2y$08$ZBb/RxlrNHcA.YNasvGlhOeUmJVZe/clNelP4jwBpkpq/r4mE.lze", -} - type Authenticator interface { isAuthorised(string, string) bool Authenticate(w http.ResponseWriter, r *http.Request) bool } type Authentication struct{} -// 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 -} - type LoginForm struct { Username string `json:"username"` Password string `json:"password"` @@ -61,13 +23,50 @@ type Claims struct { jwt.RegisteredClaims } -func ValidateCredentials(lf *LoginForm) bool { - p, ok := DATABASE[lf.Username] - if !ok { - return false +// Private functions + +func getUserPass(user string) (string, error) { + var d SQLite + err := d.Initialize("../src/data.db") + if err != nil { + log.Fatal("Failed to get into DB: ", err) } - err := bcrypt.CompareHashAndPassword([]byte(p), []byte(lf.Password)) + query := ` + SELECT password FROM users WHERE name='` + user + `'; + ` + + rows, err := d.DB.Query(query) + if err != nil { + log.Fatal("Failed to get user data: ", err) + return "", err + } + defer rows.Close() + + var p string + for rows.Next() { + if err := rows.Scan(&p); err != nil { + log.Fatal("Failed to read row.", err) + } + } + + // No password found (user doesn't exist?) + if len(p) == 0 { + return "", nil + } + + return p, nil +} + +// Public functions + +func ValidateCredentials(lf *LoginForm) bool { + passwd, err := getUserPass(lf.Username) + if err != nil { + log.Fatal("Failed to get password from DB: ", err) + } + + err = bcrypt.CompareHashAndPassword([]byte(passwd), []byte(lf.Password)) return err == nil } diff --git a/faxSrc/models/basicAuth.go b/faxSrc/models/basicAuth.go new file mode 100644 index 0000000..6b002ba --- /dev/null +++ b/faxSrc/models/basicAuth.go @@ -0,0 +1,37 @@ +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/faxSrc/models/dbAccess.go b/faxSrc/models/dbAccess.go new file mode 100644 index 0000000..5ed593e --- /dev/null +++ b/faxSrc/models/dbAccess.go @@ -0,0 +1,49 @@ +package models + +import ( + "database/sql" + + _ "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 SQLite struct { + DB *sql.DB + Path string +} + +func (s *SQLite) Initialize(path string) error { + db, err := sql.Open("sqlite3", path) + if err != nil { + return err + } + + s.Path = path + s.DB = db + + return nil +} + +func (s *SQLite) Createq(query string) error { + return nil +} + +func (s *SQLite) Selectq(query string) error { + return nil +} + +func (s *SQLite) Deleteq(query string) error { + return nil +} + +func (s *SQLite) Updateq(query string) error { + return nil +} diff --git a/faxSrc/usefulQueries.sql b/faxSrc/usefulQueries.sql new file mode 100644 index 0000000..df05320 --- /dev/null +++ b/faxSrc/usefulQueries.sql @@ -0,0 +1,16 @@ +-- Generate a password +-- htpasswd -bnBC 10 "" kika | tr -d ':\n' + +CREATE TABLE IF NOT EXISTS users( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL UNIQUE, + password TEXT NOT NULL +); + +-- pass is kika here +INSERT INTO + users(name, password) + values( + 'kika', + '$2y$10$JgmGJBRPqJB5/S9gL24nC.JuMj.wnFmUHBwENCGFboCzeNATmu.rq%' + ); \ No newline at end of file