From 771166f809310898009ea8a747b14a030450acec Mon Sep 17 00:00:00 2001 From: Eduardo Silva Date: Mon, 20 May 2024 17:16:31 +0100 Subject: [PATCH] Store sessions --- faxSrc/controllers/authentication.go | 5 ++++ faxSrc/models/authentication.go | 42 +++++++++++++++++++++++++++- faxSrc/usefulQueries.sql | 7 +++++ 3 files changed, 53 insertions(+), 1 deletion(-) diff --git a/faxSrc/controllers/authentication.go b/faxSrc/controllers/authentication.go index 33230e2..d6f57bf 100644 --- a/faxSrc/controllers/authentication.go +++ b/faxSrc/controllers/authentication.go @@ -69,5 +69,10 @@ func Authenticate(w http.ResponseWriter, r *http.Request) { } http.SetCookie(w, &cookie) + err = models.StoreSessionToken(tokenString, loginForm.Username, expirationTime.Unix()) + if err != nil { + log.Fatal("Failed to store session token: ", err) + } + log.Printf(`| {"user": %s, "time": %d}`, loginForm.Username, time.Now().Unix()) } diff --git a/faxSrc/models/authentication.go b/faxSrc/models/authentication.go index 9c5ddeb..8e0b6c5 100644 --- a/faxSrc/models/authentication.go +++ b/faxSrc/models/authentication.go @@ -3,6 +3,7 @@ package models import ( "log" "net/http" + "strconv" "github.com/golang-jwt/jwt/v4" "golang.org/x/crypto/bcrypt" @@ -25,13 +26,19 @@ type Claims struct { // Private functions -func getUserPass(user string) (string, error) { +func openDB() *SQLite { var d SQLite err := d.Initialize("../src/data.db") if err != nil { log.Fatal("Failed to get into DB: ", err) } + return &d +} + +func getUserPass(user string) (string, error) { + d := openDB() + query := ` SELECT password FROM users WHERE name='` + user + `'; ` @@ -58,6 +65,30 @@ func getUserPass(user string) (string, error) { return p, nil } +func insertToken(token string, user string, expirationDate int64) error { + d := openDB() + + query := ` + INSERT INTO + sessions(user, token, expires) + values( + '` + user + `', + '` + token + `', + ` + strconv.Itoa(int(expirationDate)) + ` + ); + ` + + log.Println(query) + + _, err := d.DB.Exec(query) + if err != nil { + log.Fatal("Failed to insert data: ", err) + return err + } + + return nil +} + // Public functions func ValidateCredentials(lf *LoginForm) bool { @@ -70,3 +101,12 @@ func ValidateCredentials(lf *LoginForm) bool { return err == nil } + +func StoreSessionToken(token string, user string, expirationDate int64) error { + err := insertToken(token, user, expirationDate) + if err != nil { + log.Fatal("Unable to insert token into DB: ", err) + } + + return nil +} diff --git a/faxSrc/usefulQueries.sql b/faxSrc/usefulQueries.sql index df05320..ac17793 100644 --- a/faxSrc/usefulQueries.sql +++ b/faxSrc/usefulQueries.sql @@ -7,6 +7,13 @@ CREATE TABLE IF NOT EXISTS users( password TEXT NOT NULL ); +CREATE TABLE IF NOT EXISTS sessions( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user TEXT NOT NULL UNIQUE, + token TEXT NOT NULL, + expires INTEGER +); + -- pass is kika here INSERT INTO users(name, password)