New repo to host the frontend, it made no sense having it where it was

This commit is contained in:
2024-05-26 21:41:34 +01:00
commit 29175824b4
71 changed files with 12002 additions and 0 deletions
+78
View File
@@ -0,0 +1,78 @@
package controllers
import (
"encoding/json"
"io"
"log"
"net/http"
"thermalFax/models"
"time"
"github.com/golang-jwt/jwt/v4"
)
func isAuthenticated(r *http.Request) (bool, string) {
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
}
}
return false, ""
}
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 {
log.Printf("Error: %s", err)
return
}
var loginForm models.LoginForm
err = json.Unmarshal(data, &loginForm)
if err != nil {
log.Printf("Error: %s", err)
return
}
if !models.ValidateCredentials(&loginForm) {
log.Printf("Invalid credentials.")
return
}
// Generate the thing
expirationTime := time.Now().Add(2 * time.Minute)
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 {
log.Printf("Failed to create the token.")
return
}
cookie := http.Cookie{
Name: "token",
Value: tokenString,
Expires: expirationTime,
}
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())
}
+16
View File
@@ -0,0 +1,16 @@
package controllers
import (
"net/http"
"thermalFax/views"
)
func EditorPage(w http.ResponseWriter, r *http.Request) {
authd, _ := isAuthenticated(r)
if !authd {
views.LoginPage(w, r)
return
}
views.EditorPage(w, r)
}
+153
View File
@@ -0,0 +1,153 @@
package controllers
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"strings"
"time"
"unicode/utf8"
"thermalFax/models"
)
type PrintServerResponse struct {
Message string `json:"result"`
}
type WebFrontendRequest struct {
Message string `json:"fax_message"`
}
type WebFrontendResponse struct {
State string `json:"state"`
}
// SendRequestToPrinter function will request the thermal printer
// to print the message.
// It should be able to send the requests both via http/https or sockets
func sendRequestToPrinter(msg string) (PrintServerResponse, error) {
// Send the request to the actual printer server
req, err := http.NewRequest(
http.MethodPost,
"http://127.0.0.1:9099/print",
bytes.NewBuffer([]byte(msg)),
)
if err != nil {
errStr := fmt.Sprintf("Failed to create new request: %s", err)
return PrintServerResponse{}, errors.New(errStr)
}
// Perform the request
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
errStr := fmt.Sprintf("Failed to perform new request: %s", err)
return PrintServerResponse{}, errors.New(errStr)
}
// Process the request data
out, _ := io.ReadAll(res.Body)
var resp PrintServerResponse
err = json.Unmarshal(out, &resp)
if err != nil {
errStr := fmt.Sprintf("Failed to unmarshall response: %s", err)
return PrintServerResponse{}, errors.New(errStr)
}
return resp, nil
}
// 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) {
authd, token := isAuthenticated(r)
if !authd {
w.Header().Set("Content-Type", "text/json")
w.Write([]byte("{\"state\":\"unauthenticated\"}"))
return
}
session, _ := models.GetSession(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
}
msg := signMessage(formData.Message, session.User, time.Now().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
}
w.Header().Set("Content-Type", "text/json")
w.Write([]byte("{\"state\":\"success\"}"))
}
// NOTE: this isn't multi-Unicode-codepoint aware, like specifying skintone or
// gender of an emoji: https://unicode.org/emoji/charts/full-emoji-modifiers.html
// This thing was straight up copied from SO
func substr(input string, start int, length int) string {
asRunes := []rune(input)
if start >= len(asRunes) {
return ""
}
if start+length > len(asRunes) {
length = len(asRunes) - start
}
return string(asRunes[start : start+length])
}
// truncateString given a string and a lim truncates that string if its longer than the lim
// with "..."
func truncateString(s string, lim int) string {
runeCount := utf8.RuneCountInString(s)
if runeCount > lim {
s = substr(s, 0, lim-3) + "..."
} else {
s = s + strings.Repeat(" ", lim-runeCount)
}
return s
}
// signMessage adds a small box to the message so the reader knows who sent it and the time
func signMessage(msg string, user string, time string) string {
// defWidht := 48
nameWidth := 39
userLine := "| User: "
userLine = userLine + truncateString(user, nameWidth) + "|"
// defWidht := 48
timeWidth := 39
timeLine := "| Time: "
timeLine = timeLine + truncateString(time, timeWidth) + "|"
sign := fmt.Sprintf(`
+----------------------------------------------+
%s
%s
+----------------------------------------------+`,
userLine, timeLine)
truncation := "+- END ---------------------------------- END -+"
return sign + "\n" + msg + "\n\n" + truncation
}
+155
View File
@@ -0,0 +1,155 @@
package controllers
import (
"testing"
"unicode/utf8"
)
func TestSignMessage_NormalUserName(t *testing.T) {
// Arrange
user := "Alice"
msg := "Hello, world!"
tm := "2024-05-31 15:02:23"
expectedOutput := `
+----------------------------------------------+
| User: Alice |
| Time: 2024-05-31 15:02:23 |
+----------------------------------------------+
Hello, world!
+- END ---------------------------------- END -+`
// Act
result := signMessage(msg, user, tm)
// Assert
if result != expectedOutput {
t.Errorf("Expected:\n%v\nGot:\n%v", expectedOutput, result)
}
}
func TestSignMessage_VeryLongUserName(t *testing.T) {
// Arrange
user := "Alice Cuja Mãe Deu Um Nome Demasiado Longo"
msg := "Hello, world!"
tm := "2024-05-31 15:02:23"
expectedOutput := `
+----------------------------------------------+
| User: Alice Cuja Mãe Deu Um Nome Demasiado...|
| Time: 2024-05-31 15:02:23 |
+----------------------------------------------+
Hello, world!
+- END ---------------------------------- END -+`
// Act
result := signMessage(msg, user, tm)
// Assert
if result != expectedOutput {
t.Errorf("Expected:\n%v\nGot:\n%v", expectedOutput, result)
}
}
func TestSignMessage_UserNameMatchesAvailableSpace(t *testing.T) {
// Arrange
user := "Alice Cuja Mãe Deu Um Nome Demasiado Lo"
msg := "Hello, world!"
tm := "2024-05-31 15:02:23"
expectedOutput := `
+----------------------------------------------+
| User: Alice Cuja Mãe Deu Um Nome Demasiado Lo|
| Time: 2024-05-31 15:02:23 |
+----------------------------------------------+
Hello, world!
+- END ---------------------------------- END -+`
// Act
result := signMessage(msg, user, tm)
// Assert
if result != expectedOutput {
t.Errorf("Expected:\n%v\nGot:\n%v", expectedOutput, result)
}
}
func TestTruncateString_StringLargerThenLim(t *testing.T) {
// Arrange
user := "umnomeextrasuperduperlongoesperoqueistochegue"
expected := "umnomeextrasuperduperlongoesperoquei..."
// Act
result := truncateString(user, 39)
// Assert
if result != expected {
t.Errorf("Expected:\n%v\nGot:\n%v", expected, result)
}
}
func TestTruncateString_StringSmallerThenLim(t *testing.T) {
// Arrange
user := "umnome"
expected := "umnome "
// Act
result := truncateString(user, 39)
// Assert
if result != expected {
t.Errorf("Expected:\n%v\nGot:\n%v", expected, result)
}
}
func TestTruncateString_StringEqualsThenLim(t *testing.T) {
// Arrange
user := "umnomeextrasuperduperlongoesperoqueisto"
expected := "umnomeextrasuperduperlongoesperoqueisto"
// Act
result := truncateString(user, 39)
// Assert
if result != expected {
t.Errorf("Expected:\n%v\nGot:\n[%v]", expected, result)
}
}
// This is the right method to use to get the number of characters
// in a string
func TestRuneCount(t *testing.T) {
// Arrange
str := "Mãe"
expected := 3
// Act
result := utf8.RuneCountInString(str)
// Assert
if result != expected {
t.Errorf("Expected:\n%v\nGot:\n%v", expected, result)
}
}
func TestSubstr_Correct(t *testing.T) {
// Arrange
str := "Mãe"
expected := "M"
// Act
result := substr(str, 0, 1)
// Assert
if result != expected {
t.Errorf("Expected:\n%v\nGot:\n%v", expected, result)
}
}