Login uses standard form instead of passing a dumb JSON

This commit is contained in:
2024-06-10 18:44:04 +01:00
parent 975654539f
commit 87788421cc
2 changed files with 65 additions and 84 deletions
+58 -54
View File
@@ -7,7 +7,11 @@
<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>
<button
hx-post="/send-login"
hx-swap="none"
type="submit"
id="login-submit-button">Login</button>
</div>
</fieldset>
</form>
@@ -15,66 +19,66 @@
{{ if .script }}
<script>
var loginForm = document.getElementById("login-form")
// var loginForm = document.getElementById("login-form")
function handleSuccessfulPOST(data) {
console.log(data)
const response = JSON.parse(data)
// 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") {
var endpoint = response["page"];
window.location.replace(window.location.origin + endpoint)
}
}
// // Need to add something that acts when the password is wrong
// // so that the user knows whats going on
// if (response["state"] === "success") {
// var endpoint = response["page"];
// window.location.replace(window.location.origin + endpoint)
// }
// }
function handleForm(e) {
e.preventDefault();
// function handleForm(e) {
// e.preventDefault();
// Get the login message from the textarea
var loginUser = document.getElementById("login-user").value;
var loginPass = document.getElementById("login-pass").value;
// // Get the login message from the textarea
// var loginUser = document.getElementById("login-user").value;
// var loginPass = document.getElementById("login-pass").value;
// Create the JSON object to send
var jsonData = {
username: loginUser,
password: loginPass,
};
// // Create the JSON object to send
// var jsonData = {
// username: loginUser,
// password: loginPass,
// };
// Configure the fetch request
fetch("/send-login", {
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 => {
// We should only do a refresh if the login is correct
handleSuccessfulPOST(data)
})
.catch(error => {
console.error(error);
});
}
// // Configure the fetch request
// fetch("/send-login", {
// 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 => {
// // We should only do a refresh if the login is correct
// handleSuccessfulPOST(data)
// })
// .catch(error => {
// console.error(error);
// });
// }
loginForm.addEventListener("submit", (e) => {
handleForm(e);
});
// loginForm.addEventListener("submit", (e) => {
// handleForm(e);
// });
// Allows to login by actuating the login button on the page
var submitBtn = document.getElementById("login-submit-button");
submitBtn.addEventListener("click", handleForm);
// // Allows to login by actuating the login button on the page
// var submitBtn = document.getElementById("login-submit-button");
// submitBtn.addEventListener("click", handleForm);
</script>
{{ end }}
+7 -30
View File
@@ -1,10 +1,8 @@
package controllers
import (
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"thermalFax/models"
@@ -75,22 +73,14 @@ func createSessionCookie(token string) *http.Cookie {
func Authenticate(w http.ResponseWriter, r *http.Request) {
// first we have to verify if this request brings any login data
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
r.ParseForm()
loginForm := models.LoginForm{
Username: r.FormValue("login-user"),
Password: r.FormValue("login-pass"),
}
if !models.ValidateCredentials(&loginForm) {
log.Printf("Invalid credentials.")
log.Println("| Invalid credentials.")
w.Header().Set("Content-Type", "text/json")
w.Write([]byte("{\"state\":\"wrong credentials\"}"))
return
@@ -119,14 +109,7 @@ func Authenticate(w http.ResponseWriter, r *http.Request) {
}
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 + `"
}
`))
w.Header().Set("HX-Redirect", localUserSession.Wants)
} else {
// Create a new session
authCookie, err := createAuthCookie(loginForm)
@@ -155,13 +138,7 @@ func Authenticate(w http.ResponseWriter, r *http.Request) {
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" + `"
}
`))
w.Header().Add("HX-Redirect", "/editor")
}
}