]> git.cworth.org Git - lmno.games/blobdiff - lmno.js
Add JavaScript handling for the recently-added login form
[lmno.games] / lmno.js
diff --git a/lmno.js b/lmno.js
index e4785a86d4fe8ae282ae2102a3c3bebaf2b8f414..5cd5802856c79e9fdcad6a738de1bd1cb1175070 100644 (file)
--- a/lmno.js
+++ b/lmno.js
@@ -11,18 +11,52 @@ ${message}
   message_area.insertAdjacentHTML('beforeend', message);
 }
 
-function join_loadend(request, game_id) {
+function lmno_login_loadend(request, username) {
+  if (request.status === 404) {
+    add_message("danger", "User authentication failed. Please try again.");
+    return;
+  }
+
+  /* Now that user is logged in, advance to the desired page (if any). */
+  const url = new URL(window.location);
+  const next_param = url.searchParams.get('next');
+  if (next_param) {
+    window.location.href = next_param;
+    return;
+  }
+
+  /* Otherwise, just report the successful login. */
+  add_message("success", `User ${username} logged in. Have fun.`);
+}
+
+function lmno_login(form) {
+  const username = form.username.value;
+  const password = form.password.value;
+
+  console.log("In lmno_login with username: " + username);
+  var request = new XMLHttpRequest();
+  request.addEventListener("loadend", () => lmno_login_loadend(request, username));
+
+  request.open("POST", "/login");
+  request.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
+  request.send(`{"username": "${username}", "password": "${password}"}`);
+}
+
+function lmno_join_loadend(request, game_id) {
   if (request.status === 404) {
     add_message("danger", game_id + " is not a valid game ID. Try again.");
     return;
   }
+
+  /* Now that its validated, send the browser to the URL for the game_id. */
+  window.location.href = "/" + game_id;
 }
 
 function lmno_join(form) {
   const game_id = form.id.value;
 
   var request = new XMLHttpRequest();
-  request.addEventListener("loadend", () => join_loadend(request, game_id));
+  request.addEventListener("loadend", () => lmno_join_loadend(request, game_id));
 
   request.open("GET", "/" + game_id);
   request.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
@@ -31,7 +65,7 @@ function lmno_join(form) {
   form.reset();
 }
 
-function new_loadend() {
+function lmno_new_loadend() {
   if (this.status == 200) {
     /* Response contains the game ID which we simply point the browser to. */
     const game_id = JSON.parse(this.response);
@@ -43,9 +77,8 @@ function new_loadend() {
 }
 
 function lmno_new(engine) {
-  console.log("In lmno_new");
   const request = new XMLHttpRequest();
-  request.addEventListener("loadend", new_loadend);
+  request.addEventListener("loadend", lmno_new_loadend);
 
   request.open("POST", "/new/" + engine);
   request.setRequestHeader("Content-Type", "application/json; charset=UTF-8");