added message and contact input autofocus, getUserId db query, user_id to jwt

This commit is contained in:
slawk0
2024-10-13 14:12:15 +02:00
parent bd78e7c817
commit e6f4c58d13
6 changed files with 65 additions and 27 deletions

View File

@@ -20,13 +20,24 @@ function Chat() {
} = useForm<Input>();
const [contact, setContact] = useState<string>("");
const [messages, setMessages] = useState<string>("");
const [contactFocus, setContactFocus] = useState<boolean>(false);
const [messageFocus, setMessageFocus] = useState<boolean>(true);
useEffect(() => {
const storedContact = localStorage.getItem("contact");
if (storedContact) {
setContact(storedContact);
sendRequestHistorical(storedContact);
// setMessageFocus(true);
// setContactFocus(false);
}
}, []);
console.log(
"message focus: ",
messageFocus,
"contact focus: ",
contactFocus,
);
}, [messageFocus, contactFocus]);
// Sending message
const submitMessage: SubmitHandler<Input> = (data) => {
@@ -36,16 +47,17 @@ function Chat() {
}
console.log("sended message: " + data.message + " recipient: ", contact);
sendMessage(data.message, contact);
reset({ message: "" });
//reset({ message: "" });
};
// Sending contact
const submitContact: SubmitHandler<Input> = (data) => {
// store current contact in localstorage to load it after page reload
setContactFocus(false);
setMessageFocus(true);
localStorage.setItem("contact", data.contact);
setContact(data.contact);
sendContact(data.contact); //TODO zapisz w bazie danych te kontakty
console.log("Kontakt: " + data.contact + " zostal wyslany");
console.log("Contact submitted:", data.contact);
reset({ contact: "" });
};
@@ -60,6 +72,7 @@ function Chat() {
<input
className="text-black bg-green-100 pl-2 shadow-lg rounded-md h-8 mb-2 mt-2"
type="text"
autoFocus={contactFocus}
placeholder="Enter contact"
{...register("contact", {
// valid username length (validated on signup)
@@ -90,6 +103,7 @@ function Chat() {
className="w-full h-full object-cover"
src={zdjecie}
alt="walter"
draggable={false}
/>
</div>
<div className="text-center text-gray-200">
@@ -117,6 +131,7 @@ function Chat() {
<input
className="bg-green-100 text-black rounded-md w-full ml-1 mr-1 size-10"
type="text"
autoFocus={messageFocus}
placeholder="Enter message"
{...register("message", {
maxLength: 500,

View File

@@ -5,8 +5,14 @@ import react from "@vitejs/plugin-react";
export default defineConfig({
server: {
proxy: {
"/api": "http://localhost:3000",
"/socket.io": "http://localhost:3000",
"/api": {
target: "http://localhost:3000",
changeOrigin: true,
},
"/socket.io": {
target: "ws://localhost:3000",
ws: true,
},
},
},
plugins: [react()],

View File

@@ -1,10 +1,10 @@
const jwt = require("jsonwebtoken");
const jwtSecret = process.env.JWT_SECRET;
function generateJwtToken(username) {
function generateJwtToken(username, user_id) {
try {
return jwt.sign(
{ username: username },
{ username: username, user_id: user_id },
jwtSecret,
{ algorithm: "HS256" },
{ expiresIn: "30d" },
@@ -17,10 +17,10 @@ function generateJwtToken(username) {
function verifyJwtToken(token) {
try {
const decoded = jwt.verify(token, jwtSecret);
return { username: decoded.username };
return { username: decoded.username, user_id: decoded.user_id };
} catch (e) {
console.error(e);
return { errorMessage: e.message }; // Sending message to client because it's not backend error (in most cases i guess) so
return { errorMessage: e.message }; // Sending message to client because it's not backend error (in most cases I guess) so
}
}

View File

@@ -46,8 +46,8 @@ async function createTables() {
sender VARCHAR(128),
recipient VARCHAR(128) NOT NULL,
message VARCHAR(500),
timestamp VARCHAR(100),
message_id SERIAL PRIMARY KEY
timestamp VARCHAR(100)
);
`);
} catch (e) {
@@ -80,11 +80,24 @@ async function insertUser(username, password) {
}
}
async function getUserId(username) {
const query = `
SELECT user_id FROM accounts
WHERE username = $1;
`;
try {
const result = await client.query(query, [username]);
console.log("GETUSERID: ", result.rows[0].user_id);
return result.rows[0].user_id;
} catch (e) {
console.error("Failed to get user id", e);
}
}
async function insertMessage(sender, recipient, message) {
const timestamp = new Date().toLocaleString("pl-PL");
const query = `
INSERT INTO messages (sender, recipient, message, timestamp)
VALUES ($1, $2, $3)
VALUES ($1, $2, $3, $4)
RETURNING message_id;
`;
try {
@@ -97,7 +110,7 @@ async function insertMessage(sender, recipient, message) {
async function getMessages(username, recipient) {
const query = `
SELECT message, timestamp FROM messages
WHERE (username = $1 AND recipient = $2);
WHERE (sender = $1 AND recipient = $2);
`;
try {
const results = await client.query(query, [username, recipient]);
@@ -179,4 +192,5 @@ module.exports = {
insertContact,
removeContact,
getMessages,
getUserId,
};

View File

@@ -20,6 +20,7 @@ const {
checkUserExist,
changePassword,
getPassword,
getUserId,
} = require("./db/db.js");
const { generateJwtToken, verifyJwtToken } = require("./auth/jwt");
const { initializeSocket } = require("./socket/socket");
@@ -61,9 +62,10 @@ app.post("/api/auth/signup", async (req, res) => {
console.error("Failed to hash password ", err);
return;
}
await insertUser(username, hash, user_id, created_at);
await insertUser(username, hash);
});
const user_id = getUserId(username);
// Set JWT token to cookies
const token = generateJwtToken(username, user_id);
res.cookie("token", token, {
@@ -93,24 +95,25 @@ app.post("/api/auth/login", async (req, res) => {
if (!exist) {
return res.status(404).json({ message: "User does not exist" });
}
// Compare passwords
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 compare was successfully generate JWT token and store in cookies
if (result) {
const token = generateJwtToken(username); //TODO add username_id
res.cookie("token", token, {
maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days
});
return res.status(200).json({ message: "Successfully logged In" });
} else {
res.status(401).json({ message: "Invalid password" });
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" });
});
app.get("/api/auth/validate", (req, res) => {

View File

@@ -6,7 +6,7 @@ function initializeSocket(io) {
//TODO socket authorization
io.on("connection", (socket) => {
console.log("connected");
console.log(socket.id, "connected");
const token = socket.handshake.auth.token;
const { username } = verifyJwtToken(token);
@@ -26,8 +26,8 @@ function initializeSocket(io) {
const messages = getMessages(username, recipient);
io.to(username).emit("historical", { messages });
});
socket.on("disconnect", () => {
console.log("User disconnected");
socket.on("disconnect", (reason) => {
console.log(socket.id, " disconnected due to: ", reason);
});
});
}