code refactor and improvements

This commit is contained in:
slawk0
2024-11-19 14:06:40 +01:00
parent 1b4ef5e34d
commit f4c68ecbc2
7 changed files with 55 additions and 30 deletions

View File

@@ -13,9 +13,8 @@ type MessagesProps = {
}; };
export async function getContactsList(): Promise<ContactsProps[]> { export async function getContactsList(): Promise<ContactsProps[]> {
try { try {
console.log('getcontactslisklsdfjklfsdjklsdfjklsdfjklsdfjklsdfjkl');
const response = await axiosClient.get(`/api/chat/contacts`); const response = await axiosClient.get(`/api/chat/contacts`);
console.log(response.data); console.log('Get contacts list response: ', response.data);
return response.data; return response.data;
} catch (e) { } catch (e) {
console.error('Failed to fetch /api/chat/contacts: ', e); console.error('Failed to fetch /api/chat/contacts: ', e);
@@ -60,7 +59,7 @@ export async function getMessages(
const response = await axiosClient.get( const response = await axiosClient.get(
`/api/chat/messages/${contact}?limit=${limit}&cursor=${cursor}`, `/api/chat/messages/${contact}?limit=${limit}&cursor=${cursor}`,
); );
console.log(response.data); console.log('Get messages response: ', response.data);
return response.data; return response.data;
} catch (e) { } catch (e) {
console.error('Failed to get messages: ', e); console.error('Failed to get messages: ', e);

View File

@@ -66,10 +66,7 @@ function MessagesArea({
}; };
useEffect(() => { useEffect(() => {
if (!socket) { if (!socket) return;
console.log('Socket not initialized');
return;
}
const currentContainer = containerRef.current; const currentContainer = containerRef.current;
if (currentContainer) { if (currentContainer) {

View File

@@ -15,6 +15,8 @@ function initializeSocket(token: string): Socket | null {
socket.on('disconnect', () => { socket.on('disconnect', () => {
console.log('Disconnected from server'); console.log('Disconnected from server');
}); });
} else if (!socket) {
console.error('Socket not initialized');
} }
return socket; return socket;
} }

View File

@@ -1,6 +1,5 @@
const jwt = require("jsonwebtoken"); const jwt = require("jsonwebtoken");
const jwtSecret = process.env.JWT_SECRET; const jwtSecret = process.env.JWT_SECRET;
const { isValidUsername } = require("../utils/filter");
function generateJwtToken(username, user_id) { function generateJwtToken(username, user_id) {
try { try {
@@ -18,17 +17,19 @@ function verifyJwtToken(token) {
try { try {
const decoded = jwt.verify(token, jwtSecret, { algorithms: ["HS256"] }); const decoded = jwt.verify(token, jwtSecret, { algorithms: ["HS256"] });
if (!decoded?.user_id) { 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) { 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 }; return { username: decoded.username, user_id: decoded.user_id };
} catch (e) { } catch (e) {
console.error(e.message); console.error(e.message);
throw e; return { message: "Authorization failed" };
} }
} }

View File

@@ -24,7 +24,13 @@ const {
getMessages, getMessages,
} = require("./db/db.js"); } = require("./db/db.js");
const authorizeUser = require("./utils/authorize"); 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 { generateJwtToken, verifyJwtToken } = require("./auth/jwt");
const { initializeSocket } = require("./socket/socket"); const { initializeSocket } = require("./socket/socket");
const { getContacts, insertContact } = require("./db/db"); 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" }); 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 // Check for invalid characters in password
const validChars = /^[A-Za-z0-9!@#$%^&*(),.?":{}|<>]+$/; const validChars = /^[A-Za-z0-9!@#$%^&*(),.?":{}|<>]+$/;
if (!validChars.test(password)) { if (!validChars.test(password)) {
return res return res
.status(400) .status(400)
.json({ message: "Username contains invalid character" }); .json({ message: "Password contains invalid character" });
} }
// Validate username for invalid characters, length, and type // Validate username for invalid characters, length, and type
@@ -70,7 +72,11 @@ app.post("/api/auth/signup", async (req, res) => {
} }
// Validate form data length // 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" }); 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); const token = generateJwtToken(username, user_id);
res.cookie("token", token, { res.cookie("token", token, {
maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days
httpOnly: true,
secure: true,
}); });
return res.status(200).json({ message: "Successfully signed up" }); return res.status(200).json({ message: "Successfully signed up" });
@@ -114,10 +122,10 @@ app.post("/api/auth/login", async (req, res) => {
if ( if (
!username || !username ||
!password || !password ||
username.length < 4 || username.length < MIN_USERNAME_LENGTH ||
username.length > 20 || username.length > MAX_USERNAME_LENGTH ||
password.length < 8 || password.length < MIN_PASSWORD_LENGTH ||
password.length > 128 password.length > MAX_PASSWORD_LENGTH
) { ) {
return res.status(400).json({ message: "Invalid credentials" }); 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" }); 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" }); return res.status(500).json({ message: "Internal server error" });
}); });
} catch (e) { } catch (e) {
@@ -226,8 +235,8 @@ app.get("/api/chat/messages/:contact", authorizeUser, async (req, res) => {
if (!req.params.contact) { if (!req.params.contact) {
return res.status(400).json({ message: "Missing contact parameter" }); return res.status(400).json({ message: "Missing contact parameter" });
} }
const limit = parseInt(req.query.limit); const limit = parseInt(req.query.limit) || 50;
const cursor = parseInt(req.query.cursor); const cursor = parseInt(req.query.cursor) || 0;
const messages = await getMessages( const messages = await getMessages(
req.user.username, 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" }); 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); console.log("Sent messages for: ", req.user.username, "messages: ", messages);
return res.status(200).json({ 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); initializeSocket(io);
server.listen(PORT, () => { server.listen(PORT, () => {

View File

@@ -9,8 +9,8 @@ function authorizeUser(req, res, next) {
} }
const decoded = verifyJwtToken(token); const decoded = verifyJwtToken(token);
if (!decoded.user_id || !decoded.username) { if (decoded.message) {
return res.status(401).json({ message: "Invalid token" }); return res.status(401).json({ message: decoded.message });
} }
if (!isValidUsername(decoded.username)) { if (!isValidUsername(decoded.username)) {

View File

@@ -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) { function isValidUsername(username) {
if (typeof username !== "string") { if (typeof username !== "string") {
return null; return null;
} }
if (username.length < 4 || username.length > 20) { if (
username.length < MIN_USERNAME_LENGTH ||
username.length > MAX_USERNAME_LENGTH
) {
return null; return null;
} }
@@ -11,4 +19,10 @@ function isValidUsername(username) {
return validChars.test(username); return validChars.test(username);
} }
module.exports = { isValidUsername }; module.exports = {
isValidUsername,
MAX_PASSWORD_LENGTH,
MIN_PASSWORD_LENGTH,
MAX_USERNAME_LENGTH,
MIN_USERNAME_LENGTH,
};