Files
msgs/web/js/login.js
T
wt b833266664
Continuous integration / Check (push) Successful in 35s
Continuous integration / Rustfmt (push) Successful in 31s
Continuous integration / build (push) Successful in 30s
Continuous integration / build-release (push) Successful in 51s
more refactor in frontend javascript
2025-11-28 02:28:52 +07:00

95 lines
2.5 KiB
JavaScript

async function login() {
const phone = document.getElementById("loginPhone").value.trim();
const password = document.getElementById("loginPassword").value;
if (!phone || !password) {
showAlert("Please fill all fields", "error");
return;
}
try {
const response = await fetch("/api/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ phone, password }),
});
const data = await response.json();
if (data.success) {
localStorage.setItem("chatToken", data.token);
localStorage.setItem("chatUsername", data.username);
localStorage.setItem("chatUserPhone", phone);
currentUser = data.username;
currentToken = data.token;
currentUserPhone = phone;
// Get user profile to load avatar
const profileResponse = await fetch("/api/profile", {
headers: {
Authorization: `Bearer ${currentToken}`,
},
});
if (profileResponse.ok) {
const profile = await profileResponse.json();
currentUserAvatar = profile.avatar_url;
}
document.getElementById("authContainer").style.display = "none";
document.getElementById("chatContainer").style.display = "flex";
updateUserProfile();
loadChats();
connectWebSocket();
} else {
showAlert(data.message, "error");
}
} catch (error) {
showAlert("Login failed. Please try again.", "error");
}
}
function logout() {
localStorage.removeItem("chatToken");
localStorage.removeItem("chatUsername");
localStorage.removeItem("chatUserPhone");
closeProfileModal();
if (ws) {
ws.close();
ws = null;
}
clearReconnection();
currentUser = "";
currentToken = "";
currentRecipient = "";
currentUserAvatar = "";
currentUserPhone = "";
chats = [];
searchResults = [];
messageHistory = {};
document.getElementById("authContainer").style.display = "block";
document.getElementById("chatContainer").style.display = "none";
document.getElementById("loginPhone").value = "";
document.getElementById("loginPassword").value = "";
document.getElementById("registerPhone").value = "";
document.getElementById("registerUsername").value = "";
document.getElementById("registerPassword").value = "";
showTab("login");
}
document
.getElementById("loginPassword")
.addEventListener("keypress", function (e) {
if (e.key === "Enter") login();
});
document.getElementById("loginPhone").focus();