added server site socket authorization, initializeSocket function
This commit is contained in:
@@ -1,27 +0,0 @@
|
||||
import io from "socket.io-client";
|
||||
import Cookie from "js-cookie";
|
||||
import { useEffect, useState } from "react";
|
||||
import { sendRequestHistorical } from "../socket/socket.tsx";
|
||||
import { socket } from "../socket/socket.tsx";
|
||||
|
||||
function messagesArea() {
|
||||
const [messages, setMessages] = useState<string[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
const messageHandler = (message: string) => {
|
||||
setMessages((prevMessages) => [...prevMessages, message]);
|
||||
};
|
||||
|
||||
socket.on("chat message", (msg) => {
|
||||
messageHandler(msg);
|
||||
});
|
||||
});
|
||||
const messageList = messages.map((message) => <li key={index}>{message}</li>);
|
||||
|
||||
return (
|
||||
<>
|
||||
<ul>{messageList}</ul>
|
||||
</>
|
||||
);
|
||||
}
|
||||
export default messagesArea;
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useForm, SubmitHandler } from "react-hook-form";
|
||||
import { sendContact, sendRequestHistorical } from "../socket/socket.tsx";
|
||||
import { sendContact, sendRequestHistorical } from "../../socket/socket.tsx";
|
||||
import { Dispatch, SetStateAction, useEffect } from "react";
|
||||
|
||||
type Input = {
|
||||
@@ -1,4 +1,4 @@
|
||||
import zdjecie from "../../assets/walter.png";
|
||||
import zdjecie from "../../../assets/walter.png";
|
||||
|
||||
type ContactProfileProps = {
|
||||
contact: string;
|
||||
44
client/src/components/chat/MessagesArea.tsx
Normal file
44
client/src/components/chat/MessagesArea.tsx
Normal file
@@ -0,0 +1,44 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { sendRequestHistorical } from "../../socket/socket.tsx";
|
||||
import { socket } from "../../socket/socket.tsx";
|
||||
|
||||
type chatMessages = {
|
||||
senderUsername: string;
|
||||
message: string;
|
||||
recipient: string;
|
||||
message_id: number;
|
||||
timestamp: string;
|
||||
};
|
||||
|
||||
function messagesArea() {
|
||||
const [messages, setMessages] = useState<chatMessages[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
console.log("Requesting previous messages");
|
||||
sendRequestHistorical("username");
|
||||
|
||||
const messageHandler = (msg: chatMessages) => {
|
||||
setMessages((prevMessages) => [...prevMessages, msg]);
|
||||
};
|
||||
|
||||
socket.on("chat message", (msg: chatMessages) => {
|
||||
console.log("Received data: ", msg);
|
||||
messageHandler(msg);
|
||||
});
|
||||
return () => {
|
||||
socket.off("chat message");
|
||||
};
|
||||
}, []);
|
||||
const messageList = messages.map((msg, index) => (
|
||||
<li key={index}>
|
||||
{msg.senderUsername}: {msg.message}
|
||||
</li>
|
||||
));
|
||||
|
||||
return (
|
||||
<>
|
||||
<ul>{messageList}</ul>
|
||||
</>
|
||||
);
|
||||
}
|
||||
export default messagesArea;
|
||||
@@ -1,4 +1,4 @@
|
||||
import zdjecie from "../../assets/walter.png";
|
||||
import zdjecie from "../../../assets/walter.png";
|
||||
|
||||
function UserProfile() {
|
||||
return (
|
||||
@@ -1,8 +1,8 @@
|
||||
import MessageForm from "../components/MessageForm.tsx";
|
||||
import ContactProfile from "../components/ContactProfile.tsx";
|
||||
import UserProfile from "../components/UserProfile.tsx";
|
||||
import ContactForm from "../components/ContactForm.tsx";
|
||||
import MessagesArea from "../components/MessagesArea.tsx";
|
||||
import MessageForm from "../components/chat/MessageForm.tsx";
|
||||
import ContactProfile from "../components/chat/ContactProfile.tsx";
|
||||
import UserProfile from "../components/chat/UserProfile.tsx";
|
||||
import ContactForm from "../components/chat/ContactForm.tsx";
|
||||
import MessagesArea from "../components/chat/MessagesArea.tsx";
|
||||
import { useState } from "react";
|
||||
|
||||
function Chat() {
|
||||
|
||||
@@ -1,18 +1,36 @@
|
||||
import io from "socket.io-client";
|
||||
import Cookie from "js-cookie";
|
||||
const socket = io({
|
||||
auth: {
|
||||
token: Cookie.get("token"),
|
||||
},
|
||||
});
|
||||
import Socket = SocketIOClient.Socket;
|
||||
const token = Cookie.get("token");
|
||||
|
||||
socket.on("connect", () => console.log("connected"));
|
||||
socket.on("disconnect", () => {
|
||||
console.log("Disconnected from server");
|
||||
});
|
||||
let socket: Socket;
|
||||
|
||||
export function initializeSocket() {
|
||||
if (token && !socket) {
|
||||
socket = io({
|
||||
auth: {
|
||||
token: token,
|
||||
},
|
||||
autoConnect: false,
|
||||
});
|
||||
|
||||
socket.on("connect", () => console.log("connected"));
|
||||
socket.on("disconnect", (reason: string) => {
|
||||
console.log("Disconnected from server ", reason);
|
||||
});
|
||||
}
|
||||
socket.connect();
|
||||
return socket;
|
||||
}
|
||||
|
||||
export function disconnectSocket() {
|
||||
if (socket) {
|
||||
socket.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
function sendMessage(message: string, recipient: string | null) {
|
||||
const timestamp = new Date().toLocaleDateString();
|
||||
const timestamp = new Date().toString();
|
||||
socket.emit("chat message", {
|
||||
message: message,
|
||||
recipient: recipient,
|
||||
|
||||
@@ -14,9 +14,9 @@ function useAuth() {
|
||||
|
||||
try {
|
||||
await axios.get("/api/auth/validate", { withCredentials: true });
|
||||
setAuthorized(true); // If validation is successful, user is authorized
|
||||
setAuthorized(true);
|
||||
} catch (error) {
|
||||
setAuthorized(false); // Token validation failed
|
||||
setAuthorized(false);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ function verifyJwtToken(token) {
|
||||
const decoded = jwt.verify(token, jwtSecret);
|
||||
return { username: decoded.username, user_id: decoded.user_id };
|
||||
} catch (e) {
|
||||
console.error(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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -97,23 +97,23 @@ app.post("/api/auth/login", async (req, res) => {
|
||||
}
|
||||
const hashedPassword = await getPassword(username);
|
||||
// Compare passwords
|
||||
bcrypt.compare(password, hashedPassword, (err, result) => {
|
||||
if (err) {
|
||||
console.error("Failed to compare password ", err);
|
||||
return result;
|
||||
}
|
||||
|
||||
if (!result) {
|
||||
return res.status(401).json({ message: "Invalid password" });
|
||||
}
|
||||
});
|
||||
|
||||
const user_id = await getUserId(username);
|
||||
const token = generateJwtToken(username, user_id);
|
||||
res.cookie("token", token, {
|
||||
maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days
|
||||
});
|
||||
return res.status(200).json({ message: "Successfully logged In" });
|
||||
bcrypt
|
||||
.compare(password, hashedPassword)
|
||||
.then(async (result) => {
|
||||
if (!result) {
|
||||
res.status(401).json({ message: "Invalid password" });
|
||||
return;
|
||||
}
|
||||
const user_id = await getUserId(username);
|
||||
const token = generateJwtToken(username, user_id);
|
||||
res.cookie("token", token, {
|
||||
maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days
|
||||
});
|
||||
return res.status(200).json({ message: "Successfully logged In" });
|
||||
})
|
||||
.catch((err) => {
|
||||
res.status(500).json({ message: "Internal server error" });
|
||||
});
|
||||
});
|
||||
|
||||
app.get("/api/auth/validate", (req, res) => {
|
||||
|
||||
@@ -3,30 +3,58 @@ const { insertMessage, getMessages } = require("../db/db");
|
||||
const { verifyJwtToken } = require("../auth/jwt");
|
||||
|
||||
function initializeSocket(io) {
|
||||
//TODO socket authorization
|
||||
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("Not logged in");
|
||||
next(new Error("Not logged in"));
|
||||
}
|
||||
});
|
||||
|
||||
io.on("connection", (socket) => {
|
||||
console.log(socket.id, "connected");
|
||||
|
||||
const token = socket.handshake.auth.token;
|
||||
const { username } = verifyJwtToken(token);
|
||||
socket.join(username);
|
||||
const username = socket.username;
|
||||
// if (!username) {
|
||||
// socket.on("disconnect", () => {
|
||||
// console.log(socket.id, " disconnected due to: invalid username/token");
|
||||
// });
|
||||
// }
|
||||
console.log(`${socket.id}, ${username}, connected`);
|
||||
socket.join(username); // join username room
|
||||
|
||||
socket.on("chat message", (msg) => {
|
||||
const { message, recipient, timestamp } = msg;
|
||||
const senderUsername = username;
|
||||
if (!message || recipient.length < 4 || !recipient) {
|
||||
return;
|
||||
}
|
||||
const results = insertMessage(username, recipient, message, timestamp);
|
||||
const message_id = results.message_id;
|
||||
console.log("id: ", message_id);
|
||||
if (message_id) {
|
||||
}
|
||||
console.log("received from chat message", msg);
|
||||
|
||||
io.to(username)
|
||||
.to(recipient)
|
||||
.emit("chat message", { message, recipient, message_id, timestamp });
|
||||
io.to(username).to(recipient).emit("chat message", {
|
||||
senderUsername,
|
||||
message,
|
||||
recipient,
|
||||
timestamp,
|
||||
});
|
||||
console.log("sended: ", {
|
||||
senderUsername,
|
||||
message,
|
||||
recipient,
|
||||
timestamp,
|
||||
});
|
||||
});
|
||||
|
||||
socket.on("historical", (recipient) => {
|
||||
|
||||
Reference in New Issue
Block a user