update all login-down

This commit is contained in:
2025-06-23 16:21:37 +08:00
parent 8204504f5a
commit 08239024ef
339 changed files with 34769 additions and 361 deletions

View File

@@ -16,44 +16,64 @@
.login-content {
background-color: #fefefe;
margin: 10% auto;
padding: 20px;
margin: 5% auto;
padding: 30px;
border: 1px solid #888;
width: 400px;
width: 450px;
border-radius: 15px;
box-shadow: 0 4px 8px rgba(0,0,0,0.1);
max-height: 90vh;
overflow-y: auto;
}
.login-content h2 {
text-align: center;
margin-bottom: 15px;
margin-bottom: 25px;
color: #333;
font-size: 22px;
font-size: 24px;
}
.login-form .login-type {
/* Tab styles */
.tab-container {
display: flex;
justify-content: center;
margin-bottom: 12px;
margin-bottom: 25px;
border-bottom: 1px solid #ddd;
}
.login-form .login-type label {
margin: 0 15px;
.tab-button {
flex: 1;
padding: 15px;
background: none;
border: none;
cursor: pointer;
font-size: 15px;
display: flex;
align-items: center;
font-size: 16px;
transition: all 0.3s ease;
border-bottom: 2px solid transparent;
}
.login-form .login-type input[type="radio"] {
margin-right: 5px;
width: auto;
.tab-button.active {
color: #3498db;
border-bottom-color: #3498db;
font-weight: bold;
}
.tab-button:hover {
color: #3498db;
background-color: #f8f9fa;
}
.tab-content {
display: none;
}
.tab-content.active {
display: block;
}
.login-form input {
width: 100%;
padding: 10px;
margin: 10px 0;
padding: 12px;
margin: 12px 0;
border: 1px solid #ddd;
border-radius: 8px;
box-sizing: border-box;
@@ -63,20 +83,20 @@
.login-form .code-container {
display: flex;
gap: 10px;
margin: 10px 0;
margin: 12px 0;
}
.login-form .hint-text {
font-size: 12px;
color: #666;
margin-top: 3px;
margin-bottom: 3px;
margin-bottom: 8px;
text-align: left;
}
.login-form .code-input {
flex: 3;
padding: 10px;
padding: 12px;
border: 1px solid #ddd;
border-radius: 8px;
box-sizing: border-box;
@@ -85,8 +105,9 @@
.login-form .send-code-btn {
flex: 1;
min-width: 95px;
padding: 0 8px;
min-width: 100px;
padding: 12px 10px;
height: 47px;
background-color: #3498db;
color: white;
border: none;
@@ -95,6 +116,10 @@
font-size: 14px;
transition: background-color 0.3s ease;
white-space: nowrap;
box-sizing: border-box;
display: flex;
align-items: center;
justify-content: center;
}
.login-form .send-code-btn:hover {
@@ -106,20 +131,20 @@
cursor: not-allowed;
}
.login-form button {
.login-form button[type="submit"] {
width: 100%;
padding: 10px;
padding: 12px;
background-color: #3498db;
color: white;
border: none;
border-radius: 8px;
cursor: pointer;
margin-top: 12px;
margin-top: 15px;
font-size: 16px;
transition: background-color 0.3s ease;
}
.login-form button:hover {
.login-form button[type="submit"]:hover {
background-color: #2980b9;
}
@@ -260,15 +285,35 @@
<div class="login-content">
<span class="close" onclick="closeLoginModal()">&times;</span>
<h2>Phaten Cloud Login/Register</h2>
<form id="loginForm" class="login-form">
<input type="email" id="email" placeholder="Enter your email" required>
<div class="code-container">
<input type="text" id="verificationCode" class="code-input" placeholder="Enter verification code" required>
<button type="button" id="sendCodeBtn" class="send-code-btn">Send Code</button>
</div>
<div class="hint-text">(Auto register on first login)</div>
<button type="submit">Submit</button>
</form>
<!-- Tab toggle buttons -->
<div class="tab-container">
<button class="tab-button active" onclick="switchTab('login')">Login</button>
<button class="tab-button" onclick="switchTab('register')">Register</button>
</div>
<!-- Login form -->
<div id="loginTab" class="tab-content active">
<form id="loginForm" class="login-form">
<input type="email" id="loginEmail" placeholder="Enter your email" required>
<input type="password" id="loginPassword" placeholder="Enter your password" required>
<button type="submit">Login</button>
</form>
</div>
<!-- Register form -->
<div id="registerTab" class="tab-content">
<form id="registerForm" class="login-form">
<input type="email" id="registerEmail" placeholder="Enter your email" required>
<div class="code-container">
<input type="text" id="verificationCode" class="code-input" placeholder="Enter verification code" required>
<button type="button" id="sendCodeBtn" class="send-code-btn">Send Code</button>
</div>
<input type="password" id="registerPassword" placeholder="Enter your password" required>
<input type="password" id="confirmPassword" placeholder="Confirm your password" required>
<button type="submit">Register</button>
</form>
</div>
</div>
</div>
@@ -283,36 +328,56 @@
// Get modal elements
const modal = document.getElementById("loginModal");
const loginForm = document.getElementById("loginForm");
const registerForm = document.getElementById("registerForm");
const sendCodeBtn = document.getElementById("sendCodeBtn");
const emailInput = document.getElementById("email");
let countdownTimer;
// Get message modal elements
const messageModal = document.getElementById("messageModal");
const messageTitle = document.getElementById("messageTitle");
const messageText = document.getElementById("messageText");
const messageBtn = document.getElementById("messageBtn");
const closeMessage = document.getElementsByClassName("close-message")[0];
// Get message modal elements
const messageModal = document.getElementById("messageModal");
const messageTitle = document.getElementById("messageTitle");
const messageText = document.getElementById("messageText");
const messageBtn = document.getElementById("messageBtn");
const closeMessage = document.getElementsByClassName("close-message")[0];
// Show custom message modal
function showMessage(title, text, type = 'info') {
messageTitle.textContent = title;
messageText.textContent = text;
// Set style based on type
messageText.className = type === 'success' ? 'success' : (type === 'error' ? 'error' : '');
messageModal.style.display = "block";
}
// Tab switching functionality
window.switchTab = function(tabName) {
// Hide all tab content
const tabContents = document.querySelectorAll('.tab-content');
tabContents.forEach(tab => tab.classList.remove('active'));
// Remove active state from all tab buttons
const tabButtons = document.querySelectorAll('.tab-button');
tabButtons.forEach(btn => btn.classList.remove('active'));
// Show corresponding tab content and set button active state
if (tabName === 'login') {
document.getElementById('loginTab').classList.add('active');
document.querySelector('.tab-button').classList.add('active');
} else if (tabName === 'register') {
document.getElementById('registerTab').classList.add('active');
document.querySelectorAll('.tab-button')[1].classList.add('active');
}
}
// Close message modal
function closeMessageModal() {
messageModal.style.display = "none";
}
// Show custom message modal
function showMessage(title, text, type = 'info') {
messageTitle.textContent = title;
messageText.textContent = text;
// Set style based on type
messageText.className = type === 'success' ? 'success' : (type === 'error' ? 'error' : '');
messageModal.style.display = "block";
}
// Bind message modal close events
closeMessage.onclick = closeMessageModal;
messageBtn.onclick = closeMessageModal;
// Close message modal
function closeMessageModal() {
messageModal.style.display = "none";
}
// Bind message modal close events
closeMessage.onclick = closeMessageModal;
messageBtn.onclick = closeMessageModal;
// Add login modal close button
function closeLoginModal() {
@@ -346,20 +411,20 @@ messageBtn.onclick = closeMessageModal;
}
});
// Check if token exists in local storage
function getLocalToken() {
return localStorage.getItem('ftyToken');
}
// Check if token exists in local storage
function getLocalToken() {
return localStorage.getItem('ftyToken');
}
// Save token to local storage
function saveToken(token) {
localStorage.setItem('ftyToken', token);
}
// Save token to local storage
function saveToken(token) {
localStorage.setItem('ftyToken', token);
}
// Clear token
function clearToken() {
localStorage.removeItem('ftyToken');
}
// Clear token
function clearToken() {
localStorage.removeItem('ftyToken');
}
// Validate if token is valid
async function validateToken() {
@@ -453,130 +518,243 @@ function clearToken() {
}
}
// Send verification code
sendCodeBtn.onclick = function() {
const contactValue = emailInput.value;
if (!validateEmail(contactValue)) {
showMessage('Input Error', 'Please enter a valid email address!', 'error');
return;
}
// Disable button and start countdown
startCountdown();
// Send AJAX request to get verification code
fetch(`${baseUrl}/fty/sendCode`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
type: "1", // Fixed as email type
username: contactValue
})
})
.then(response => response.json())
.then(data => {
if (data.success) {
showMessage('Send Success', 'Verification code has been sent to your email!', 'success');
} else {
showMessage('Send Failed', data.msg || 'Failed to send verification code, please try again later!', 'error');
resetCountdown();
// Send verification code
sendCodeBtn.onclick = function() {
const contactValue = document.getElementById('registerEmail').value;
if (!validateEmail(contactValue)) {
showMessage('Input Error', 'Please enter a valid email address!', 'error');
return;
}
})
.catch(error => {
console.error('Error:', error);
showMessage('Network Error', 'Failed to send verification code request, please try again later!', 'error');
resetCountdown();
});
}
// Disable button and start countdown
startCountdown();
// Send AJAX request to get verification code
fetch(`${baseUrl}/fty/sendCode`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
type: "1", // Fixed as email type
username: contactValue
})
})
.then(response => response.json())
.then(data => {
console.log("Verification code send response", data);
if (data.code==2000) {
showMessage('Send Success', 'Verification code has been sent to your email!', 'success');
} else {
showMessage('Send Failed', data.msg || 'Failed to send verification code, please try again later!', 'error');
resetCountdown();
}
})
.catch(error => {
console.error('Error:', error);
showMessage('Network Error', 'Failed to send verification code request, please try again later!', 'error');
resetCountdown();
});
}
// Validate email format
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());
}
// Validate email format
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());
}
// Start countdown
function startCountdown() {
let countdown = 60;
sendCodeBtn.disabled = true;
sendCodeBtn.textContent = `Retry after ${countdown}s`;
countdownTimer = setInterval(() => {
countdown--;
// Start countdown
function startCountdown() {
let countdown = 60;
sendCodeBtn.disabled = true;
sendCodeBtn.textContent = `Retry after ${countdown}s`;
if (countdown <= 0) {
resetCountdown();
countdownTimer = setInterval(() => {
countdown--;
sendCodeBtn.textContent = `Retry after ${countdown}s`;
if (countdown <= 0) {
resetCountdown();
}
}, 1000);
}
// Reset countdown
function resetCountdown() {
clearInterval(countdownTimer);
sendCodeBtn.disabled = false;
sendCodeBtn.textContent = 'Send Code';
}
// Handle login form submission
loginForm.onsubmit = function(e) {
console.log("Login form submitted");
e.preventDefault();
const email = document.getElementById("loginEmail").value;
const password = document.getElementById("loginPassword").value;
if (!validateEmail(email)) {
showMessage('Input Error', 'Please enter a valid email address!', 'error');
return;
}
}, 1000);
}
// Reset countdown
function resetCountdown() {
clearInterval(countdownTimer);
sendCodeBtn.disabled = false;
sendCodeBtn.textContent = 'Send Code';
}
// Handle login form submission
loginForm.onsubmit = function(e) {
console.log("Form submitted");
e.preventDefault();
const verificationCode = document.getElementById("verificationCode").value;
const contactValue = emailInput.value;
// Send AJAX request
fetch(`${baseUrl}/fty/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
type: "1", // Fixed as email type
username: contactValue,
code: verificationCode
if (!password) {
showMessage('Input Error', 'Please enter your password!', 'error');
return;
}
// Show loading state
const submitBtn = loginForm.querySelector('button[type="submit"]');
const originalText = submitBtn.textContent;
submitBtn.textContent = 'Logging in...';
submitBtn.disabled = true;
// Send AJAX request
fetch(`${baseUrl}/fty/userLogin`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: email,
type: 1,
password: password
})
})
})
.then(response => response.json())
.then(data => {
console.log("Login response", data);
if (data.code==2000) {
// Save token to local storage
if (data.data.token) {
saveToken(data.data.token);
}
showMessage('Login Success', 'Login successful!', 'success');
// Close modal after successful login
modal.style.display = "none";
resetCountdown();
// Check if there's a pending download link
const pendingDownloadUrl = sessionStorage.getItem('pendingDownloadUrl');
if (pendingDownloadUrl) {
sessionStorage.removeItem('pendingDownloadUrl');
.then(response => response.json())
.then(data => {
console.log("Login response", data);
if (data.code==2000) {
// Save token to local storage
if (data.data.token) {
saveToken(data.data.token);
}
// Delay a bit before redirect to let user see success message
setTimeout(() => {
if (downloadBtn) {
downloadBtn.innerHTML = 'Downloading...';
}
window.location.href = pendingDownloadUrl;
}, 1500);
showMessage('Login Success', 'Login successful!', 'success');
// Close modal after successful login
modal.style.display = "none";
// Check if there's a pending download link
const pendingDownloadUrl = sessionStorage.getItem('pendingDownloadUrl');
if (pendingDownloadUrl) {
sessionStorage.removeItem('pendingDownloadUrl');
// Delay a bit before redirect to let user see success message
setTimeout(() => {
const downloadBtn = document.getElementById('designDownloadBtn');
if (downloadBtn) {
downloadBtn.innerHTML = 'Downloading...';
}
window.location.href = pendingDownloadUrl;
}, 1500);
}
} else {
showMessage('Login Failed', data.msg || 'Login failed, please check your email and password!', 'error');
}
} else {
showMessage('Login Failed', data.msg || 'Login failed, please check email and verification code!', 'error');
})
.catch(error => {
console.error('Error:', error);
showMessage('Network Error', 'Login request failed, please try again later!', 'error');
})
.finally(() => {
// Restore button state
submitBtn.textContent = originalText;
submitBtn.disabled = false;
});
}
// Handle register form submission
registerForm.onsubmit = function(e) {
console.log("Register form submitted");
e.preventDefault();
const email = document.getElementById("registerEmail").value;
const verificationCode = document.getElementById("verificationCode").value;
const password = document.getElementById("registerPassword").value;
const confirmPassword = document.getElementById("confirmPassword").value;
if (!validateEmail(email)) {
showMessage('Input Error', 'Please enter a valid email address!', 'error');
return;
}
})
.catch(error => {
console.error('Error:', error);
showMessage('Network Error', 'Login request failed, please try again later!', 'error');
});
}
if (!verificationCode) {
showMessage('Input Error', 'Please enter verification code!', 'error');
return;
}
if (!password) {
showMessage('Input Error', 'Please enter your password!', 'error');
return;
}
if (password !== confirmPassword) {
showMessage('Input Error', 'The two passwords entered are inconsistent!', 'error');
return;
}
// Show loading state
const submitBtn = registerForm.querySelector('button[type="submit"]');
const originalText = submitBtn.textContent;
submitBtn.textContent = 'Registering...';
submitBtn.disabled = true;
// Send AJAX request
fetch(`${baseUrl}/fty/userRegister`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
type: 1, // Fixed as email type
username: email,
code: verificationCode,
password: password,
confirm_password: confirmPassword
})
})
.then(response => response.json())
.then(data => {
console.log("Register response", data);
if (data.code==2000) {
// Save token to local storage
if (data.data.token) {
saveToken(data.data.token);
}
showMessage('Register Success', 'Registration successful!', 'success');
// Close modal after successful registration
modal.style.display = "none";
resetCountdown();
// Check if there's a pending download link
const pendingDownloadUrl = sessionStorage.getItem('pendingDownloadUrl');
if (pendingDownloadUrl) {
sessionStorage.removeItem('pendingDownloadUrl');
// Delay a bit before redirect to let user see success message
setTimeout(() => {
const downloadBtn = document.getElementById('designDownloadBtn');
if (downloadBtn) {
downloadBtn.innerHTML = 'Downloading...';
}
window.location.href = pendingDownloadUrl;
}, 1500);
}
} else {
showMessage('Register Failed', data.msg || 'Registration failed, please check your input!', 'error');
}
})
.catch(error => {
console.error('Error:', error);
showMessage('Network Error', 'Registration request failed, please try again later!', 'error');
})
.finally(() => {
// Restore button state
submitBtn.textContent = originalText;
submitBtn.disabled = false;
});
}
// ESC key to close login modal
document.addEventListener('keydown', function(event) {

548
en/docs/login/index.md Normal file
View File

@@ -0,0 +1,548 @@
---
title: Login & Register
---
# Login & Register
<style>
/* Page version login/register styles */
.login-page-container {
max-width: 500px;
margin: 2rem auto;
padding: 30px;
background-color: #fefefe;
border: 1px solid #ddd;
border-radius: 15px;
box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}
.login-page-container h2 {
text-align: center;
margin-bottom: 25px;
color: #333;
font-size: 24px;
}
/* Tab styles */
.tab-container {
display: flex;
margin-bottom: 25px;
border-bottom: 1px solid #ddd;
}
.tab-button {
flex: 1;
padding: 15px;
background: none;
border: none;
cursor: pointer;
font-size: 16px;
transition: all 0.3s ease;
border-bottom: 2px solid transparent;
}
.tab-button.active {
color: #3498db;
border-bottom-color: #3498db;
font-weight: bold;
}
.tab-button:hover {
color: #3498db;
background-color: #f8f9fa;
}
.tab-content {
display: none;
}
.tab-content.active {
display: block;
}
.login-form input {
width: 100%;
padding: 12px;
margin: 12px 0;
border: 1px solid #ddd;
border-radius: 8px;
box-sizing: border-box;
font-size: 15px;
}
.login-form .code-container {
display: flex;
gap: 10px;
margin: 12px 0;
}
.login-form .hint-text {
font-size: 12px;
color: #666;
margin-top: 3px;
margin-bottom: 8px;
text-align: left;
}
.login-form .code-input {
flex: 3;
padding: 12px;
border: 1px solid #ddd;
border-radius: 8px;
box-sizing: border-box;
font-size: 15px;
}
.login-form .send-code-btn {
flex: 1;
min-width: 100px;
padding: 12px 10px;
height: 47px;
background-color: #3498db;
color: white;
border: none;
border-radius: 8px;
cursor: pointer;
font-size: 14px;
transition: background-color 0.3s ease;
white-space: nowrap;
box-sizing: border-box;
display: flex;
align-items: center;
justify-content: center;
}
.login-form .send-code-btn:hover {
background-color: #2980b9;
}
.login-form .send-code-btn:disabled {
background-color: #95a5a6;
cursor: not-allowed;
}
.login-form button[type="submit"] {
width: 100%;
padding: 12px;
background-color: #3498db;
color: white;
border: none;
border-radius: 8px;
cursor: pointer;
margin-top: 15px;
font-size: 16px;
transition: background-color 0.3s ease;
}
.login-form button[type="submit"]:hover {
background-color: #2980b9;
}
/* Message prompt styles */
.message-box {
display: none;
padding: 15px;
margin: 15px 0;
border-radius: 8px;
text-align: center;
}
.message-box.success {
background-color: #d4edda;
color: #155724;
border: 1px solid #c3e6cb;
}
.message-box.error {
background-color: #f8d7da;
color: #721c24;
border: 1px solid #f5c6cb;
}
.message-box.info {
background-color: #d1ecf1;
color: #0c5460;
border: 1px solid #bee5eb;
}
</style>
<div class="login-page-container">
<h2>Phaten Cloud Login/Register</h2>
<!-- Message prompt box -->
<div id="messageBox" class="message-box">
<span id="messageText"></span>
</div>
<!-- Tab toggle buttons -->
<div class="tab-container">
<button class="tab-button active" onclick="switchTab('login')">Login</button>
<button class="tab-button" onclick="switchTab('register')">Register</button>
</div>
<!-- Login form -->
<div id="loginTab" class="tab-content active">
<form id="loginForm" class="login-form">
<input type="email" id="loginEmail" placeholder="Enter your email" required>
<input type="password" id="loginPassword" placeholder="Enter your password" required>
<button type="submit">Login</button>
</form>
</div>
<!-- Register form -->
<div id="registerTab" class="tab-content">
<form id="registerForm" class="login-form">
<input type="email" id="registerEmail" placeholder="Enter your email" required>
<div class="code-container">
<input type="text" id="verificationCode" class="code-input" placeholder="Enter verification code" required>
<button type="button" id="sendCodeBtn" class="send-code-btn">Send Code</button>
</div>
<input type="password" id="registerPassword" placeholder="Enter your password" required>
<input type="password" id="confirmPassword" placeholder="Confirm your password" required>
<button type="submit">Register</button>
</form>
</div>
</div>
<script>
// Page version login/register functionality
(function() {
'use strict';
// Define API base URL
const baseUrl = 'https://api.phaten-audio.com/api';
//const baseUrl = 'http://localhost:8010/api';
// Get form elements
const loginForm = document.getElementById("loginForm");
const registerForm = document.getElementById("registerForm");
const sendCodeBtn = document.getElementById("sendCodeBtn");
const messageBox = document.getElementById("messageBox");
const messageText = document.getElementById("messageText");
let countdownTimer;
// Tab switching functionality
window.switchTab = function(tabName) {
// Hide all tab content
const tabContents = document.querySelectorAll('.tab-content');
tabContents.forEach(tab => tab.classList.remove('active'));
// Remove active state from all tab buttons
const tabButtons = document.querySelectorAll('.tab-button');
tabButtons.forEach(btn => btn.classList.remove('active'));
// Show corresponding tab content and set button active state
if (tabName === 'login') {
document.getElementById('loginTab').classList.add('active');
document.querySelector('.tab-button').classList.add('active');
} else if (tabName === 'register') {
document.getElementById('registerTab').classList.add('active');
document.querySelectorAll('.tab-button')[1].classList.add('active');
}
// Hide message box
hideMessage();
}
// Show message
function showMessage(text, type = 'info') {
messageText.textContent = text;
messageBox.className = `message-box ${type}`;
messageBox.style.display = 'block';
// Auto hide success and info messages after 3 seconds
if (type === 'success' || type === 'info') {
setTimeout(() => {
hideMessage();
}, 3000);
}
}
// Hide message
function hideMessage() {
messageBox.style.display = 'none';
}
// Check if token exists in local storage
function getLocalToken() {
return localStorage.getItem('ftyToken');
}
// Save token to local storage
function saveToken(token) {
localStorage.setItem('ftyToken', token);
}
// Clear token
function clearToken() {
localStorage.removeItem('ftyToken');
}
// Validate if token is valid
async function validateToken() {
const token = getLocalToken();
console.log("validateToken function called, token:", token);
if (!token) {
console.log("No token, return false");
return false;
}
try {
console.log("Sending token validation request...");
const response = await fetch(`${baseUrl}/fty/validateToken`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
}
});
const data = await response.json();
console.log("Token validation server response:", data);
const isValid = data.data && data.data.valid === true;
console.log("Is token valid:", isValid);
// If token is invalid, clear local storage
if (!isValid) {
console.log("Token invalid, clear local storage");
clearToken();
}
return isValid;
} catch (error) {
console.error('Token validation error:', error);
console.log("Token validation error, clear local storage");
clearToken();
return false;
}
}
// Send verification code
sendCodeBtn.onclick = function() {
const contactValue = document.getElementById('registerEmail').value;
if (!validateEmail(contactValue)) {
showMessage('Please enter a valid email address!', 'error');
return;
}
// Disable button and start countdown
startCountdown();
// Send AJAX request to get verification code
fetch(`${baseUrl}/fty/sendCode`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
type: "1", // Fixed as email type
username: contactValue
})
})
.then(response => response.json())
.then(data => {
console.log("Verification code send response", data);
if (data.code==2000) {
showMessage('Verification code has been sent to your email!', 'success');
} else {
showMessage(data.msg || 'Failed to send verification code, please try again later!', 'error');
resetCountdown();
}
})
.catch(error => {
console.error('Error:', error);
showMessage('Failed to send verification code request, please try again later!', 'error');
resetCountdown();
});
}
// Validate email format
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());
}
// Start countdown
function startCountdown() {
let countdown = 60;
sendCodeBtn.disabled = true;
sendCodeBtn.textContent = `Retry after ${countdown}s`;
countdownTimer = setInterval(() => {
countdown--;
sendCodeBtn.textContent = `Retry after ${countdown}s`;
if (countdown <= 0) {
resetCountdown();
}
}, 1000);
}
// Reset countdown
function resetCountdown() {
clearInterval(countdownTimer);
sendCodeBtn.disabled = false;
sendCodeBtn.textContent = 'Send Code';
}
// Handle login form submission
loginForm.onsubmit = function(e) {
console.log("Login form submitted");
e.preventDefault();
const email = document.getElementById("loginEmail").value;
const password = document.getElementById("loginPassword").value;
if (!validateEmail(email)) {
showMessage('Please enter a valid email address!', 'error');
return;
}
if (!password) {
showMessage('Please enter your password!', 'error');
return;
}
// Show loading state
const submitBtn = loginForm.querySelector('button[type="submit"]');
const originalText = submitBtn.textContent;
submitBtn.textContent = 'Logging in...';
submitBtn.disabled = true;
// Send AJAX request
fetch(`${baseUrl}/fty/userLogin`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: email,
type: 1,
password: password
})
})
.then(response => response.json())
.then(data => {
console.log("Login response", data);
if (data.code==2000) {
// Save token to local storage
if (data.data.token) {
saveToken(data.data.token);
}
showMessage('Login successful! Redirecting...', 'success');
// Delay redirect to homepage
setTimeout(() => {
window.location.href = '/';
}, 1500);
} else {
showMessage(data.msg || 'Login failed, please check your email and password!', 'error');
}
})
.catch(error => {
console.error('Error:', error);
showMessage('Login request failed, please try again later!', 'error');
})
.finally(() => {
// Restore button state
submitBtn.textContent = originalText;
submitBtn.disabled = false;
});
}
// Handle register form submission
registerForm.onsubmit = function(e) {
console.log("Register form submitted");
e.preventDefault();
const email = document.getElementById("registerEmail").value;
const verificationCode = document.getElementById("verificationCode").value;
const password = document.getElementById("registerPassword").value;
const confirmPassword = document.getElementById("confirmPassword").value;
if (!validateEmail(email)) {
showMessage('Please enter a valid email address!', 'error');
return;
}
if (!verificationCode) {
showMessage('Please enter verification code!', 'error');
return;
}
if (!password) {
showMessage('Please enter your password!', 'error');
return;
}
if (password !== confirmPassword) {
showMessage('The two passwords entered are inconsistent!', 'error');
return;
}
// Show loading state
const submitBtn = registerForm.querySelector('button[type="submit"]');
const originalText = submitBtn.textContent;
submitBtn.textContent = 'Registering...';
submitBtn.disabled = true;
// Send AJAX request
fetch(`${baseUrl}/fty/userRegister`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
type: 1, // Fixed as email type
username: email,
code: verificationCode,
password: password,
confirm_password: confirmPassword
})
})
.then(response => response.json())
.then(data => {
console.log("Register response", data);
if (data.code==2000) {
// Save token to local storage
if (data.data.token) {
saveToken(data.data.token);
}
showMessage('Registration successful! Redirecting...', 'success');
resetCountdown();
// Delay redirect to homepage
setTimeout(() => {
window.location.href = '/';
}, 1500);
} else {
showMessage(data.msg || 'Registration failed, please check your input!', 'error');
}
})
.catch(error => {
console.error('Error:', error);
showMessage('Registration request failed, please try again later!', 'error');
})
.finally(() => {
// Restore button state
submitBtn.textContent = originalText;
submitBtn.disabled = false;
});
}
// Check login status when page loads
document.addEventListener('DOMContentLoaded', async function() {
// const isLoggedIn = await validateToken();
// if (isLoggedIn) {
// showMessage('You are already logged in, redirecting to homepage...', 'info');
// setTimeout(() => {
// window.location.href = '/';
// }, 2000);
// }
});
})(); // End of immediately invoked function
</script>