authorization code refactor, added insertContact function

This commit is contained in:
slawk0
2024-10-22 17:50:32 +02:00
parent 7b13996154
commit c2af7f744e
6 changed files with 83 additions and 37 deletions

View File

@@ -1,4 +1,4 @@
import { socket } from '../../socket/socket.tsx';
import { sendRequestHistorical, socket } from '../../socket/socket.tsx';
import { useEffect, useState } from 'react';
type Contact = {
@@ -10,6 +10,8 @@ function ContactsList() {
const [contacts, setContacts] = useState<Contact[]>([]);
useEffect(() => {
sendRequestHistorical();
function contactHandler(contactInf: Contact) {
setContacts((prevContacts) => {
// Check if the contact already exists
@@ -21,7 +23,7 @@ function ContactsList() {
}
socket.on('contact', (contactInf: Contact) => {
console.log('Added contact');
console.log('Received contact: ', contactInf);
contactHandler(contactInf);
});
}, []);

View File

@@ -37,7 +37,7 @@ type Contact = {
};
function sendContact(data: Contact) {
const { contact, read } = data;
socket.emit('contact', { contact: contact, read: read });
socket.emit('add contact', { contact: contact, read: read });
console.log('Sent contact: ', contact, 'status: ', read);
}
@@ -45,4 +45,15 @@ function sendRequestHistorical(recipient: string) {
socket.emit('historical', { recipient: recipient });
console.log('Requested historical messages for: ', recipient);
}
export { sendMessage, sendContact, sendRequestHistorical, socket };
function sendGetContacts(username: string) {
socket.emit('get contacts', username);
console.log('Requested contact list');
}
export {
sendMessage,
sendContact,
sendRequestHistorical,
sendGetContacts,
socket,
};

View File

@@ -11,16 +11,19 @@ function generateJwtToken(username, user_id) {
);
} catch (e) {
console.log("Failed to generate JWT token, ", e);
throw e;
}
}
function verifyJwtToken(token) {
try {
const decoded = jwt.verify(token, jwtSecret);
return { username: decoded.username, user_id: decoded.user_id };
if (decoded.user_id) {
return { username: decoded.username, user_id: decoded.user_id };
}
} catch (e) {
console.error(e.message);
return { errorMessage: e.message }; // Sending message to client because it's not backend error (in most cases I guess) so
throw e;
}
}

View File

@@ -116,8 +116,7 @@ async function insertMessage(sender, recipient, message, timestamp) {
}
async function getMessages(username, recipient) {
username = username.trim();
recipient = recipient.trim();
console.log(`Username: ${username}, recipient: ${recipient}`);
const query = `
SELECT * FROM messages
WHERE (sender = $1 AND recipient = $2) OR (sender = $2 AND recipient = $1)
@@ -132,7 +131,6 @@ async function getMessages(username, recipient) {
}
async function checkUserExist(username) {
username = username.trim();
const query = `
SELECT COUNT(*) FROM accounts
WHERE username = $1;
@@ -147,7 +145,6 @@ async function checkUserExist(username) {
}
async function getPassword(username) {
username = username.trim();
const query = `
SELECT password FROM accounts
WHERE username = $1;
@@ -161,7 +158,6 @@ async function getPassword(username) {
}
async function changePassword(username, newPassword) {
username = username.trim();
const query = `
UPDATE accounts
SET password = $1
@@ -175,7 +171,6 @@ async function changePassword(username, newPassword) {
}
async function insertContact(username, usernameContact, read) {
username = username.trim();
console.log(
`insertContact username: ${username}, usernameContact: ${usernameContact}, read: ${read}`,
);
@@ -190,6 +185,19 @@ async function insertContact(username, usernameContact, read) {
}
}
async function getContacts(username) {
const query = `
SELECT * FROM contacts
WHERE username = $1;
`;
try {
const result = await client.query(query, [username]);
return result.rows;
} catch (e) {
console.error("Failed to get contacts ", e);
}
}
async function removeContact(username, usernameContact) {
username = username.trim();
usernameContact = usernameContact.trim();
@@ -215,4 +223,5 @@ module.exports = {
removeContact,
getMessages,
getUserId,
getContacts,
};

View File

@@ -38,7 +38,7 @@ app.use(bodyParser.json());
app.use(cookieParser());
app.post("/api/auth/signup", async (req, res) => {
const username = req.body.username.toLowerCase();
const username = req.body.username.toLowerCase().trim();
const password = req.body.password;
console.log(username);
// Validate form data length
@@ -75,7 +75,7 @@ app.post("/api/auth/signup", async (req, res) => {
});
app.post("/api/auth/login", async (req, res) => {
const username = req.body.username;
const username = req.body.username.trim().toLowerCase();
const password = req.body.password;
if (

View File

@@ -1,30 +1,39 @@
const { Server } = require("socket.io");
const { insertMessage, getMessages, insertContact } = require("../db/db");
const {
insertMessage,
getMessages,
insertContact,
getContacts,
} = require("../db/db");
const { verifyJwtToken } = require("../auth/jwt");
const console = require("node:console");
function initializeSocket(io) {
io.use((socket, next) => {
// user auth
const token = socket.handshake.auth.token;
if (token) {
const { username, user_id } = verifyJwtToken(token);
if (username && user_id) {
socket.username = username;
console.log(
`socket id: ${socket.id}, username: ${username}, user_id: ${user_id}`,
);
next();
} else {
console.log("Invalid token");
next(new Error("Invalid token"));
}
} else {
if (!token) {
console.log("Not logged in");
next(new Error("Not logged in"));
return next(new Error("Not logged in"));
}
try {
const { username, user_id } = verifyJwtToken(token);
if (!username || !user_id) {
console.log("Invalid token payload");
return next(new Error("Invalid token payload"));
}
socket.username = username;
socket.user_id = user_id;
console.log(
`socket id: ${socket.id}, username: ${username}, user_id: ${user_id}`,
);
next();
} catch (error) {
console.error("Token verification failed:", error.message);
next(new Error("Invalid token"));
}
});
io.on("connection", (socket) => {
const username = socket.username;
if (!username) {
@@ -40,13 +49,13 @@ function initializeSocket(io) {
if (!message || recipient.length < 4 || !recipient) {
return;
}
const results = await insertMessage(
const insertedMessage = await insertMessage(
username,
recipient,
message,
timestamp,
);
const message_id = results.message_id;
const message_id = insertedMessage.message_id;
console.log("received from chat message", msg);
io.to(username).to(recipient).emit("chat message", {
@@ -56,7 +65,7 @@ function initializeSocket(io) {
timestamp,
message_id,
});
console.log("sent: ", {
console.log("sent on 'chat message' socket: ", {
sender,
message,
recipient,
@@ -70,10 +79,22 @@ function initializeSocket(io) {
io.to(username).emit("historical", messages);
});
socket.on("contact", (contactInf) => {
const { contact, read } = contactInf;
socket.on("add contact", (contactInf) => {
let { contact, read } = contactInf;
if (contact) {
if (contact.length < 4 || contact.length > 20) {
return;
}
}
insertContact(username, contact, read);
socket.to(username).emit({ contact, read });
io.to(username).emit("contact", { contact, read });
console.log("sent on 'contact' socket: ", { contact, read });
});
socket.on("get contacts", (username) => {
const contacts = getContacts(username);
io.to(username).emit(contacts);
console.log("sent on 'get contacts: ", contacts);
});
socket.on("disconnect", (reason) => {
console.log(socket.id, " disconnected due to: ", reason);