fixed undefined user_id after signup

This commit is contained in:
slawk0
2024-10-23 22:40:00 +02:00
parent 85c086c496
commit c853256dfe
6 changed files with 98 additions and 87 deletions

View File

@@ -2,40 +2,41 @@ import {
RouterProvider,
createBrowserRouter,
Navigate,
} from "react-router-dom";
import Chat from "./pages/Chat.tsx";
import Login from "./pages/Login.tsx";
import Signup from "./pages/Signup.tsx";
import ProtectedRoutes from "./utils/ProtectedRoutes.tsx";
import Settings from "./pages/Settings.tsx";
} from 'react-router-dom';
import Chat from './pages/Chat.tsx';
import Login from './pages/Login.tsx';
import Signup from './pages/Signup.tsx';
import ProtectedRoutes from './utils/ProtectedRoutes.tsx';
import Settings from './pages/Settings.tsx';
const router = createBrowserRouter([
{
path: "/",
path: '/',
element: <Navigate to="/chat" replace />,
},
{
element: <ProtectedRoutes />,
children: [
{
path: "/chat",
path: '/chat',
element: <Chat />,
},
{
path: "/settings",
path: '/settings',
element: <Settings />,
},
],
},
{
path: "/login",
path: '/login',
element: <Login />,
},
{
path: "/signup",
path: '/signup',
element: <Signup />,
},
{
path: "*",
path: '*',
element: <Navigate to="/lost" replace />,
},
]);

View File

@@ -1,6 +1,5 @@
import { socket } from '../../socket/socket.tsx';
import { useEffect, useState } from 'react';
type ContactList = {
username: string;
usernamecontact: string;
@@ -22,14 +21,14 @@ function ContactsList() {
}, []);
const contactsList = contacts.map((contacts: ContactList, index) => (
<li className="hover:bg-gray-800" key={index}>
<li className="hover:bg-green-700 p-2 rounded cursor-pointer" key={index}>
{contacts.usernamecontact}
</li>
));
return (
<div className="flex-grow overflow-y-auto w-64">
<ul className="m-2 flex-grow-1">{contactsList}</ul>
<ul className="m-2 flex-grow-1 ">{contactsList}</ul>
</div>
);
}

View File

@@ -44,7 +44,12 @@ function UserProfile() {
role="menuitem"
onClick={logout}
>
<img className="w-5 mr-2" src={logoutIcon} alt="log out ico" />
<img
className="w-5 mr-2"
draggable={false}
src={logoutIcon}
alt="log out ico"
/>
<p>Log out</p>
</a>
</div>

View File

@@ -2,11 +2,13 @@ import io from 'socket.io-client';
import Cookie from 'js-cookie';
const token = Cookie.get('token');
//TODO socket is trying to connect on login page fix it
const socket = io({
auth: {
token: token,
},
});
socket.on('connect', () => console.log('connected'));
socket.on('disconnect', () => {

View File

@@ -3,12 +3,10 @@ const jwtSecret = process.env.JWT_SECRET;
function generateJwtToken(username, user_id) {
try {
return jwt.sign(
{ username: username, user_id: user_id },
jwtSecret,
{ algorithm: "HS256" },
{ expiresIn: "30d" },
);
return jwt.sign({ username: username, user_id: user_id }, jwtSecret, {
algorithm: "HS256",
expiresIn: "30d",
});
} catch (e) {
console.log("Failed to generate JWT token, ", e);
throw e;

View File

@@ -38,81 +38,87 @@ app.use(bodyParser.json());
app.use(cookieParser());
app.post("/api/auth/signup", async (req, res) => {
const username = req.body.username.toLowerCase().trim();
const password = req.body.password;
console.log(username);
// Validate form data length
if (!username || username.length < 4 || username.length > 20) {
return res.status(400).json({ message: "Invalid username length" });
}
if (!password || password.length < 8 || password.length > 128) {
return res.status(400).json({ message: "Invalid password length" });
}
// Checks if the user already exists in database (returns result.rows[0].count > 0;)
const exist = await checkUserExist(username);
if (exist) {
return res.status(409).json({ message: "User already exist" });
}
// Hash password and insert hash and username to database
bcrypt.hash(password, saltRounds, async (err, hash) => {
if (err) {
console.error("Failed to hash password ", err);
return;
try {
const username = req.body.username.toLowerCase().trim();
const password = req.body.password;
console.log(username);
// Validate form data length
if (!username || username.length < 4 || username.length > 20) {
return res.status(400).json({ message: "Invalid username length" });
}
if (!password || password.length < 8 || password.length > 128) {
return res.status(400).json({ message: "Invalid password length" });
}
// Checks if the user already exists in database (returns result.rows[0].count > 0;)
const exist = await checkUserExist(username);
if (exist) {
return res.status(409).json({ message: "User already exist" });
}
// Hash password and insert hash and username to database
const hash = await bcrypt.hash(password, saltRounds);
await insertUser(username, hash);
});
const user_id = await getUserId(username);
const user_id = getUserId(username);
// Set JWT token to cookies
const token = generateJwtToken(username, user_id);
res.cookie("token", token, {
maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days
});
// Set JWT token to cookies
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 signed up" });
return res.status(200).json({ message: "Successfully signed up" });
} catch (e) {
console.error("Signup error: ", e);
return res.status(500).json({ message: "internal server error" });
}
});
app.post("/api/auth/login", async (req, res) => {
const username = req.body.username.trim().toLowerCase();
const password = req.body.password;
try {
const username = req.body.username.trim().toLowerCase();
const password = req.body.password;
if (
!username ||
!password ||
username.length < 4 ||
username.length > 20 ||
password.length < 8 ||
password.length > 128
) {
return res.status(400).json({ message: "Invalid credentials" });
}
if (
!username ||
!password ||
username.length < 4 ||
username.length > 20 ||
password.length < 8 ||
password.length > 128
) {
return res.status(400).json({ message: "Invalid credentials" });
}
// Checks if the user exist
const exist = await checkUserExist(username);
if (!exist) {
return res.status(404).json({ message: "User does not exist" });
}
const hashedPassword = await getPassword(username);
// Compare passwords
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
// Checks if the user exist
const exist = await checkUserExist(username);
if (!exist) {
return res.status(404).json({ message: "User does not exist" });
}
const hashedPassword = await getPassword(username);
// Compare passwords
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) => {
return res.status(500).json({ message: "Internal server error" });
});
return res.status(200).json({ message: "Successfully logged In" });
})
.catch((err) => {
return res.status(500).json({ message: "Internal server error" });
});
} catch (e) {
console.error("Login error: ", e);
return res.status(500).json({ message: "Internal server error" });
}
});
app.get("/api/auth/validate", (req, res) => {