From f4c68ecbc2879b18797fe4709bad713fbfc140a2 Mon Sep 17 00:00:00 2001 From: slawk0 Date: Tue, 19 Nov 2024 14:06:40 +0100 Subject: [PATCH] code refactor and improvements --- client/src/api/contactsApi.tsx | 5 +-- client/src/components/chat/MessagesArea.tsx | 5 +-- client/src/socket/socket.tsx | 2 + server/auth/jwt.js | 9 +++-- server/server.js | 42 +++++++++++++-------- server/utils/authorize.js | 4 +- server/utils/filter.js | 18 ++++++++- 7 files changed, 55 insertions(+), 30 deletions(-) diff --git a/client/src/api/contactsApi.tsx b/client/src/api/contactsApi.tsx index 046d994..9a55957 100644 --- a/client/src/api/contactsApi.tsx +++ b/client/src/api/contactsApi.tsx @@ -13,9 +13,8 @@ type MessagesProps = { }; export async function getContactsList(): Promise { try { - console.log('getcontactslisklsdfjklfsdjklsdfjklsdfjklsdfjklsdfjkl'); const response = await axiosClient.get(`/api/chat/contacts`); - console.log(response.data); + console.log('Get contacts list response: ', response.data); return response.data; } catch (e) { console.error('Failed to fetch /api/chat/contacts: ', e); @@ -60,7 +59,7 @@ export async function getMessages( const response = await axiosClient.get( `/api/chat/messages/${contact}?limit=${limit}&cursor=${cursor}`, ); - console.log(response.data); + console.log('Get messages response: ', response.data); return response.data; } catch (e) { console.error('Failed to get messages: ', e); diff --git a/client/src/components/chat/MessagesArea.tsx b/client/src/components/chat/MessagesArea.tsx index b3f7d20..1eb9250 100644 --- a/client/src/components/chat/MessagesArea.tsx +++ b/client/src/components/chat/MessagesArea.tsx @@ -66,10 +66,7 @@ function MessagesArea({ }; useEffect(() => { - if (!socket) { - console.log('Socket not initialized'); - return; - } + if (!socket) return; const currentContainer = containerRef.current; if (currentContainer) { diff --git a/client/src/socket/socket.tsx b/client/src/socket/socket.tsx index 2d22aea..bf2e7a4 100644 --- a/client/src/socket/socket.tsx +++ b/client/src/socket/socket.tsx @@ -15,6 +15,8 @@ function initializeSocket(token: string): Socket | null { socket.on('disconnect', () => { console.log('Disconnected from server'); }); + } else if (!socket) { + console.error('Socket not initialized'); } return socket; } diff --git a/server/auth/jwt.js b/server/auth/jwt.js index b2e0dcb..df531e2 100644 --- a/server/auth/jwt.js +++ b/server/auth/jwt.js @@ -1,6 +1,5 @@ const jwt = require("jsonwebtoken"); const jwtSecret = process.env.JWT_SECRET; -const { isValidUsername } = require("../utils/filter"); function generateJwtToken(username, user_id) { try { @@ -18,17 +17,19 @@ function verifyJwtToken(token) { try { const decoded = jwt.verify(token, jwtSecret, { algorithms: ["HS256"] }); if (!decoded?.user_id) { - throw new Error("Token verification failed - missing user_id"); + console.error("Token verification failed - missing user_id"); + return { message: "Invalid token" }; } if (!decoded?.username) { - throw new Error("Token verification failed - missing username"); + console.error("Token verification failed - missing username"); + return { message: "Invalid token" }; } return { username: decoded.username, user_id: decoded.user_id }; } catch (e) { console.error(e.message); - throw e; + return { message: "Authorization failed" }; } } diff --git a/server/server.js b/server/server.js index 750c3e6..6bb55f8 100644 --- a/server/server.js +++ b/server/server.js @@ -24,7 +24,13 @@ const { getMessages, } = require("./db/db.js"); const authorizeUser = require("./utils/authorize"); -const { isValidUsername } = require("./utils/filter"); +const { + isValidUsername, + MIN_USERNAME_LENGTH, + MAX_USERNAME_LENGTH, + MAX_PASSWORD_LENGTH, + MIN_PASSWORD_LENGTH, +} = require("./utils/filter"); const { generateJwtToken, verifyJwtToken } = require("./auth/jwt"); const { initializeSocket } = require("./socket/socket"); const { getContacts, insertContact } = require("./db/db"); @@ -52,16 +58,12 @@ app.post("/api/auth/signup", async (req, res) => { return res.status(400).json({ message: "No password provided" }); } - if (typeof password && typeof username !== "string") { - return res.status(400).json({ message: "Internal server error" }); - } - // Check for invalid characters in password const validChars = /^[A-Za-z0-9!@#$%^&*(),.?":{}|<>]+$/; if (!validChars.test(password)) { return res .status(400) - .json({ message: "Username contains invalid character" }); + .json({ message: "Password contains invalid character" }); } // Validate username for invalid characters, length, and type @@ -70,7 +72,11 @@ app.post("/api/auth/signup", async (req, res) => { } // Validate form data length - if (!password || password.length < 8 || password.length > 128) { + if ( + !password || + password.length < MIN_PASSWORD_LENGTH || + password.length > MAX_PASSWORD_LENGTH + ) { return res.status(400).json({ message: "Invalid password length" }); } @@ -93,6 +99,8 @@ app.post("/api/auth/signup", async (req, res) => { const token = generateJwtToken(username, user_id); res.cookie("token", token, { maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days + httpOnly: true, + secure: true, }); return res.status(200).json({ message: "Successfully signed up" }); @@ -114,10 +122,10 @@ app.post("/api/auth/login", async (req, res) => { if ( !username || !password || - username.length < 4 || - username.length > 20 || - password.length < 8 || - password.length > 128 + username.length < MIN_USERNAME_LENGTH || + username.length > MAX_USERNAME_LENGTH || + password.length < MIN_PASSWORD_LENGTH || + password.length > MAX_PASSWORD_LENGTH ) { return res.status(400).json({ message: "Invalid credentials" }); } @@ -143,7 +151,8 @@ app.post("/api/auth/login", async (req, res) => { }); return res.status(200).json({ message: "Successfully logged In" }); }) - .catch((err) => { + .catch((e) => { + console.error("Failed to compare password: ", e); return res.status(500).json({ message: "Internal server error" }); }); } catch (e) { @@ -226,8 +235,8 @@ app.get("/api/chat/messages/:contact", authorizeUser, async (req, res) => { if (!req.params.contact) { return res.status(400).json({ message: "Missing contact parameter" }); } - const limit = parseInt(req.query.limit); - const cursor = parseInt(req.query.cursor); + const limit = parseInt(req.query.limit) || 50; + const cursor = parseInt(req.query.cursor) || 0; const messages = await getMessages( req.user.username, @@ -239,11 +248,14 @@ app.get("/api/chat/messages/:contact", authorizeUser, async (req, res) => { return res.status(404).json({ message: "No more messages found" }); } - console.log("MESSAGESLENGTH: ", messages.length, limit); console.log("Sent messages for: ", req.user.username, "messages: ", messages); return res.status(200).json({ messages }); }); +app.post("/api/chat/sendmessage", authorizeUser, async (req, res) => { + return res.status(500).json({ message: "HUJ!" }); +}); + initializeSocket(io); server.listen(PORT, () => { diff --git a/server/utils/authorize.js b/server/utils/authorize.js index 9bd6655..51f189c 100644 --- a/server/utils/authorize.js +++ b/server/utils/authorize.js @@ -9,8 +9,8 @@ function authorizeUser(req, res, next) { } const decoded = verifyJwtToken(token); - if (!decoded.user_id || !decoded.username) { - return res.status(401).json({ message: "Invalid token" }); + if (decoded.message) { + return res.status(401).json({ message: decoded.message }); } if (!isValidUsername(decoded.username)) { diff --git a/server/utils/filter.js b/server/utils/filter.js index 964d6e3..2f906d9 100644 --- a/server/utils/filter.js +++ b/server/utils/filter.js @@ -1,9 +1,17 @@ +const MIN_USERNAME_LENGTH = 4; +const MAX_USERNAME_LENGTH = 20; +const MIN_PASSWORD_LENGTH = 8; +const MAX_PASSWORD_LENGTH = 128; + function isValidUsername(username) { if (typeof username !== "string") { return null; } - if (username.length < 4 || username.length > 20) { + if ( + username.length < MIN_USERNAME_LENGTH || + username.length > MAX_USERNAME_LENGTH + ) { return null; } @@ -11,4 +19,10 @@ function isValidUsername(username) { return validChars.test(username); } -module.exports = { isValidUsername }; +module.exports = { + isValidUsername, + MAX_PASSWORD_LENGTH, + MIN_PASSWORD_LENGTH, + MAX_USERNAME_LENGTH, + MIN_USERNAME_LENGTH, +};