Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat/owner-chat-actions #135

Merged
merged 9 commits into from
Nov 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion backend/src/chat/chat.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,15 @@ import {
HttpStatus,
Logger,
ParseIntPipe,
Patch,
Post,
Query,
Req,
UseGuards,
} from '@nestjs/common';
import { ChatService } from './chat.service';
import { chatMemberRole, chatType } from '@prisma/client';
import { User, chatMemberRole, chatType } from '@prisma/client';
import { AccessTokenGuard } from 'src/auth/jwt/jwt.guard';

// create a new chat in the database using post request
// get all chats from the database using get request
Expand All @@ -27,11 +31,13 @@ export class ChatController {
): Promise<boolean> {
const you = await this.chatService.getMemberFromChat(chatId, login);
const member = await this.chatService.getMemberFromChat(chatId, user);

// Me and him must exist in the database
if (!you || !member) {
this.logger.error('Unable to find user or member');
return true;
}

// I cannot be the member I want to mute, I cannot be member to mute, I cannot mute an admin nor the owner
if (you === member || you.role === 'MEMBER' || member.role !== 'MEMBER') {
this.logger.error('You are not allowed to mute this user');
Expand Down Expand Up @@ -189,4 +195,21 @@ export class ChatController {
throw new HttpException({ error }, HttpStatus.FORBIDDEN);
}
}

// Patch to update a chat password if the user is the owner
@UseGuards(AccessTokenGuard)
@Patch('/password')
async updateChatPassword(
@Req() request: Request & { user: User },
@Body() body: { chatId: number; password: string },
) {
const { chatId, password } = body;
const { login } = request.user;
const updatedChat = await this.chatService.updateChatPassword(
chatId,
password,
login,
);
return updatedChat;
}
}
69 changes: 68 additions & 1 deletion backend/src/chat/chat.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { Injectable } from '@nestjs/common';
import {
HttpException,
Injectable,
NotFoundException,
UnauthorizedException,
} from '@nestjs/common';
import {
Chat,
ChatMember,
Expand Down Expand Up @@ -666,6 +671,68 @@ export class ChatService {
return isPasswordValid;
}

async updateChatPassword(
chatId: number,
password: string,
userLogin: string,
): Promise<Chat | null> {
// check if user is the owner of the chat
const chat = await this.prisma.chat.findUnique({
where: {
id: chatId,
},
});

if (!chat) {
throw new NotFoundException('Chat not found');
}

if (chat.owner !== userLogin) {
throw new UnauthorizedException('You are not the owner of this chat');
}

if (chat.chatType !== 'PROTECTED' || !chat.password) {
throw new HttpException(
{
status: 403,
error: 'Chat is not protected',
},
403,
);
}

// if password is empty, remove password and set chat type to public
if (!password) {
const updatedChat = await this.prisma.chat.update({
where: {
id: chatId,
},
data: {
password: null,
chatType: 'PUBLIC',
},
});

return updatedChat;
}

try {
const updatedChat = await this.prisma.chat.update({
where: {
id: chatId,
},
data: {
password: await argon2.hash(password),
},
});

return updatedChat;
} catch (error) {
console.log(error);
return null;
}
}

async getChatByName(name: string): Promise<Chat> {
try {
const chat = await this.prisma.chat.findFirst({
Expand Down
19 changes: 8 additions & 11 deletions frontend/src/app/(private)/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,13 @@ export default function RootPrivateLayout({
children: React.ReactNode;
}) {
return (
<html lang="en">
<body className="bg-black42-100 flex">
<Providers>
<ChatProvider>
<div className="flex flex-col flex-1">{children}</div>
<Toaster />
</ChatProvider>
</Providers>
<Toaster />
</body>
</html>
<>
<Providers>
<ChatProvider>
<div className="flex flex-col flex-1 bg-black42-100">{children}</div>
<Toaster />
</ChatProvider>
</Providers>
</>
);
}
8 changes: 3 additions & 5 deletions frontend/src/app/auth/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,8 @@ export default function RootLoginPublicLayout({
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>
<Providers>{children}</Providers>
</body>
</html>
<>
<Providers>{children}</Providers>
</>
);
}
2 changes: 1 addition & 1 deletion frontend/src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export default function RootPublicLayout({
children: React.ReactNode;
}) {
return (
<html lang="en">
<html lang="pt-BR">
<body>{children}</body>
</html>
);
Expand Down
6 changes: 1 addition & 5 deletions frontend/src/app/login/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,5 @@ export default function RootLoginPublicLayout({
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
);
return <>{children}</>;
}
205 changes: 205 additions & 0 deletions frontend/src/components/Chat/ChangeChatPassword.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
import { AuthContext } from "@/contexts/AuthContext";
import { api } from "@/services/apiClient";
import { queryClient } from "@/services/queryClient";
import { Dialog, Transition } from "@headlessui/react";
import { Lock } from "@phosphor-icons/react";
import { Fragment, useContext, useState } from "react";
import { useForm } from "react-hook-form";
import toast from "react-hot-toast";

type ChangeChatPasswordProps = {
chatId: number;
handleHideLock: () => void;
};

export default function ChangeChatPassword({
chatId,
handleHideLock,
}: ChangeChatPasswordProps) {
const [isOpen, setIsOpen] = useState(false);
const [isLoading, setIsLoading] = useState(false);

const {
register,
handleSubmit,
formState: { errors },
} = useForm();

function closeModal() {
setIsOpen(false);
}

function openModal() {
setIsOpen(true);
}

const onSubmit = async (data: any) => {
// create a new form data and append the data, send to api
if (data.password) {
setIsLoading(true);
await api
.patch("/chat/password", {
chatId,
password: data.password,
})
.then(() => {
toast.success("Senha atualizada!");
})
.catch((error) => {
toast.error(
`Erro ao atualizar senha: ${error.response.data.message}`
);
})
.finally(() => {
setIsLoading(false);
setIsOpen(false);
});
}
};

const handleRemovePassword = async () => {
if (window.confirm("Tem certeza que deseja remover a senha do chat?")) {
// Handle password removal here
setIsLoading(true);
await api
.patch("/chat/password", {
chatId,
password: "",
})
.then(() => {
toast.success("Senha removida!");
})
.catch((error) => {
toast.error(`Erro ao remover senha: ${error.response.data.message}`);
})
.finally(() => {
setIsLoading(false);
setIsOpen(false);
handleHideLock();
});
}
};

return (
<>
<Lock
onClick={openModal}
className="cursor-pointer"
color="white"
size={20}
/>

<Transition appear show={isOpen} as={Fragment}>
<Dialog as="div" className="relative z-10" onClose={closeModal}>
<Transition.Child
as={Fragment}
enter="ease-out duration-300"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="ease-in duration-200"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<div className="fixed inset-0 bg-black bg-opacity-25" />
</Transition.Child>

<div className="fixed inset-0 overflow-y-auto">
<div className="flex min-h-full items-center justify-center p-4 text-center">
<Transition.Child
as={Fragment}
enter="ease-out duration-300"
enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
leave="ease-in duration-200"
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95"
>
<Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-2xl bg-black42-200 p-6 text-left align-middle shadow-xl transition-all">
<Dialog.Title
as="h3"
className="text-lg font-medium leading-6 text-white pb-4"
>
Editando senha do chat
</Dialog.Title>
<form onSubmit={handleSubmit(onSubmit)} className="space-y-3">
<div className="flex flex-col space-y-2">
<input
type="text"
className="bg-black42-400 text-white rounded-lg p-2 placeholder-gray-700"
placeholder="Nova senha"
{...register("password", {
required: true,
})}
/>
{errors.password && (
<span className="text-red-600 text-xs">
Campo obrigatório
</span>
)}
</div>
<button
type="submit"
className="bg-purple42-300 text-white rounded-lg p-2 w-full"
disabled={isLoading}
>
{isLoading ? (
<svg
className="animate-spin h-5 w-5 mr-3"
viewBox="0 0 24 24"
>
<circle
className="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
strokeWidth="4"
/>
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
/>
</svg>
) : (
<span>Atualizar</span>
)}
</button>
</form>
<button
type="button"
className="bg-red-400 text-white rounded-lg p-2 w-full mt-4"
onClick={handleRemovePassword}
>
{isLoading ? (
<svg
className="animate-spin h-5 w-5 mr-3"
viewBox="0 0 24 24"
>
<circle
className="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
strokeWidth="4"
/>
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
/>
</svg>
) : (
<span>Remover senha</span>
)}
</button>
</Dialog.Panel>
</Transition.Child>
</div>
</div>
</Dialog>
</Transition>
</>
);
}
Loading
Loading