verifying if user is admin when adding member

This commit is contained in:
slawk0
2024-12-14 23:20:41 +01:00
parent 9a0f8c6de6
commit 8cad73d01d
4 changed files with 46 additions and 11 deletions

View File

@@ -4,7 +4,6 @@ import { SubmitHandler, useForm } from 'react-hook-form';
import { axiosClient } from '../../App.tsx'; import { axiosClient } from '../../App.tsx';
import { ContactsProps } from '../../pages/Chat.tsx'; import { ContactsProps } from '../../pages/Chat.tsx';
import { socket } from '../../socket/socket.tsx'; import { socket } from '../../socket/socket.tsx';
import { AxiosResponse } from 'axios';
import { UserRoundPlus } from 'lucide-react'; import { UserRoundPlus } from 'lucide-react';
type Inputs = { type Inputs = {
@@ -23,17 +22,19 @@ function AddGroupMember({ contact }: AddGroupMemberProps) {
const [isLoading, setIsLoading] = useState<boolean>(false); const [isLoading, setIsLoading] = useState<boolean>(false);
const [notFound, setNotFound] = useState<boolean>(false); const [notFound, setNotFound] = useState<boolean>(false);
const [selectedIndex, setSelectedIndex] = useState<number>(0); const [selectedIndex, setSelectedIndex] = useState<number>(0);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
useEffect(() => { useEffect(() => {
const fetchSuggestions = async () => { const fetchSuggestions = async () => {
if (contactInput?.length >= 3) { if (contactInput?.length >= 3) {
try { try {
setIsLoading(true); setIsLoading(true);
const response: AxiosResponse<string[]> = await axiosClient.get( setErrorMessage(null);
const response = await axiosClient.get(
`/api/chat/contacts/suggestions/${contactInput}`, `/api/chat/contacts/suggestions/${contactInput}`,
); );
setSuggestions(response.data); setSuggestions(response.data);
setSelectedIndex(0); // Reset selection to first item when suggestions update setSelectedIndex(0);
if (response.data.length < 1) { if (response.data.length < 1) {
setIsLoading(false); setIsLoading(false);
setNotFound(true); setNotFound(true);
@@ -41,9 +42,12 @@ function AddGroupMember({ contact }: AddGroupMemberProps) {
setIsLoading(false); setIsLoading(false);
setNotFound(false); setNotFound(false);
} }
} catch (error) { } catch (e) {
setIsLoading(false); setIsLoading(false);
console.error('Error fetching suggestions:', error); console.error('Error fetching suggestions:', e);
setErrorMessage(
e.response?.data?.message || 'Failed to fetch suggestions',
);
} }
} else { } else {
setNotFound(false); setNotFound(false);
@@ -60,6 +64,7 @@ function AddGroupMember({ contact }: AddGroupMemberProps) {
}, [contactInput]); }, [contactInput]);
if (!socket) return; if (!socket) return;
const onSubmit: SubmitHandler<Inputs> = async (data) => { const onSubmit: SubmitHandler<Inputs> = async (data) => {
const contactToSubmit = const contactToSubmit =
suggestions.length > 0 suggestions.length > 0
@@ -68,19 +73,22 @@ function AddGroupMember({ contact }: AddGroupMemberProps) {
try { try {
setIsLoading(true); setIsLoading(true);
setErrorMessage(null);
const response = await axiosClient.post(`/api/chat/groups/addMember/`, { const response = await axiosClient.post(`/api/chat/groups/addMember/`, {
group_id: contact?.conversation_id, group_id: contact?.conversation_id,
username: contactToSubmit, username: contactToSubmit,
}); });
console.log(response.data); console.log('Add member to group', response);
setIsLoading(false); setIsLoading(false);
socket?.emit('added to group', { group_id: contact?.conversation_id }); socket?.emit('added to group', { group_id: contact?.conversation_id });
if (modalRef.current) { if (modalRef.current) {
modalRef.current.close(); modalRef.current.close();
} }
reset();
} catch (e) { } catch (e) {
console.error('Failed to create group: ', e); console.error('Failed to add group member: ', e);
setIsLoading(false); setIsLoading(false);
setErrorMessage(e.response?.data?.message || 'Failed to add member');
} }
}; };
@@ -134,7 +142,7 @@ function AddGroupMember({ contact }: AddGroupMemberProps) {
<div className="text-center"> <div className="text-center">
<form onSubmit={handleSubmit(onSubmit)}> <form onSubmit={handleSubmit(onSubmit)}>
<input <input
className="text-black bg-green-50 pl-2 shadow-lg rounded-md h-8 mb-2 mt-2" className="text-black bg-green-50 pl-2 shadow-lg rounded-md h-10 mb-2 mt-2"
type="text" type="text"
onKeyDown={handleKeyDown} onKeyDown={handleKeyDown}
{...register('username', { {...register('username', {
@@ -155,7 +163,6 @@ function AddGroupMember({ contact }: AddGroupMemberProps) {
: 'hover:bg-gray-500' : 'hover:bg-gray-500'
}`} }`}
onClick={() => { onClick={() => {
reset({ username: suggestion });
handleSubmit(() => handleSubmit(() =>
onSubmit({ username: suggestion }), onSubmit({ username: suggestion }),
)(); )();
@@ -176,6 +183,11 @@ function AddGroupMember({ contact }: AddGroupMemberProps) {
) : null} ) : null}
</div> </div>
</div> </div>
{errorMessage && (
<p className="text-red-500 mt-2 p-1 bg-gray-800 rounded-md w-full">
{errorMessage}
</p>
)}
</div> </div>
<div className="mt-4 flex justify-center"> <div className="mt-4 flex justify-center">

View File

@@ -14,6 +14,7 @@ function CreateGroupButton() {
const { const {
register, register,
handleSubmit, handleSubmit,
reset,
formState: { errors }, formState: { errors },
} = useForm<Inputs>(); } = useForm<Inputs>();
@@ -28,6 +29,7 @@ function CreateGroupButton() {
modalRef.current.close(); modalRef.current.close();
} }
} }
reset();
} catch (e) { } catch (e) {
console.error('Failed to create group: ', e); console.error('Failed to create group: ', e);
setIsLoading(false); setIsLoading(false);
@@ -62,7 +64,7 @@ function CreateGroupButton() {
className="w-full max-w-xs relative" className="w-full max-w-xs relative"
> >
<input <input
className="input input-bordered bg-green-50 w-full text-black rounded-md text-center" className="input input-bordered bg-green-50 w-full h-10 text-black rounded-md text-center"
{...register('groupName', { {...register('groupName', {
required: true, required: true,
minLength: 4, minLength: 4,

View File

@@ -1033,4 +1033,5 @@ module.exports = {
getMembers, getMembers,
removeUserFromGroupById, removeUserFromGroupById,
isConversationMember, isConversationMember,
isAdmin,
}; };

View File

@@ -42,6 +42,8 @@ const {
deleteMessage, deleteMessage,
getMembers, getMembers,
insertContactByUsername, insertContactByUsername,
isConversationMember,
isAdmin,
} = require("./db/db"); } = require("./db/db");
const { extname } = require("node:path"); const { extname } = require("node:path");
@@ -368,15 +370,22 @@ app.post("/api/chat/groups/create", authorizeUser, async (req, res) => {
}); });
}); });
app.post("/api/chat/groups/addMember", async (req, res) => { app.post("/api/chat/groups/addMember", authorizeUser, async (req, res) => {
const username = req.body.username; const username = req.body.username;
const group_id = req.body.group_id; const group_id = req.body.group_id;
const user_id = req.user.user_id;
if (!username) { if (!username) {
return res.status(400).json({ message: "Username not provided" }); return res.status(400).json({ message: "Username not provided" });
} }
if (!group_id) { if (!group_id) {
return res.status(400).json({ message: "group_id not provided" }); return res.status(400).json({ message: "group_id not provided" });
} }
const isUserAdmin = await isAdmin(user_id, group_id);
if (!isUserAdmin) {
return res.status(401).json({ message: "You are not group administrator" });
}
const result = await addMemberToGroupByUsername(group_id, username); const result = await addMemberToGroupByUsername(group_id, username);
if (result !== null) { if (result !== null) {
io.to(result).to(group_id).emit("added to group", { io.to(result).to(group_id).emit("added to group", {
@@ -417,6 +426,17 @@ app.get(
if (!conversation_id) { if (!conversation_id) {
return res.status(400).json({ message: "No conversation_id provided" }); return res.status(400).json({ message: "No conversation_id provided" });
} }
const isMember = await isConversationMember(
req.user.user_id,
conversation_id,
);
if (!isMember) {
return res
.status(401)
.json({ message: "You are not member of this conversation" });
}
const participants = await getMembers(conversation_id); const participants = await getMembers(conversation_id);
console.log( console.log(
`getMemers for conversation: ${conversation_id}, participants: ${participants} `, `getMemers for conversation: ${conversation_id}, participants: ${participants} `,