Reworked the login flow

It is looking neat, but I still have to make sure it behaves how
I want it to behave
This commit is contained in:
2024-06-10 22:27:46 +01:00
parent fd8f3720fb
commit 0c1dd26df4
8 changed files with 106 additions and 80 deletions
+25 -1
View File
@@ -3,6 +3,7 @@
<fieldset id="login-box-boundaries">
<legend>LOGIN</legend>
<div class="login-container">
<div id="login-state" class="warning"></div><br>
<!-- <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> -->
@@ -12,7 +13,30 @@
hx-swap="none"
type="submit"
id="login-submit-button">Login</button>
<br>
</div>
</fieldset>
</form>
</div>
</div>
<script>
document.body.addEventListener("wrongCredentials", function(evt) {
var messageDiv = document.getElementById("login-state")
messageDiv.innerHTML = evt.detail.value
setTimeout(() => {
messageDiv.innerHTML = ""
}, 3000);
});
// Add the spinner
var btn = document.getElementById("login-submit-button");
btn.addEventListener('htmx:beforeRequest', function (evt) {
btn.classList.add("loading");
spinner(btn)
});
btn.addEventListener('htmx:afterRequest', function (evt) {
btn.classList.remove("loading");
});
</script>
+74 -45
View File
@@ -7,6 +7,7 @@ import (
"net/http"
"thermalFax/models"
"thermalFax/scache"
"thermalFax/views"
"time"
"github.com/golang-jwt/jwt/v4"
@@ -71,7 +72,63 @@ func createSessionCookie(token string) *http.Cookie {
return &sessionCookie
}
func createNewSession(w http.ResponseWriter, loginForm models.LoginForm) {
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().Add("HX-Redirect", "/editor")
}
func updateSession(w http.ResponseWriter, loginForm models.LoginForm,
sessionCookie *http.Cookie) {
localUserSession := models.GetSession(sessionCookie.Value)
if localUserSession == nil {
// Just create a new session in this case
log.Println("| User has session key not present locally")
createNewSession(w, loginForm)
return
}
expirationTime := time.Now().Add(SESSION_INTERVAL)
cookie := http.Cookie{
Name: "token",
Value: sessionCookie.Value,
Expires: expirationTime,
}
http.SetCookie(w, &cookie)
log.Println("| User is being sent to ", localUserSession.Wants)
w.Header().Set("HX-Redirect", localUserSession.Wants)
}
func Authenticate(w http.ResponseWriter, r *http.Request) {
// DELETE THIS AFTER TESTING AND SO ON
time.Sleep(1 * time.Second)
// first we have to verify if this request brings any login data
r.ParseForm()
loginForm := models.LoginForm{
@@ -81,8 +138,7 @@ func Authenticate(w http.ResponseWriter, r *http.Request) {
if !models.ValidateCredentials(&loginForm) {
log.Println("| Invalid credentials.")
w.Header().Set("Content-Type", "text/json")
w.Write([]byte("{\"state\":\"wrong credentials\"}"))
w.Header().Add("HX-Trigger", `{"wrongCredentials":"Wrong Credentials"}`)
return
}
@@ -96,53 +152,14 @@ func Authenticate(w http.ResponseWriter, r *http.Request) {
// 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)
updateSession(w, loginForm, sessionCookie)
} 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().Add("HX-Redirect", "/editor")
createNewSession(w, loginForm)
}
}
func reauth(w http.ResponseWriter, r *http.Request) {
func saveSessionState(r *http.Request) {
cache := scache.GetInstance()
cookie := getToken(r, "fax-session")
if cookie == nil {
@@ -158,7 +175,19 @@ func reauth(w http.ResponseWriter, r *http.Request) {
}
cache.Data[tok].Wants = r.RequestURI
}
log.Println("| User wants to go to ", cache.Data[tok].Wants)
}
}
func reauth(w http.ResponseWriter, r *http.Request) {
log.Println("| User wants to request something but authentication has expired")
saveSessionState(r)
w.Header().Set("HX-Redirect", "/login")
w.Header().Set("HX-Push-Url", "true")
}
func relogin(w http.ResponseWriter, r *http.Request) {
saveSessionState(r)
views.LoginPage(w, r)
}
+1 -1
View File
@@ -8,7 +8,7 @@ import (
func Editor(w http.ResponseWriter, r *http.Request) {
authd, _ := isAuthenticated(r)
if !authd {
views.LoginPage(w, r)
relogin(w, r)
return
}
+1 -3
View File
@@ -1,7 +1,6 @@
package controllers
import (
"log"
"net/http"
"thermalFax/views"
)
@@ -9,8 +8,7 @@ import (
func History(w http.ResponseWriter, r *http.Request) {
authd, _ := isAuthenticated(r)
if !authd {
log.Println("Request history")
views.LoginPage(w, r)
relogin(w, r)
return
}
-16
View File
@@ -6,21 +6,5 @@ import (
)
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)
// }
+1 -1
View File
@@ -8,7 +8,7 @@ import (
func PersonalData(w http.ResponseWriter, r *http.Request) {
authd, _ := isAuthenticated(r)
if !authd {
views.LoginPage(w, r)
relogin(w, r)
return
}
+3 -12
View File
@@ -70,8 +70,9 @@ 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\"}"))
// We don't do a reauth here so that the user is actually sent to the
// login page and then to the /editor by default
// - We will have to make it be clear that the message was not sent tho
w.Header().Set("HX-Redirect", "/login")
return
}
@@ -88,16 +89,6 @@ func SendFax(w http.ResponseWriter, r *http.Request) {
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)
if err != nil {
+1 -1
View File
@@ -13,7 +13,7 @@ func Serve() {
case http.MethodGet:
// We redirect to the editor page, if the user is logged in he can fire a fax right away
// Otherwise it just redirects him to the login page anyway
http.Redirect(w, r, "/editor", http.StatusPermanentRedirect)
http.Redirect(w, r, "/login", http.StatusPermanentRedirect)
default:
w.WriteHeader(http.StatusMethodNotAllowed)
}