From 6d609896e1fd96b887f3c0b40ddb6aac28e150e7 Mon Sep 17 00:00:00 2001 From: slawk0 Date: Sun, 8 Sep 2024 00:21:23 +0200 Subject: [PATCH] code refactor to use json for communicating with frontend --- frontend/js/login.js | 22 +++++++++++++++++++ frontend/js/settings.js | 5 ++--- frontend/js/signup.js | 26 +++++++++++++++++----- frontend/routes/login.html | 4 +++- frontend/routes/signup.html | 4 ++-- frontend/stylesheet/login.css | 3 +++ frontend/stylesheet/signup.css | 4 ++++ index.js | 40 ++++++++++++++++------------------ 8 files changed, 76 insertions(+), 32 deletions(-) diff --git a/frontend/js/login.js b/frontend/js/login.js index 837fb2b..42b6c58 100644 --- a/frontend/js/login.js +++ b/frontend/js/login.js @@ -17,3 +17,25 @@ document.querySelector('form').addEventListener('submit', () => { const username = document.getElementById('username').value; 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; + } +}) \ No newline at end of file diff --git a/frontend/js/settings.js b/frontend/js/settings.js index 7b26e28..ffb81cc 100644 --- a/frontend/js/settings.js +++ b/frontend/js/settings.js @@ -1,5 +1,4 @@ const logoutButton = document.getElementById('logout'); -const messageBox = document.getElementById('messageBox'); logoutButton.onclick = logout; function logout() { @@ -28,7 +27,7 @@ document.getElementById('changePasswordForm').addEventListener('submit', async ( e.preventDefault(); const cPassword = document.getElementById('cPassword').value.trim(); const nPassword = document.getElementById('nPassword').value.trim(); - + const messageBox = document.getElementById('messageBox'); const jsonData = JSON.stringify({ cPassword, nPassword }); const response = await fetch('/auth/changepassword', { method: 'POST', @@ -38,6 +37,6 @@ document.getElementById('changePasswordForm').addEventListener('submit', async ( body: jsonData }); const result = await response.json(); - // display result message (successful or no) + // Display result message messageBox.innerText = result.message; }) \ No newline at end of file diff --git a/frontend/js/signup.js b/frontend/js/signup.js index 50f0b80..3b3d4ce 100644 --- a/frontend/js/signup.js +++ b/frontend/js/signup.js @@ -16,13 +16,29 @@ function showPasswd() { document.getElementById('signupForm').addEventListener('submit',async function (event) { 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){ - 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 { - this.submit(); + messageBox.innerText = result.message; } }) diff --git a/frontend/routes/login.html b/frontend/routes/login.html index df14f2b..32e8393 100644 --- a/frontend/routes/login.html +++ b/frontend/routes/login.html @@ -13,7 +13,7 @@

Login

-
+ @@ -24,8 +24,10 @@ Show Password +
Sign up +

\ No newline at end of file diff --git a/frontend/routes/signup.html b/frontend/routes/signup.html index 2d31993..72f25cf 100644 --- a/frontend/routes/signup.html +++ b/frontend/routes/signup.html @@ -13,7 +13,7 @@

Sign up

-
+ @@ -27,7 +27,7 @@ Show Passwords - +

diff --git a/frontend/stylesheet/login.css b/frontend/stylesheet/login.css index ddfe20b..a73f558 100644 --- a/frontend/stylesheet/login.css +++ b/frontend/stylesheet/login.css @@ -16,3 +16,6 @@ button { margin: 0 10px; /* Add margin to separate buttons */ } +p { + color: red; +} diff --git a/frontend/stylesheet/signup.css b/frontend/stylesheet/signup.css index ddfe20b..25a3b59 100644 --- a/frontend/stylesheet/signup.css +++ b/frontend/stylesheet/signup.css @@ -16,3 +16,7 @@ button { margin: 0 10px; /* Add margin to separate buttons */ } + +p { + color: red; +} \ No newline at end of file diff --git a/index.js b/index.js index 67c7fb4..270a807 100644 --- a/index.js +++ b/index.js @@ -54,7 +54,7 @@ app.post('/auth/logout', (req, res) => { res.clearCookie('io', { path: '/' }); - res.status(200).json({ message: 'Successfully logged out'}); + res.status(200).json({ message: 'Successfully logged out', success: true}); }); // get JWT token API @@ -80,7 +80,7 @@ app.post('/auth/changepassword', async (req, res) => { const decoded = jwt.verify(token, jwtSecret); username = username = decoded.username; } catch (err) { - return res.status(400).json({ message: 'Unauthorized'}); + return res.status(403).json({ message: 'Unauthorized'}); } try { 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')) }); }) - -// serving the chat page if logged in app.get('/', (req, res) => { 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) { res.redirect('/login'); return; @@ -184,14 +193,11 @@ async function signupUser(req, res) { if(username && password){ try { - // trimming here to avoid app crash when username or password is undefined - username = username.trim(); - password = password.trim(); // Check if user exists const exists = await isUserExists(username); if (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 @@ -200,13 +206,13 @@ async function signupUser(req, res) { // Insert user await insertUser(username, hash); - return res.status(200).send("Account successfully created Login screen"); + return res.status(200).json({ message: "Account successfully created" }); } catch (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 { - 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 const match = await bcrypt.compare(password, result.rows[0].password); if (!match) { - res.send('Incorrect Username or Password!'); + res.status(401).json({ message: 'Invalid password'}); return; } const token = jwt.sign({ username }, jwtSecret, { @@ -239,15 +245,7 @@ async function loginUser(req, res) { }); req.session.loggedin = true; req.session.username = username; - res.send(` -

Login successful!

-

Redirecting to chat...

- - `); + res.status(200).json({ message: 'Successfully logged in', success: true }); } else { res.send('Incorrect Username or Password!'); }