Junior
Describe the login process in a system.
sobes.tech AI
Answer from AI
- The user enters login credentials (username and password) on the login page.
- The browser sends an HTTP POST request to the server with the entered data.
- The server receives the request and passes the credentials to the authentication component.
- The authentication component compares the received data with the information in the user database:
- Checks for the existence of a user with such a login.
- Hashes the entered password and compares it with the stored password hash for that user.
- In case of successful authentication:
- The server creates a session for the user or generates an access token (e.g., JWT).
- The session/token is associated with the user's unique identifier and contains information about their access rights.
- The server sends an HTTP response with a 200 OK status and transmits the session (via cookie) or access token to the user's browser.
- The browser saves the cookie or token.
- The user is redirected to the main or target page.
- In case of failed authentication (incorrect login or password):
- The server sends an HTTP response with an error code (e.g., 401 Unauthorized) and an error message.
- The browser displays an error message to the user on the login page.
- For subsequent requests to protected resources, the browser automatically sends the saved session (cookie) or access token in the HTTP request headers.
- The server verifies the validity of the session/token and grants access to the resource if authentication is confirmed and the user has the necessary rights.
Example (pseudocode):
# On the server
def login(username, password):
user = database.find_user(username)
if user and hash(password) == user.hashed_password:
session_id = generate_session_id(user.id)
database.save_session(session_id, user.id)
return {"status": "success", "session_id": session_id}
else:
return {"status": "fail", "message": "Invalid credentials"}
# On the client (in the browser)
async function handle_login_submit(event):
event.preventDefault();
const username = document.getElementById("username").value;
const password = document.getElementById("password").value;
const response = await fetch("/api/login", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ username, password })
});
const data = await response.json();
if (data.status === "success") {
// The server will set a cookie with session_id, or we can save the token from the response
window.location.href = "/dashboard";
} else {
alert(data.message);
}