Login Flow
In this commit I added: More pages like history, personal data and editor with dummy content A HTMX login flow The login flow is mostly backend, I think there's nothing on the frontend made to support it. Pretty neat if I say so myself
This commit is contained in:
+19
-63
@@ -7,7 +7,11 @@
|
||||
</fieldset>
|
||||
|
||||
<br>
|
||||
<button id="fax-submit-button" type="button">Submit</button>
|
||||
<button
|
||||
hx-post="/send-fax"
|
||||
hx-swap="none"
|
||||
id="fax-submit-button"
|
||||
type="submit">Submit</button>
|
||||
<br>
|
||||
|
||||
<div id="req-result"></div>
|
||||
@@ -15,79 +19,31 @@
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// This function will persist the current editor data
|
||||
// and send the user back to the login page
|
||||
function reauth() {
|
||||
localStorage.setItem("editor-text", document.getElementById("fax-message").value)
|
||||
window.location.replace(window.location.origin + "/")
|
||||
}
|
||||
|
||||
// this will load the editor data if we have it in storage
|
||||
function loadStorageData() {
|
||||
function loadTempFax() {
|
||||
const savedContent = localStorage.getItem('editor-text');
|
||||
if (savedContent) {
|
||||
document.getElementById('fax-message').value = savedContent;
|
||||
}
|
||||
}
|
||||
|
||||
// If the fax is sent successfully we no longer need to cache it
|
||||
// We will persist in the DB
|
||||
function resetStorageData() {
|
||||
// This will store the current message in local storage
|
||||
function saveTempFax() {
|
||||
localStorage.setItem("editor-text", document.getElementById("fax-message").value)
|
||||
}
|
||||
|
||||
function handleSuccessfulPOST(data) {
|
||||
const response = JSON.parse(data)
|
||||
// Event listener so that we trigger the saveTempFax and other stuff if we want to
|
||||
var btn = document.getElementById("fax-submit-button");
|
||||
btn.addEventListener('htmx:beforeRequest', function (evt) {
|
||||
saveTempFax();
|
||||
btn.classList.add("loading");
|
||||
|
||||
var elem = document.getElementById("req-result")
|
||||
if (response["state"] === "success") {
|
||||
elem.innerHTML = "-> Fax sent successfully <-"
|
||||
resetStorageData();
|
||||
} else if (response["state"] === "unauthenticated") {
|
||||
reauth();
|
||||
} else {
|
||||
elem.innerHTML = "-> Fax failed to send <-"
|
||||
}
|
||||
}
|
||||
|
||||
// Get a reference to the submit button
|
||||
var submitBtn = document.getElementById("fax-submit-button");
|
||||
|
||||
// Add a click event listener to the submit button
|
||||
submitBtn.addEventListener("click", function () {
|
||||
// Get the fax message from the textarea
|
||||
var faxMessage = document.getElementById("fax-message").value;
|
||||
|
||||
// Create the JSON object to send
|
||||
var jsonData = {
|
||||
fax_message: faxMessage
|
||||
};
|
||||
|
||||
// Configure the fetch request
|
||||
fetch("/send-fax", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json"
|
||||
},
|
||||
body: JSON.stringify(jsonData)
|
||||
})
|
||||
.then(response => {
|
||||
// Check if the response is OK
|
||||
if (response.ok) {
|
||||
// Request was successful, handle response if needed
|
||||
return response.text();
|
||||
} else {
|
||||
// Request failed, handle error if needed
|
||||
throw new Error("Error: " + response.statusText);
|
||||
}
|
||||
})
|
||||
.then(data => {
|
||||
handleSuccessfulPOST(data)
|
||||
})
|
||||
.catch(error => {
|
||||
console.error(error);
|
||||
});
|
||||
spinner(btn)
|
||||
});
|
||||
|
||||
loadStorageData();
|
||||
btn.addEventListener('htmx:afterRequest', function (evt) {
|
||||
btn.classList.remove("loading");
|
||||
});
|
||||
|
||||
loadTempFax();
|
||||
</script>
|
||||
@@ -0,0 +1 @@
|
||||
Hello, there!
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
<div id="login-modal" class="modal">
|
||||
<form id="login-form" action="submit" data-endpoint="{{ if .page }}{{ .page }}{{ else }}/editor{{ end }}">
|
||||
<fieldset id="login-box-boundaries">
|
||||
<legend>LOGIN</legend>
|
||||
<div class="login-container">
|
||||
<!-- <label for="login-user">USERNAME</label> -->
|
||||
<input class="tui-input" type="text" name="login-user" id="login-user"><br><br>
|
||||
<!-- <label for="login-pass">PASSWORD</label> -->
|
||||
<input class="tui-input" type="password" name="login-pass" id="login-pass"><br><br>
|
||||
<button type="submit" id="login-submit-button">Login</button>
|
||||
</div>
|
||||
</fieldset>
|
||||
</form>
|
||||
</div>
|
||||
@@ -0,0 +1 @@
|
||||
Personal Data Alright
|
||||
@@ -24,26 +24,33 @@
|
||||
hx-target="#container"
|
||||
hx-replace-url="true">ESILVA.ORG</legend>
|
||||
<div id="main-container-content" class="main-container-content">
|
||||
<!-- {{ if .renderNavBar }}
|
||||
<nav id="page-navigation">
|
||||
<button
|
||||
hx-post="/fax"
|
||||
hx-target="#content"
|
||||
hx-target-5*="#doc"
|
||||
hx-swap="innerHTML"
|
||||
hx-replace-url="true"
|
||||
id="aboutMe"
|
||||
class="nav-button {{ if eq .page "fax" }}selected{{ end }}">FAX</button>
|
||||
<button
|
||||
hx-post="/homepage"
|
||||
hx-target="#content"
|
||||
hx-swap="innerHTML"
|
||||
hx-replace-url="true"
|
||||
id="projects"
|
||||
class="nav-button {{ if eq .page "homepage" }}selected{{ end }}">HOMEPAGE</button>
|
||||
</nav>
|
||||
<br>
|
||||
{{ end }} -->
|
||||
{{ if .renderNavBar }}
|
||||
<nav id="page-navigation">
|
||||
<button
|
||||
hx-post="/editor"
|
||||
hx-target="#content"
|
||||
hx-target-5*="#doc"
|
||||
hx-swap="innerHTML"
|
||||
hx-replace-url="true"
|
||||
id="editor"
|
||||
class="nav-button {{ if eq .page "editor" }}selected{{ end }}">EDITOR</button>
|
||||
<button
|
||||
hx-post="/history"
|
||||
hx-target="#content"
|
||||
hx-swap="innerHTML"
|
||||
hx-replace-url="true"
|
||||
id="history"
|
||||
class="nav-button {{ if eq .page "history" }}selected{{ end }}">HISTORY</button>
|
||||
<button
|
||||
hx-post="/personalData"
|
||||
hx-target="#content"
|
||||
hx-swap="innerHTML"
|
||||
hx-replace-url="true"
|
||||
id="personalData"
|
||||
class="nav-button {{ if eq .page "personalData" }}selected{{ end }}">PERSONAL DATA</button>
|
||||
</nav>
|
||||
<br>
|
||||
{{ end }}
|
||||
<main id="content">
|
||||
{{ .content }}
|
||||
</main>
|
||||
+5
-4
@@ -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
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
// }
|
||||
@@ -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)
|
||||
}
|
||||
+22
-14
@@ -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\"}"))
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
+41
-2
@@ -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"))))
|
||||
|
||||
|
||||
+12
-2
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user