Home  >  Article  >  Web Front-end  >  JavaScript settings login

JavaScript settings login

王林
王林Original
2023-05-22 09:55:07730browse

JavaScript is a commonly used programming language, usually used for interactive effects and dynamic data processing on Web pages. In web applications, login is a very important function, which involves issues such as the security and privacy protection of user information. Today we will explore how to use JavaScript to set up login functionality, including validating user input, handling login requests, remembering users and logging out, etc.

Verify user input

Before setting up the login function, we need to ensure that the information entered by the user is legal and valid, such as user name and password. To validate user input, we can use methods such as regular expressions, form validation, and server-side authentication.

Regular expression is a language for matching patterns, which can help us check whether the input is valid or well-formatted. For example, a simple regular expression can check whether the input is a valid email address:

function validateEmail(email) {
  const re = /^(([^<>()[]\.,;:s@"]+(.[^<>()[]\.,;:s@"]+)*)|(".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/;
  return re.test(String(email).toLowerCase());
}

Form validation is another method of validating user input. It can check the input by setting rules and error prompts. effectiveness. For example, we can use HTML and JavaScript code to validate a login form, ensuring that both the username and password are required and that the username contains at least 6 characters:

<form id="loginForm" onsubmit="return validateForm()">
  <label for="username">Username:</label>
  <input type="text" id="username" name="username" required minlength="6"><br><br>
  <label for="password">Password:</label>
  <input type="password" id="password" name="password" required><br><br>
  <input type="submit" value="Log in">
</form>

<script>
function validateForm() {
  const username = document.getElementById("username").value;
  const password = document.getElementById("password").value;
  if (username.length < 6) {
    document.getElementById("username").setCustomValidity("Username must contain at least 6 characters");
    return false;
  } else {
    document.getElementById("username").setCustomValidity("");
  }
  if (password.length < 8) {
    document.getElementById("password").setCustomValidity("Password must contain at least 8 characters");
    return false;
  } else {
    document.getElementById("password").setCustomValidity("");
  }
  return true;
}
</script>

Server-side authentication is the last line of defense. It ensures that the information entered by the user is legal and valid as it verifies that the username and password match the records in the database. For example, we can use Node.js and the Express framework to implement server-side authentication:

app.post('/login', function(req, res) {
  const username = req.body.username;
  const password = req.body.password;
  if(username === 'admin' && password === 'admin') {
    res.status(200).send('Login successful');
  } else {
    res.status(401).send('Invalid username or password');
  }
});

Handling login requests

Once the user has entered a valid username and password, and the verification has passed, we need Use it to handle login requests and create sessions. A session is an interaction method between the server and the client, which allows the server to maintain contact with the client for a certain period of time and save the user's status and information on the server.

In web applications, we can use cookies and sessions to create and manage user sessions. Among them, a cookie is a small text file that can be stored in the user's computer by the web browser and sent to the server the next time it visits the website; the session is a server-side data structure that can store and manage user status and information.

For example, we can use JavaScript code to create a session and store user information:

function login(username, password) {
  const xhr = new XMLHttpRequest();
  xhr.open('POST', '/login');
  xhr.setRequestHeader('Content-Type', 'application/json');
  xhr.onload = function() {
    if (xhr.status === 200) {
      const response = JSON.parse(xhr.responseText);
      const user = response.user;
      const sessionId = response.sessionId;
      // Save user information and sessionId in cookies
      document.cookie = `user=${user}`;
      document.cookie = `sessionId=${sessionId}`;
      // Redirect user to home page
      window.location.href = '/home';
    } else {
      alert('Invalid username or password');
    }
  };
  const data = JSON.stringify({ username: username, password: password });
  xhr.send(data);
}

In this example, we use the XMLHttpRequest object to send a POST request, sending the username and password to the server authenticating. If the login is successful, the server will return the user information and session ID, which we can store in cookies. We then redirect the user to the home page, maintaining the user session through the information in the cookie.

Remember User

After the user logs in, we can improve the user experience by remembering the username and password, and allow the user to log in automatically the next time they visit the website. This can be achieved by storing username and password in cookies.

For example, we can use JavaScript code to remember a user's username and password:

function rememberMe() {
  const username = document.getElementById('username').value;
  const password = document.getElementById('password').value;
  if (document.getElementById('rememberMe').checked) {
    // Save username and password in cookies for 30 days
    const expires = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toUTCString();
    document.cookie = `username=${username}; expires=${expires};`;
    document.cookie = `password=${password}; expires=${expires};`;
  } else {
    // Remove username and password from cookies
    document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC;";
    document.cookie = "password=; expires=Thu, 01 Jan 1970 00:00:00 UTC;";
  }
}

In this example, we use a checkbox to represent the "Remember Me" option. If the user checks this option, we store the username and password in a cookie and set the expiration time to 30 days. If the user cancels this option, we will delete the username and password from the cookie.

Log out

Finally, we need to provide a convenient way for users to log out to avoid accidental or illegal use of the user's account. Logging out requires destroying the user session and clearing the information in cookies.

For example, we can use JavaScript code to log out:

function logout() {
  const xhr = new XMLHttpRequest();
  xhr.open('POST', '/logout');
  xhr.setRequestHeader('Content-Type', 'application/json');
  xhr.onload = function() {
    if (xhr.status === 200) {
      // Remove user information and sessionId from cookies
      document.cookie = 'user=; expires=Thu, 01 Jan 1970 00:00:00 UTC;';
      document.cookie = 'sessionId=; expires=Thu, 01 Jan 1970 00:00:00 UTC;';
      // Redirect user to login page
      window.location.href = '/login';
    } else {
      alert('Logout failed');
    }
  };
  const sessionId = getCookie('sessionId');
  const data = JSON.stringify({ sessionId: sessionId });
  xhr.send(data);
}

In this example, we use the XMLHttpRequest object to send a POST request and send the session ID to the server. The server will destroy the user session and return a success status code. We will then remove the user information and session ID from the cookie and redirect the user to the login page.

Conclusion

In this article, we explored how to use JavaScript to set up login functionality, including validating user input, handling login requests, remembering users, and logging out. Login is a very important function in web applications, which involves important issues such as the security and privacy protection of user information. By using technologies such as JavaScript and server-side authentication, we can ensure that the information entered by users is legal and valid, and improve user experience and security.

The above is the detailed content of JavaScript settings login. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn