code refactor to use json for communicating with frontend

This commit is contained in:
slawk0
2024-09-08 00:21:23 +02:00
parent 5a6e40a3a4
commit 6d609896e1
8 changed files with 76 additions and 32 deletions

View File

@@ -17,3 +17,25 @@ document.querySelector('form').addEventListener('submit', () => {
const username = document.getElementById('username').value; const username = document.getElementById('username').value;
localStorage.setItem('username', username); localStorage.setItem('username', username);
}) })
document.getElementById('loginForm').addEventListener('submit', async (e) => {
e.preventDefault()
const username = document.getElementById('username').value.trim();
const password = document.getElementById('password').value.trim();
const messageBox = document.getElementById('messageBox');
const jsonData = JSON.stringify({ username, password })
const response = await fetch ('/auth/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: jsonData
});
const result = await response.json();
if(response.ok) {
location.href='/chat';
} else {
messageBox.innerText = result.message;
}
})

View File

@@ -1,5 +1,4 @@
const logoutButton = document.getElementById('logout'); const logoutButton = document.getElementById('logout');
const messageBox = document.getElementById('messageBox');
logoutButton.onclick = logout; logoutButton.onclick = logout;
function logout() { function logout() {
@@ -28,7 +27,7 @@ document.getElementById('changePasswordForm').addEventListener('submit', async (
e.preventDefault(); e.preventDefault();
const cPassword = document.getElementById('cPassword').value.trim(); const cPassword = document.getElementById('cPassword').value.trim();
const nPassword = document.getElementById('nPassword').value.trim(); const nPassword = document.getElementById('nPassword').value.trim();
const messageBox = document.getElementById('messageBox');
const jsonData = JSON.stringify({ cPassword, nPassword }); const jsonData = JSON.stringify({ cPassword, nPassword });
const response = await fetch('/auth/changepassword', { const response = await fetch('/auth/changepassword', {
method: 'POST', method: 'POST',
@@ -38,6 +37,6 @@ document.getElementById('changePasswordForm').addEventListener('submit', async (
body: jsonData body: jsonData
}); });
const result = await response.json(); const result = await response.json();
// display result message (successful or no) // Display result message
messageBox.innerText = result.message; messageBox.innerText = result.message;
}) })

View File

@@ -16,13 +16,29 @@ function showPasswd() {
document.getElementById('signupForm').addEventListener('submit',async function (event) { document.getElementById('signupForm').addEventListener('submit',async function (event) {
event.preventDefault(); event.preventDefault();
const messageBox = document.getElementById('messageBox');
const username = document.getElementById('username').value.trim();
const password = document.getElementById("password").value.trim();
const sPassword = document.getElementById("sPassword").value.trim();
const jsonData = JSON.stringify({ username, password });
const password = document.getElementById("password").value;
const sPassword = document.getElementById("sPassword").value;
console.log(password, sPassword);
if(password !== sPassword){ if(password !== sPassword){
alert("Passwords don't match!"); messageBox.innerText = "Passwords don't match!"
return;
}
const response = await fetch ('/auth/signup', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: jsonData
});
const result = await response.json();
if(response.ok) {
location.href='/chat';
} else { } else {
this.submit(); messageBox.innerText = result.message;
} }
}) })

View File

@@ -13,7 +13,7 @@
<div class="login"> <div class="login">
<h1>Login</h1> <h1>Login</h1>
<form action="/auth/login" method="post"> <form id="loginForm">
<label for="username"></label> <label for="username"></label>
<input type="text" name="username" placeholder="Username" id="username" required> <input type="text" name="username" placeholder="Username" id="username" required>
@@ -24,8 +24,10 @@
<input type="checkbox" onclick="showPasswd()">Show Password <input type="checkbox" onclick="showPasswd()">Show Password
<button type="submit">Login</button> <button type="submit">Login</button>
</form> </form>
</div> </div>
<a href="/signup">Sign up</a> <a href="/signup">Sign up</a>
<p id="messageBox"></p>
</body> </body>
</html> </html>

View File

@@ -13,7 +13,7 @@
<div class="signup"> <div class="signup">
<h1>Sign up</h1> <h1>Sign up</h1>
<form action="/auth/signup" method="post" id="signupForm"> <form id="signupForm">
<label for="username"></label> <label for="username"></label>
<input type="text" name="username" placeholder="Username" id="username" required> <input type="text" name="username" placeholder="Username" id="username" required>
@@ -27,7 +27,7 @@
<input type="checkbox" id="checkbox" onclick="showPasswd()">Show Passwords <input type="checkbox" id="checkbox" onclick="showPasswd()">Show Passwords
<button type="submit">Sign up</button> <button type="submit">Sign up</button>
<p id="messageBox"></p>
</form> </form>
</div> </div>
</body> </body>

View File

@@ -16,3 +16,6 @@ button {
margin: 0 10px; /* Add margin to separate buttons */ margin: 0 10px; /* Add margin to separate buttons */
} }
p {
color: red;
}

View File

@@ -16,3 +16,7 @@ button {
margin: 0 10px; /* Add margin to separate buttons */ margin: 0 10px; /* Add margin to separate buttons */
} }
p {
color: red;
}

View File

@@ -54,7 +54,7 @@ app.post('/auth/logout', (req, res) => {
res.clearCookie('io', { res.clearCookie('io', {
path: '/' path: '/'
}); });
res.status(200).json({ message: 'Successfully logged out'}); res.status(200).json({ message: 'Successfully logged out', success: true});
}); });
// get JWT token API // get JWT token API
@@ -80,7 +80,7 @@ app.post('/auth/changepassword', async (req, res) => {
const decoded = jwt.verify(token, jwtSecret); const decoded = jwt.verify(token, jwtSecret);
username = username = decoded.username; username = username = decoded.username;
} catch (err) { } catch (err) {
return res.status(400).json({ message: 'Unauthorized'}); return res.status(403).json({ message: 'Unauthorized'});
} }
try { try {
const result = await db.query('SELECT * FROM accounts WHERE username = $1', [username]); const result = await db.query('SELECT * FROM accounts WHERE username = $1', [username]);
@@ -153,11 +153,20 @@ app.get('/settings', (req, res) => {
res.sendFile(path.join(__dirname, '/frontend/routes/settings.html')) res.sendFile(path.join(__dirname, '/frontend/routes/settings.html'))
}); });
}) })
// serving the chat page if logged in
app.get('/', (req, res) => { app.get('/', (req, res) => {
const token = req.cookies.token; const token = req.cookies.token;
if(!token) {
return res.redirect('/login');
} else {
return res.redirect('/chat');
}
})
// serving the chat page if logged in
app.get('/chat', (req, res) => {
const token = req.cookies.token;
if(!token) { if(!token) {
res.redirect('/login'); res.redirect('/login');
return; return;
@@ -184,14 +193,11 @@ async function signupUser(req, res) {
if(username && password){ if(username && password){
try { try {
// trimming here to avoid app crash when username or password is undefined
username = username.trim();
password = password.trim();
// Check if user exists // Check if user exists
const exists = await isUserExists(username); const exists = await isUserExists(username);
if (exists) { if (exists) {
console.log('User already exists'); console.log('User already exists');
return res.status(500).send('User already exists!'); return res.status(500).json({ message: 'User already exists!' });
} }
// Hash password // Hash password
@@ -200,13 +206,13 @@ async function signupUser(req, res) {
// Insert user // Insert user
await insertUser(username, hash); await insertUser(username, hash);
return res.status(200).send("Account successfully created <a href=/login>Login screen</a>"); return res.status(200).json({ message: "Account successfully created" });
} catch (err) { } catch (err) {
console.error('Error inserting data:', err); console.error('Error inserting data:', err);
return res.status(500).send('Error inserting data'); return res.status(500).json({ message: 'Error inserting data' });
} }
} else { } else {
res.send('Please enter Username and Password!') res.status(400).json({ message: 'Form is empty'})
} }
} }
@@ -227,7 +233,7 @@ async function loginUser(req, res) {
// Compare password // Compare password
const match = await bcrypt.compare(password, result.rows[0].password); const match = await bcrypt.compare(password, result.rows[0].password);
if (!match) { if (!match) {
res.send('Incorrect Username or Password!'); res.status(401).json({ message: 'Invalid password'});
return; return;
} }
const token = jwt.sign({ username }, jwtSecret, { const token = jwt.sign({ username }, jwtSecret, {
@@ -239,15 +245,7 @@ async function loginUser(req, res) {
}); });
req.session.loggedin = true; req.session.loggedin = true;
req.session.username = username; req.session.username = username;
res.send(` res.status(200).json({ message: 'Successfully logged in', success: true });
<p>Login successful!</p>
<p>Redirecting to chat...</p>
<script>
setTimeout(() => {
window.location.href = '/';
}, 1500);
</script>
`);
} else { } else {
res.send('Incorrect Username or Password!'); res.send('Incorrect Username or Password!');
} }