@@ -15,79 +19,31 @@
\ No newline at end of file
diff --git a/src/assets/htmx/history.html b/src/assets/htmx/history.html
new file mode 100644
index 0000000..4a2c281
--- /dev/null
+++ b/src/assets/htmx/history.html
@@ -0,0 +1 @@
+Hello, there!
\ No newline at end of file
diff --git a/src/assets/htmx/login.html b/src/assets/htmx/login.html
index 7595f65..763136a 100644
--- a/src/assets/htmx/login.html
+++ b/src/assets/htmx/login.html
@@ -18,12 +18,14 @@
var loginForm = document.getElementById("login-form")
function handleSuccessfulPOST(data) {
+ console.log(data)
const response = JSON.parse(data)
// Need to add something that acts when the password is wrong
// so that the user knows whats going on
if (response["state"] === "success") {
- window.location.replace(window.location.origin + "/")
+ var endpoint = response["page"];
+ window.location.replace(window.location.origin + endpoint)
}
}
diff --git a/src/assets/htmx/loginModal.html b/src/assets/htmx/loginModal.html
new file mode 100644
index 0000000..96798f5
--- /dev/null
+++ b/src/assets/htmx/loginModal.html
@@ -0,0 +1,14 @@
+
+
+
\ No newline at end of file
diff --git a/src/assets/htmx/panic.tmpl b/src/assets/htmx/panic.html
similarity index 100%
rename from src/assets/htmx/panic.tmpl
rename to src/assets/htmx/panic.html
diff --git a/src/assets/htmx/personalData.html b/src/assets/htmx/personalData.html
new file mode 100644
index 0000000..a31d791
--- /dev/null
+++ b/src/assets/htmx/personalData.html
@@ -0,0 +1 @@
+Personal Data Alright
\ No newline at end of file
diff --git a/src/assets/htmx/terminal.tmpl b/src/assets/htmx/terminal.html
similarity index 53%
rename from src/assets/htmx/terminal.tmpl
rename to src/assets/htmx/terminal.html
index 5387d4c..e07135b 100644
--- a/src/assets/htmx/terminal.tmpl
+++ b/src/assets/htmx/terminal.html
@@ -24,26 +24,33 @@
hx-target="#container"
hx-replace-url="true">ESILVA.ORG
-
+ {{ if .renderNavBar }}
+
+
+ {{ end }}
{{ .content }}
diff --git a/src/cmd/root.go b/src/cmd/root.go
index f80651b..b3fa464 100644
--- a/src/cmd/root.go
+++ b/src/cmd/root.go
@@ -6,6 +6,7 @@ package cmd
import (
"os"
"thermalFax/config"
+ "thermalFax/scache"
"thermalFax/server"
"github.com/spf13/cobra"
@@ -13,11 +14,11 @@ import (
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()
+ config.GetInstance(cfgPath, nil)
+ scache.GetInstance()
+
+ server.Serve()
}
// rootCmd represents the base command when called without any subcommands
diff --git a/src/controllers/authentication.go b/src/controllers/authentication.go
index 4da5d24..375ce22 100644
--- a/src/controllers/authentication.go
+++ b/src/controllers/authentication.go
@@ -2,31 +2,79 @@ package controllers
import (
"encoding/json"
+ "errors"
+ "fmt"
"io"
"log"
"net/http"
"thermalFax/models"
+ "thermalFax/scache"
"time"
"github.com/golang-jwt/jwt/v4"
)
-func isAuthenticated(r *http.Request) (bool, string) {
+var (
+ SESSION_INTERVAL = 2 * time.Minute
+)
+
+func getToken(r *http.Request, tokenName string) *http.Cookie {
cookies := r.Cookies()
for _, c := range cookies {
- if c.Name == "token" {
- // Check if the token exists and if its date is valid
- expirationTime := time.Now()
- return expirationTime.Unix() >= c.Expires.Unix(), c.Value
+ if c.Name == tokenName {
+ return c
}
}
- return false, ""
+ return nil
+}
+
+func isAuthenticated(r *http.Request) (bool, string) {
+ token := getToken(r, "token")
+ if token == nil {
+ return false, ""
+ }
+
+ expirationTime := time.Now()
+ return expirationTime.Unix() >= token.Expires.Unix(), token.Value
+}
+
+func createAuthCookie(loginForm models.LoginForm) (*http.Cookie, error) {
+ expirationTime := time.Now().Add(SESSION_INTERVAL)
+ claims := models.Claims{
+ RegisteredClaims: jwt.RegisteredClaims{
+ Subject: loginForm.Username,
+ ExpiresAt: jwt.NewNumericDate(expirationTime),
+ },
+ }
+
+ token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
+ tokenString, err := token.SignedString([]byte("secret"))
+ if err != nil {
+ errStr := fmt.Sprintf("Failed to create the token: %s", err)
+ return nil, errors.New(errStr)
+ }
+
+ cookie := http.Cookie{
+ Name: "token",
+ Value: tokenString,
+ Expires: expirationTime,
+ }
+
+ return &cookie, nil
+}
+
+func createSessionCookie(token string) *http.Cookie {
+ sessionCookie := http.Cookie{
+ Name: "fax-session",
+ Value: token,
+ }
+
+ return &sessionCookie
}
func Authenticate(w http.ResponseWriter, r *http.Request) {
// first we have to verify if this request brings any login data
- // Otherwise we login, which we will do everytime lmao
data, err := io.ReadAll(r.Body)
if err != nil {
@@ -48,36 +96,92 @@ func Authenticate(w http.ResponseWriter, r *http.Request) {
return
}
- // Generate the thing
- expirationTime := time.Now().Add(2 * time.Minute)
- claims := models.Claims{
- RegisteredClaims: jwt.RegisteredClaims{
- Subject: loginForm.Username,
- ExpiresAt: jwt.NewNumericDate(expirationTime),
- },
+ // First check if there is an active session
+ sessionCookie := getToken(r, "fax-session")
+ userReqSession := false
+ if sessionCookie != nil {
+ userReqSession = true
}
- token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
- tokenString, err := token.SignedString([]byte("secret"))
- if err != nil {
- log.Printf("Failed to create the token.")
- return
+ // If there is an active session we update the current session
+ if userReqSession {
+ // Update current session
+ localUserSession := models.GetSession(sessionCookie.Value)
+ if localUserSession == nil {
+ log.Panicln("| But what happened should not have happened. Blame the user")
+ }
+
+ expirationTime := time.Now().Add(SESSION_INTERVAL)
+ cookie := http.Cookie{
+ Name: "token",
+ Value: sessionCookie.Value,
+ Expires: expirationTime,
+ }
+ http.SetCookie(w, &cookie)
+
+ // w.Header().Set("HX-Redirect", localUserSession.Wants)
+ w.Header().Set("Content-Type", "text/json")
+ w.Write([]byte(`
+ {
+ "state":"success",
+ "page":"` + localUserSession.Wants + `"
+ }
+ `))
+ } else {
+ // Create a new session
+ authCookie, err := createAuthCookie(loginForm)
+ if err != nil {
+ log.Printf("Error: %s", err)
+ return
+ }
+ http.SetCookie(w, authCookie)
+
+ sessionCookie := createSessionCookie(authCookie.Value)
+ http.SetCookie(w, sessionCookie)
+
+ // Store the auth token in the database
+ err = models.StoreAuthToken(authCookie.Value, loginForm.Username, 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)
+ if err != nil {
+ log.Println("Failed to store session token: ", err)
+ return
+ }
+
+ log.Printf(`| {"user": %s, "time": %d}`, loginForm.Username, time.Now().Unix())
+
+ w.Header().Set("Content-Type", "text/json")
+ w.Write([]byte(`
+ {
+ "state":"success",
+ "page":"` + "/editor" + `"
+ }
+ `))
}
+}
- cookie := http.Cookie{
- Name: "token",
- Value: tokenString,
- Expires: expirationTime,
+func reauth(w http.ResponseWriter, r *http.Request) {
+ cache := scache.GetInstance()
+ cookie := getToken(r, "fax-session")
+ if cookie == nil {
+ log.Println("The cookie is nil. It should not be")
}
- http.SetCookie(w, &cookie)
- err = models.StoreSessionToken(tokenString, loginForm.Username, expirationTime.Unix())
- if err != nil {
- log.Fatal("Failed to store session token: ", err)
+ if cookie != nil {
+ tok := cookie.Value
+
+ if _, ok := cache.Data[tok]; !ok {
+ session := &scache.Session{}
+ cache.Data[tok] = session
+ }
+
+ cache.Data[tok].Wants = r.RequestURI
}
-
- log.Printf(`| {"user": %s, "time": %d}`, loginForm.Username, time.Now().Unix())
- w.Header().Set("Content-Type", "text/json")
- w.Write([]byte("{\"state\":\"success\"}"))
+ w.Header().Set("HX-Redirect", "/login")
}
diff --git a/src/controllers/editor.go b/src/controllers/editor.go
index 7a1f1d0..5f6c19d 100644
--- a/src/controllers/editor.go
+++ b/src/controllers/editor.go
@@ -5,7 +5,7 @@ import (
"thermalFax/views"
)
-func EditorPage(w http.ResponseWriter, r *http.Request) {
+func Editor(w http.ResponseWriter, r *http.Request) {
authd, _ := isAuthenticated(r)
if !authd {
views.LoginPage(w, r)
@@ -14,3 +14,13 @@ func EditorPage(w http.ResponseWriter, r *http.Request) {
views.EditorPage(w, r)
}
+
+func EditorPOST(w http.ResponseWriter, r *http.Request) {
+ authd, _ := isAuthenticated(r)
+ if !authd {
+ reauth(w, r)
+ return
+ }
+
+ views.EditorPagePOST(w, r)
+}
diff --git a/src/controllers/history.go b/src/controllers/history.go
new file mode 100644
index 0000000..b67597e
--- /dev/null
+++ b/src/controllers/history.go
@@ -0,0 +1,28 @@
+package controllers
+
+import (
+ "log"
+ "net/http"
+ "thermalFax/views"
+)
+
+func History(w http.ResponseWriter, r *http.Request) {
+ authd, _ := isAuthenticated(r)
+ if !authd {
+ log.Println("Request history")
+ views.LoginPage(w, r)
+ return
+ }
+
+ views.HistoryPage(w, r)
+}
+
+func HistoryPOST(w http.ResponseWriter, r *http.Request) {
+ authd, _ := isAuthenticated(r)
+ if !authd {
+ reauth(w, r)
+ return
+ }
+
+ views.HistoryPagePOST(w, r)
+}
diff --git a/src/controllers/login.go b/src/controllers/login.go
new file mode 100644
index 0000000..7f44c80
--- /dev/null
+++ b/src/controllers/login.go
@@ -0,0 +1,26 @@
+package controllers
+
+import (
+ "net/http"
+ "thermalFax/views"
+)
+
+func Login(w http.ResponseWriter, r *http.Request) {
+ authd, _ := isAuthenticated(r)
+ if !authd {
+ views.LoginPage(w, r)
+ return
+ }
+
+ views.LoginPage(w, r)
+}
+
+// func LoginPOST(w http.ResponseWriter, r *http.Request) {
+// authd, _ := isAuthenticated(r)
+// if !authd {
+// reauth(w, r)
+// return
+// }
+
+// views.LoginPagePOST(w, r)
+// }
diff --git a/src/controllers/personalData.go b/src/controllers/personalData.go
new file mode 100644
index 0000000..87c602e
--- /dev/null
+++ b/src/controllers/personalData.go
@@ -0,0 +1,26 @@
+package controllers
+
+import (
+ "net/http"
+ "thermalFax/views"
+)
+
+func PersonalData(w http.ResponseWriter, r *http.Request) {
+ authd, _ := isAuthenticated(r)
+ if !authd {
+ views.LoginPage(w, r)
+ return
+ }
+
+ views.PersonalDataPage(w, r)
+}
+
+func PersonalDataPOST(w http.ResponseWriter, r *http.Request) {
+ authd, _ := isAuthenticated(r)
+ if !authd {
+ reauth(w, r)
+ return
+ }
+
+ views.PersonalDataPagePOST(w, r)
+}
diff --git a/src/controllers/sendFax.go b/src/controllers/sendFax.go
index 09190e4..f44f4fc 100644
--- a/src/controllers/sendFax.go
+++ b/src/controllers/sendFax.go
@@ -70,28 +70,36 @@ func sendRequestToPrinter(msg string) (PrintServerResponse, error) {
func SendFax(w http.ResponseWriter, r *http.Request) {
authd, token := isAuthenticated(r)
if !authd {
- w.Header().Set("Content-Type", "text/json")
- w.Write([]byte("{\"state\":\"unauthenticated\"}"))
-
+ // w.Header().Set("Content-Type", "text/json")
+ // w.Write([]byte("{\"state\":\"unauthenticated\"}"))
+ w.Header().Set("HX-Redirect", "/login")
return
}
- session, _ := models.GetSession(token)
+ // REMOVE THIS YO
+ time.Sleep(3 * time.Second)
+
+ session, _ := models.GetAuth(token)
log.Printf("| User %s requested a fax", session.User)
- data, _ := io.ReadAll(r.Body)
-
- // Parse the JSON data that comes from the form
- var formData WebFrontendRequest
- err := json.Unmarshal(data, &formData)
- if err != nil {
- log.Println("Failed to unmarshal form data: ", err)
- w.Write([]byte("{\"state\":\"failed\"}"))
- return
+ // Parse the data that comes from the "form"
+ r.ParseForm()
+ formData := WebFrontendRequest{
+ Message: r.FormValue("fax-message"),
}
+ // Parse the JSON data that comes from the form
+ // data, _ := io.ReadAll(r.Body)
+ // var formData WebFrontendRequest
+ // err := json.Unmarshal(data, &formData)
+ // if err != nil {
+ // log.Println("Failed to unmarshal form data: ", err)
+ // w.Write([]byte("{\"state\":\"failed\"}"))
+ // return
+ // }
+
msg := signMessage(formData.Message, session.User, 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)
w.Write([]byte("{\"state\":\"failed\"}"))
diff --git a/src/models/authentication.go b/src/models/authentication.go
index 362c1a5..25b0379 100644
--- a/src/models/authentication.go
+++ b/src/models/authentication.go
@@ -5,6 +5,7 @@ import (
"net/http"
"strconv"
"thermalFax/config"
+ "thermalFax/scache"
"github.com/golang-jwt/jwt/v4"
"golang.org/x/crypto/bcrypt"
@@ -141,7 +142,7 @@ func ValidateCredentials(lf *LoginForm) bool {
return err == nil
}
-func StoreSessionToken(token string, user string, expirationDate int64) error {
+func StoreAuthToken(token string, user string, expirationDate int64) error {
err := insertToken(token, user, expirationDate)
if err != nil {
log.Fatal("Unable to insert token into DB: ", err)
@@ -150,6 +151,30 @@ func StoreSessionToken(token string, user string, expirationDate int64) error {
return nil
}
-func GetSession(token string) (*SessionData, error) {
+func StoreSessionToken(token string) error {
+ cache := scache.GetInstance()
+ if _, activeSession := cache.Data[token]; !activeSession {
+ session := &scache.Session{
+ Wants: "/editor",
+ }
+ cache.Data[token] = session
+ } else {
+ 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 GetSession(token string) *scache.Session {
+ cache := scache.GetInstance()
+ if session, ok := cache.Data[token]; ok {
+ return session
+ }
+
+ return nil
+}
+
+func GetAuth(token string) (*SessionData, error) {
return getSessionData(token)
}
diff --git a/src/scache/cache.go b/src/scache/cache.go
new file mode 100644
index 0000000..2b9935f
--- /dev/null
+++ b/src/scache/cache.go
@@ -0,0 +1,30 @@
+// This is a very temporary™ solution
+
+package scache
+
+import (
+ "sync"
+)
+
+var (
+ instance *Cache
+ once sync.Once
+)
+
+type Session struct {
+ Wants string // endpoint the user that needs reauthentication request
+}
+
+type Cache struct {
+ Data map[string]*Session
+}
+
+func GetInstance() *Cache {
+ once.Do(func() {
+ instance = &Cache{
+ Data: make(map[string]*Session),
+ }
+ })
+
+ return instance
+}
diff --git a/src/server/server.go b/src/server/server.go
index 91bb4c6..41743ac 100644
--- a/src/server/server.go
+++ b/src/server/server.go
@@ -10,7 +10,7 @@ func checkMethod(method string, r *http.Request) bool {
return r.Method == method
}
-func Server() {
+func Serve() {
// GET calls
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if !checkMethod(http.MethodGet, r) {
@@ -18,7 +18,17 @@ func Server() {
return
}
- controllers.EditorPage(w, r)
+ http.Redirect(w, r, "/login", http.StatusPermanentRedirect)
+ // controllers.Editor(w, r)
+ })
+
+ http.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) {
+ if !checkMethod(http.MethodGet, r) {
+ w.WriteHeader(http.StatusMethodNotAllowed)
+ return
+ }
+
+ controllers.Editor(w, r)
})
// POST calls
@@ -40,6 +50,35 @@ func Server() {
controllers.Authenticate(w, r)
})
+ // Pages
+ // On default add to a page on invalid methods or something like that
+ http.HandleFunc("/history", func(w http.ResponseWriter, r *http.Request) {
+ switch r.Method {
+ case http.MethodPost:
+ controllers.HistoryPOST(w, r)
+ case http.MethodGet:
+ controllers.History(w, r)
+ }
+ })
+
+ http.HandleFunc("/editor", func(w http.ResponseWriter, r *http.Request) {
+ switch r.Method {
+ case http.MethodPost:
+ controllers.EditorPOST(w, r)
+ case http.MethodGet:
+ controllers.Editor(w, r)
+ }
+ })
+
+ http.HandleFunc("/personalData", func(w http.ResponseWriter, r *http.Request) {
+ switch r.Method {
+ case http.MethodPost:
+ controllers.PersonalDataPOST(w, r)
+ case http.MethodGet:
+ controllers.PersonalData(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"))))
diff --git a/src/views/editorPage.go b/src/views/editorPage.go
index b724b10..e9fcb46 100644
--- a/src/views/editorPage.go
+++ b/src/views/editorPage.go
@@ -5,10 +5,10 @@ import "net/http"
func EditorPage(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
- mainPage := HtmlTemplate("./assets/htmx/terminal.tmpl", map[string]interface{}{
+ mainPage := HtmlTemplate("./assets/htmx/terminal.html", map[string]interface{}{
"content": HtmlTemplate("./assets/htmx/editor.html", nil),
"renderNavBar": true,
- "page": "fax",
+ "page": "editor",
})
_, err := w.Write([]byte(mainPage))
@@ -17,3 +17,13 @@ func EditorPage(w http.ResponseWriter, r *http.Request) {
return
}
}
+
+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
+ }
+}
diff --git a/src/views/historyPage.go b/src/views/historyPage.go
new file mode 100644
index 0000000..52dfbda
--- /dev/null
+++ b/src/views/historyPage.go
@@ -0,0 +1,29 @@
+package views
+
+import "net/http"
+
+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",
+ })
+
+ _, err := w.Write([]byte(mainPage))
+ if err != nil {
+ http.Error(w, "Internal error", http.StatusInternalServerError)
+ return
+ }
+}
diff --git a/src/views/loginPage.go b/src/views/loginPage.go
index a5b1fcf..e238d4b 100644
--- a/src/views/loginPage.go
+++ b/src/views/loginPage.go
@@ -9,10 +9,9 @@ func LoginPage(w http.ResponseWriter, r *http.Request) {
"script": true,
})
- loginPage := HtmlTemplate("./assets/htmx/terminal.tmpl", map[string]interface{}{
+ loginPage := HtmlTemplate("./assets/htmx/terminal.html", map[string]interface{}{
"content": loginTemplate,
- "renderNavBar": true,
- "page": "fax",
+ "renderNavBar": false,
})
_, err := w.Write([]byte(loginPage))
diff --git a/src/views/personalDataPage.go b/src/views/personalDataPage.go
new file mode 100644
index 0000000..c67a13d
--- /dev/null
+++ b/src/views/personalDataPage.go
@@ -0,0 +1,29 @@
+package views
+
+import "net/http"
+
+func PersonalDataPagePOST(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+
+ _, err := w.Write([]byte(HtmlTemplate("./assets/htmx/personalData.html", nil)))
+ if err != nil {
+ http.Error(w, "Internal error", http.StatusInternalServerError)
+ return
+ }
+}
+
+func PersonalDataPage(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+
+ mainPage := HtmlTemplate("./assets/htmx/terminal.html", map[string]interface{}{
+ "content": HtmlTemplate("./assets/htmx/personalData.html", nil),
+ "renderNavBar": true,
+ "page": "personalData",
+ })
+
+ _, err := w.Write([]byte(mainPage))
+ if err != nil {
+ http.Error(w, "Internal error", http.StatusInternalServerError)
+ return
+ }
+}