improved authorization
This commit is contained in:
@@ -9,7 +9,7 @@ import Login from './pages/Login.tsx';
|
||||
import Signup from './pages/Signup.tsx';
|
||||
import ProtectedRoutes, { AuthContext } from './utils/ProtectedRoutes.tsx';
|
||||
import Settings from './pages/Settings.tsx';
|
||||
|
||||
import Lost from './pages/404.tsx';
|
||||
const router = createBrowserRouter([
|
||||
{
|
||||
path: '/',
|
||||
@@ -38,7 +38,7 @@ const router = createBrowserRouter([
|
||||
},
|
||||
{
|
||||
path: '*',
|
||||
element: <Navigate to="/lost" replace />,
|
||||
element: <Lost />,
|
||||
},
|
||||
]);
|
||||
|
||||
|
||||
@@ -1,24 +1,44 @@
|
||||
import io from 'socket.io-client';
|
||||
import Cookie from 'js-cookie';
|
||||
const token = Cookie.get('token');
|
||||
import { authorized } from '../utils/ProtectedRoutes.tsx';
|
||||
import Socket = SocketIOClient.Socket;
|
||||
import { useContext } from 'react';
|
||||
import { AuthContext } from '../utils/ProtectedRoutes.tsx';
|
||||
|
||||
//TODO socket is trying to connect on login page fix it
|
||||
|
||||
const socket = io({
|
||||
auth: {
|
||||
token: token,
|
||||
},
|
||||
});
|
||||
let socket: Socket | null = null;
|
||||
|
||||
if (authorized) {
|
||||
socket.on('connect', () => console.log('connected'));
|
||||
function initializeSocket(token: string): Socket | null {
|
||||
const { authorized } = useContext(AuthContext);
|
||||
// Only initialize if we don't already have a socket
|
||||
if (!socket && token && authorized) {
|
||||
socket = io({
|
||||
auth: {
|
||||
token: token,
|
||||
},
|
||||
});
|
||||
|
||||
socket.on('connect', () => console.log('connected'));
|
||||
|
||||
socket.on('disconnect', () => {
|
||||
console.log('Disconnected from server');
|
||||
});
|
||||
}
|
||||
return socket;
|
||||
}
|
||||
|
||||
socket.on('disconnect', () => {
|
||||
console.log('Disconnected from server');
|
||||
});
|
||||
function disconnectSocket() {
|
||||
if (socket) {
|
||||
socket.disconnect();
|
||||
socket = null;
|
||||
}
|
||||
}
|
||||
|
||||
function sendMessage(message: string, recipient: string | null) {
|
||||
if (!socket) {
|
||||
console.error('Socket not initialized');
|
||||
return;
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const year = now.getFullYear();
|
||||
const month = ('0' + (now.getMonth() + 1)).slice(-2);
|
||||
@@ -42,21 +62,38 @@ type Contact = {
|
||||
};
|
||||
|
||||
function sendContact(data: Contact) {
|
||||
if (!socket) {
|
||||
console.error('Socket not initialized');
|
||||
return;
|
||||
}
|
||||
|
||||
const { contact, read } = data;
|
||||
socket.emit('add contact', { contact: contact, read: read });
|
||||
console.log('Sent contact: ', contact, 'status: ', read);
|
||||
}
|
||||
|
||||
function sendRequestHistorical(recipient: string) {
|
||||
if (!socket) {
|
||||
console.error('Socket not initialized');
|
||||
return;
|
||||
}
|
||||
|
||||
socket.emit('historical', { recipient: recipient });
|
||||
console.log('Requested historical messages for: ', recipient);
|
||||
}
|
||||
|
||||
function sendGetContacts(username: string) {
|
||||
if (!socket) {
|
||||
console.error('Socket not initialized');
|
||||
return;
|
||||
}
|
||||
|
||||
socket.emit('get contacts', username);
|
||||
console.log('Requested contact list for: ', username);
|
||||
}
|
||||
export {
|
||||
initializeSocket,
|
||||
disconnectSocket,
|
||||
sendMessage,
|
||||
sendContact,
|
||||
sendRequestHistorical,
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Navigate, Outlet } from 'react-router-dom';
|
||||
import axios from 'axios';
|
||||
import { useState, useEffect, createContext, useContext } from 'react';
|
||||
import Cookie from 'js-cookie';
|
||||
import { initializeSocket } from '../socket/socket.tsx';
|
||||
|
||||
export type UsernameType = {
|
||||
username: string | null;
|
||||
@@ -10,18 +11,18 @@ export type UsernameType = {
|
||||
|
||||
type AuthContextType = {
|
||||
authorized: boolean | null;
|
||||
setAuthorized: (value: boolean | null) => void;
|
||||
setAuthorized: (value: boolean) => void;
|
||||
};
|
||||
|
||||
export const AuthContext = createContext<AuthContextType>({
|
||||
authorized: null,
|
||||
authorized: false,
|
||||
setAuthorized: () => {},
|
||||
});
|
||||
|
||||
export const useAuth = () => useContext(AuthContext);
|
||||
//export const useAuth = () => useContext(AuthContext);
|
||||
|
||||
function ProtectedRoutes() {
|
||||
const { authorized, setAuthorized } = useAuth();
|
||||
const { authorized, setAuthorized } = useContext(AuthContext);
|
||||
const [username, setUsername] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -38,6 +39,7 @@ function ProtectedRoutes() {
|
||||
setUsername(res.data.username);
|
||||
console.log(res.data.username);
|
||||
setAuthorized(true);
|
||||
initializeSocket(token);
|
||||
})
|
||||
.catch((err) => {
|
||||
setAuthorized(false);
|
||||
|
||||
@@ -15,12 +15,12 @@ function generateJwtToken(username, user_id) {
|
||||
|
||||
function verifyJwtToken(token) {
|
||||
try {
|
||||
const decoded = jwt.verify(token, jwtSecret);
|
||||
if (decoded.user_id) {
|
||||
console.log("verifyJwtToken decoded: ", decoded);
|
||||
return { username: decoded.username, user_id: decoded.user_id };
|
||||
const decoded = jwt.verify(token, jwtSecret, { algorithms: ["HS256"] });
|
||||
if (!decoded?.user_id) {
|
||||
throw new Error("Token verification failed - missing user_id");
|
||||
}
|
||||
console.log("verifyJwtToken decoded: ", decoded);
|
||||
return { username: decoded.username, user_id: decoded.user_id };
|
||||
} catch (e) {
|
||||
console.error(e.message);
|
||||
throw e;
|
||||
|
||||
@@ -13,25 +13,25 @@ function initializeSocket(io) {
|
||||
const token = socket.handshake.auth.token;
|
||||
if (!token) {
|
||||
console.log("(socket) Not logged in");
|
||||
return next(new Error("Not logged in"));
|
||||
return next(new Error("(socket) 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"));
|
||||
console.log("(socket) Invalid token payload");
|
||||
return next(new Error("(socket) Invalid token payload"));
|
||||
}
|
||||
|
||||
socket.username = username;
|
||||
socket.user_id = user_id;
|
||||
console.log(
|
||||
`socket id: ${socket.id}, username: ${username}, user_id: ${user_id}`,
|
||||
`(socket) 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"));
|
||||
console.error("(socket) Token verification failed:", error.message);
|
||||
next(new Error("(socket) Invalid token"));
|
||||
}
|
||||
});
|
||||
|
||||
@@ -39,7 +39,11 @@ function initializeSocket(io) {
|
||||
const username = socket.username;
|
||||
if (!username) {
|
||||
socket.on("disconnect", () => {
|
||||
console.log(socket.id, " disconnected due to: invalid username/token");
|
||||
console.log(
|
||||
"(socket)",
|
||||
socket.id,
|
||||
" disconnected due to: invalid username/token",
|
||||
);
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -48,7 +52,7 @@ function initializeSocket(io) {
|
||||
const sendContactList = async () => {
|
||||
const contacts = await getContacts(username);
|
||||
io.to(username).emit("contacts list", contacts);
|
||||
console.log("sent on 'contacts list: ", contacts);
|
||||
console.log("(socket) sent on 'contacts list: ", contacts);
|
||||
};
|
||||
|
||||
await sendContactList(username);
|
||||
@@ -66,7 +70,7 @@ function initializeSocket(io) {
|
||||
timestamp,
|
||||
);
|
||||
const message_id = insertedMessage.message_id;
|
||||
console.log("received from chat message", msg);
|
||||
console.log("(socket) received from chat message", msg);
|
||||
|
||||
io.to(username).to(recipient).emit("chat message", {
|
||||
sender,
|
||||
@@ -75,7 +79,7 @@ function initializeSocket(io) {
|
||||
timestamp,
|
||||
message_id,
|
||||
});
|
||||
console.log("sent on 'chat message' socket: ", {
|
||||
console.log("(socket) sent on 'chat message' socket: ", {
|
||||
sender,
|
||||
message,
|
||||
recipient,
|
||||
@@ -98,11 +102,11 @@ function initializeSocket(io) {
|
||||
}
|
||||
insertContact(username, contact, read);
|
||||
io.to(username).emit("contact", { contact, read });
|
||||
console.log("sent on 'contact' socket: ", { contact, read });
|
||||
console.log("(socket) sent on 'contact' socket: ", { contact, read });
|
||||
});
|
||||
|
||||
socket.on("disconnect", (reason) => {
|
||||
console.log(socket.id, " disconnected due to: ", reason);
|
||||
console.log("(socket)", socket.id, " disconnected due to: ", reason);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user