Socialify

Folder ..

Viewing login.js
39 lines (37 loc) • 903.0 B

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
$(".ui.form").form({
  fields: {
    username: "empty",
    password: "empty",
  },
});

function login(event) {
  event.preventDefault();
  const username = $("#username").val().trim();
  const password = $("#password").val().trim();

  // make sure username is a-zA-Z0-9
  if (!username.match(/^[a-zA-Z0-9]+$/)) {
    alert("Username must be alphanumeric");
    return;
  } else {
    // make request to /api/login
    fetch("/api/login", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        username,
        password,
      }),
    }).then((response) => {
      if (response.status === 200) {
        response.json().then((data) => {
          localStorage.setItem("token", data.token);
          window.location.href = "/";
        });
      } else {
        alert("Invalid username or password");
      }
    });
  }
}