Ateração na role para que somente o administrador acesse o /connections quando logado

pull/1/head
adriano 2022-01-10 17:10:20 -03:00
parent 605a33751b
commit d687d0900a
21 changed files with 220 additions and 26 deletions

View File

@ -6,6 +6,8 @@ import cors from "cors";
import cookieParser from "cookie-parser";
import * as Sentry from "@sentry/node";
console.log('dddddddddddddddddddddddddddd')
import "./database";
import uploadConfig from "./config/upload";
import AppError from "./errors/AppError";

View File

@ -6,9 +6,13 @@ import ListQueuesService from "../services/QueueService/ListQueuesService";
import ShowQueueService from "../services/QueueService/ShowQueueService";
import UpdateQueueService from "../services/QueueService/UpdateQueueService";
export const index = async (req: Request, res: Response): Promise<Response> => {
const queues = await ListQueuesService();
return res.status(200).json(queues);
};

View File

@ -9,6 +9,8 @@ import UpdateTicketService from "../services/TicketServices/UpdateTicketService"
import SendWhatsAppMessage from "../services/WbotServices/SendWhatsAppMessage";
import ShowWhatsAppService from "../services/WhatsappService/ShowWhatsAppService";
type IndexQuery = {
searchParam: string;
pageNumber: string;
@ -24,7 +26,9 @@ interface TicketData {
status: string;
queueId: number;
userId: number;
}
}
export const index = async (req: Request, res: Response): Promise<Response> => {
const {
@ -37,13 +41,13 @@ export const index = async (req: Request, res: Response): Promise<Response> => {
withUnreadMessages
} = req.query as IndexQuery;
const userId = req.user.id;
const userId = req.user.id;
let queueIds: number[] = [];
if (queueIdsStringified) {
queueIds = JSON.parse(queueIdsStringified);
}
}
const { tickets, count, hasMore } = await ListTicketsService({
searchParam,
@ -55,7 +59,7 @@ export const index = async (req: Request, res: Response): Promise<Response> => {
queueIds,
withUnreadMessages
});
return res.status(200).json({ tickets, count, hasMore });
};
@ -115,7 +119,7 @@ export const remove = async (
res: Response
): Promise<Response> => {
const { ticketId } = req.params;
const ticket = await DeleteTicketService(ticketId);
const io = getIO();

View File

@ -19,8 +19,8 @@ interface WhatsappData {
}
export const index = async (req: Request, res: Response): Promise<Response> => {
const whatsapps = await ListWhatsAppsService();
const whatsapps = await ListWhatsAppsService();
return res.status(200).json(whatsapps);
};
@ -65,7 +65,7 @@ export const show = async (req: Request, res: Response): Promise<Response> => {
const { whatsappId } = req.params;
const whatsapp = await ShowWhatsAppService(whatsappId);
return res.status(200).json(whatsapp);
};

View File

@ -24,6 +24,7 @@ const syncUnreadMessages = async (wbot: Session) => {
});
for (const msg of unreadMessages) {
console.log('--BACKEND MSG: ', msg)
await handleMessage(msg, wbot);
}

View File

@ -13,6 +13,8 @@ import quickAnswerRoutes from "./quickAnswerRoutes";
const routes = Router();
routes.use(userRoutes);
routes.use("/auth", authRoutes);
routes.use(settingRoutes);

View File

@ -5,6 +5,8 @@ import * as SettingController from "../controllers/SettingController";
const settingRoutes = Router();
settingRoutes.get("/settings", isAuth, SettingController.index);
// routes.get("/settings/:settingKey", isAuth, SettingsController.show);

View File

@ -5,6 +5,8 @@ import * as TicketController from "../controllers/TicketController";
const ticketRoutes = express.Router();
ticketRoutes.get("/tickets", isAuth, TicketController.index);
ticketRoutes.get("/tickets/:ticketId", isAuth, TicketController.show);

View File

@ -5,6 +5,8 @@ import * as UserController from "../controllers/UserController";
const userRoutes = Router();
userRoutes.get("/users", isAuth, UserController.index);
userRoutes.post("/users", isAuth, UserController.store);

View File

@ -5,6 +5,8 @@ import * as WhatsAppController from "../controllers/WhatsAppController";
const whatsappRoutes = express.Router();
whatsappRoutes.get("/whatsapp/", isAuth, WhatsAppController.index);
whatsappRoutes.post("/whatsapp/", isAuth, WhatsAppController.store);

View File

@ -5,6 +5,8 @@ import WhatsAppSessionController from "../controllers/WhatsAppSessionController"
const whatsappSessionRoutes = Router();
whatsappSessionRoutes.post(
"/whatsappsession/:whatsappId",
isAuth,

View File

@ -16,9 +16,7 @@ interface Request {
messageData: MessageData;
}
const CreateMessageService = async ({
messageData
}: Request): Promise<Message> => {
const CreateMessageService = async ({messageData}: Request): Promise<Message> => {
await Message.upsert(messageData);
const message = await Message.findByPk(messageData.id, {
@ -41,6 +39,8 @@ const CreateMessageService = async ({
throw new Error("ERR_CREATING_MESSAGE");
}
//console.log('SERVER SIDE MESSAGE: ', message)
const io = getIO();
io.to(message.ticketId.toString())
.to(message.ticket.status)

View File

@ -86,7 +86,7 @@ const verifyMediaMessage = async (
);
} catch (err) {
Sentry.captureException(err);
logger.error(err);
logger.error(`There was an error: wbotMessageLitener.ts: ${err}`);
}
const messageData = {
@ -135,8 +135,11 @@ const verifyQueue = async (
ticket: Ticket,
contact: Contact
) => {
const { queues, greetingMessage } = await ShowWhatsAppService(wbot.id!);
console.log('---greetingMessage: ',greetingMessage)
if (queues.length === 1) {
await UpdateTicketService({
ticketData: { queueId: queues[0].id },
@ -148,7 +151,7 @@ const verifyQueue = async (
const selectedOption = msg.body;
const choosenQueue = queues[+selectedOption - 1];
const choosenQueue = queues[+selectedOption - 1];
if (choosenQueue) {
await UpdateTicketService({
@ -170,6 +173,8 @@ const verifyQueue = async (
const body = `\u200e${greetingMessage}\n${options}`;
console.log('BACKEND BODY TEST: ', body)
const debouncedSentMessage = debounce(
async () => {
const sentMessage = await wbot.sendMessage(
@ -226,7 +231,11 @@ const handleMessage = async (
msgContact = await wbot.getContactById(msg.to);
} else {
msgContact = await msg.getContact();
console.log('---msgContact: ', msgContact, ' | msg.body: ', msg.body)
}
const chat = await msg.getChat();
@ -247,7 +256,8 @@ const handleMessage = async (
const unreadMessages = msg.fromMe ? 0 : chat.unreadCount;
const contact = await verifyContact(msgContact);
const contact = await verifyContact(msgContact);
if ( unreadMessages === 0 && whatsapp.farewellMessage && whatsapp.farewellMessage === msg.body) return;
@ -258,24 +268,33 @@ const handleMessage = async (
groupContact
);
console.log('---passou 1')
if (msg.hasMedia) {
await verifyMediaMessage(msg, ticket, contact);
} else {
await verifyMessage(msg, ticket, contact);
}
console.log('---passou 2 ')
//await verifyQueue(wbot, msg, ticket, contact);
if (
!ticket.queue &&
!chat.isGroup &&
!msg.fromMe &&
!ticket.userId &&
whatsapp.queues.length >= 1
) {
) {
await verifyQueue(wbot, msg, ticket, contact);
}
} catch (err) {
Sentry.captureException(err);
logger.error(`Error handling whatsapp message: Err: ${err}`);

View File

@ -283,6 +283,7 @@ const reducer = (state, action) => {
state[messageIndex] = newMessage;
} else {
state.push(newMessage);
console.log(' TESTANDO NOVA MENSAGEM: ', newMessage)
}
return [...state];
@ -363,6 +364,9 @@ const MessagesList = ({ ticketId, isGroup }) => {
socket.on("appMessage", (data) => {
if (data.action === "create") {
dispatch({ type: "ADD_MESSAGE", payload: data.message });
console.log('* NOVA MENSAGEM CAP: ', data.message)
scrollToBottom();
}
@ -513,6 +517,8 @@ const MessagesList = ({ ticketId, isGroup }) => {
let messageUser = messagesList[index].fromMe;
let previousMessageUser = messagesList[index - 1].fromMe;
if (messageUser !== previousMessageUser) {
return (
<span style={{ marginTop: 16 }} key={`divider-${message.id}`}></span>

View File

@ -7,6 +7,8 @@ const AuthContext = createContext();
const AuthProvider = ({ children }) => {
const { loading, user, isAuth, handleLogin, handleLogout } = useAuth();
//{console.log('authContext teste: ', user)}
return (
<AuthContext.Provider
value={{ loading, user, isAuth, handleLogin, handleLogout }}

View File

@ -41,6 +41,11 @@ import { i18n } from "../../translate/i18n";
import { WhatsAppsContext } from "../../context/WhatsApp/WhatsAppsContext";
import toastError from "../../errors/toastError";
//--------
import { AuthContext } from "../../context/Auth/AuthContext";
import { Can } from "../../components/Can";
const useStyles = makeStyles(theme => ({
mainPaper: {
flex: 1,
@ -93,13 +98,20 @@ const CustomToolTip = ({ title, content, children }) => {
};
const Connections = () => {
//--------
const { user } = useContext(AuthContext);
const classes = useStyles();
const { whatsApps, loading } = useContext(WhatsAppsContext);
const [whatsAppModalOpen, setWhatsAppModalOpen] = useState(false);
const [qrModalOpen, setQrModalOpen] = useState(false);
const [selectedWhatsApp, setSelectedWhatsApp] = useState(null);
const [confirmModalOpen, setConfirmModalOpen] = useState(false);
const [confirmModalOpen, setConfirmModalOpen] = useState(false);
const confirmationModalInitialState = {
action: "",
title: "",
@ -112,7 +124,7 @@ const Connections = () => {
);
const handleStartWhatsAppSession = async whatsAppId => {
try {
try {
await api.post(`/whatsappsession/${whatsAppId}`);
} catch (err) {
toastError(err);
@ -289,8 +301,13 @@ const Connections = () => {
);
};
return (
<MainContainer>
return (
<Can
role={user.profile}
perform="connections-view:show"
yes={() => (
<MainContainer>
<ConfirmationModal
title={confirmModalInfo.title}
open={confirmModalOpen}
@ -394,7 +411,115 @@ const Connections = () => {
</TableBody>
</Table>
</Paper>
</MainContainer>
</MainContainer>
)}
/>
/*<MainContainer>
<ConfirmationModal
title={confirmModalInfo.title}
open={confirmModalOpen}
onClose={setConfirmModalOpen}
onConfirm={handleSubmitConfirmationModal}
>
{confirmModalInfo.message}
</ConfirmationModal>
<QrcodeModal
open={qrModalOpen}
onClose={handleCloseQrModal}
whatsAppId={!whatsAppModalOpen && selectedWhatsApp?.id}
/>
<WhatsAppModal
open={whatsAppModalOpen}
onClose={handleCloseWhatsAppModal}
whatsAppId={!qrModalOpen && selectedWhatsApp?.id}
/>
<MainHeader>
<Title>{i18n.t("connections.title")}</Title>
<MainHeaderButtonsWrapper>
<Button
variant="contained"
color="primary"
onClick={handleOpenWhatsAppModal}
>
{i18n.t("connections.buttons.add")}
</Button>
</MainHeaderButtonsWrapper>
</MainHeader>
<Paper className={classes.mainPaper} variant="outlined">
<Table size="small">
<TableHead>
<TableRow>
<TableCell align="center">
{i18n.t("connections.table.name")}
</TableCell>
<TableCell align="center">
{i18n.t("connections.table.status")}
</TableCell>
<TableCell align="center">
{i18n.t("connections.table.session")}
</TableCell>
<TableCell align="center">
{i18n.t("connections.table.lastUpdate")}
</TableCell>
<TableCell align="center">
{i18n.t("connections.table.default")}
</TableCell>
<TableCell align="center">
{i18n.t("connections.table.actions")}
</TableCell>
</TableRow>
</TableHead>
<TableBody>
{loading ? (
<TableRowSkeleton />
) : (
<>
{whatsApps?.length > 0 &&
whatsApps.map(whatsApp => (
<TableRow key={whatsApp.id}>
<TableCell align="center">{whatsApp.name}</TableCell>
<TableCell align="center">
{renderStatusToolTips(whatsApp)}
</TableCell>
<TableCell align="center">
{renderActionButtons(whatsApp)}
</TableCell>
<TableCell align="center">
{format(parseISO(whatsApp.updatedAt), "dd/MM/yy HH:mm")}
</TableCell>
<TableCell align="center">
{whatsApp.isDefault && (
<div className={classes.customTableCell}>
<CheckCircle style={{ color: green[500] }} />
</div>
)}
</TableCell>
<TableCell align="center">
<IconButton
size="small"
onClick={() => handleEditWhatsApp(whatsApp)}
>
<Edit />
</IconButton>
<IconButton
size="small"
onClick={e => {
handleOpenConfirmationModal("delete", whatsApp.id);
}}
>
<DeleteOutline />
</IconButton>
</TableCell>
</TableRow>
))}
</>
)}
</TableBody>
</Table>
</Paper>
</MainContainer>*/
);
};

View File

@ -92,7 +92,7 @@ const Contacts = () => {
const classes = useStyles();
const history = useHistory();
const { user } = useContext(AuthContext);
const { user } = useContext(AuthContext);
const [loading, setLoading] = useState(false);
const [pageNumber, setPageNumber] = useState(1);

View File

@ -133,6 +133,7 @@ const Login = () => {
</Button>
<Grid container>
<Grid item>
<Link
href="#"
variant="body2"
@ -141,6 +142,7 @@ const Login = () => {
>
{i18n.t("login.buttons.register")}
</Link>
</Grid>
</Grid>
</form>

View File

@ -219,13 +219,15 @@ const Users = () => {
),
}}
/>
<Button
<Button
variant="contained"
color="primary"
onClick={handleOpenUserModal}
>
{i18n.t("users.buttons.add")}
</Button>
</Button>
</MainHeaderButtonsWrapper>
</MainHeader>
<Paper
@ -243,9 +245,11 @@ const Users = () => {
<TableCell align="center">
{i18n.t("users.table.profile")}
</TableCell>
<TableCell align="center">
{i18n.t("users.table.actions")}
</TableCell>
</TableRow>
</TableHead>
<TableBody>
@ -255,7 +259,9 @@ const Users = () => {
<TableCell align="center">{user.name}</TableCell>
<TableCell align="center">{user.email}</TableCell>
<TableCell align="center">{user.profile}</TableCell>
<TableCell align="center">
<IconButton
size="small"
onClick={() => handleEditUser(user)}
@ -263,7 +269,7 @@ const Users = () => {
<EditIcon />
</IconButton>
<IconButton
<IconButton
size="small"
onClick={(e) => {
setConfirmModalOpen(true);
@ -271,8 +277,10 @@ const Users = () => {
}}
>
<DeleteOutlineIcon />
</IconButton>
</IconButton>
</TableCell>
</TableRow>
))}
{loading && <TableRowSkeleton columns={4} />}

View File

@ -16,6 +16,11 @@ import Queues from "../pages/Queues/";
import { AuthProvider } from "../context/Auth/AuthContext";
import { WhatsAppsProvider } from "../context/WhatsApp/WhatsAppsContext";
import Route from "./Route";
//console.log('---AuthProvider: ',AuthProvider)
const Routes = () => {
return (
@ -33,12 +38,14 @@ const Routes = () => {
component={Tickets}
isPrivate
/>
<Route
<Route
exact
path="/connections"
component={Connections}
isPrivate
/>
<Route exact path="/contacts" component={Contacts} isPrivate />
<Route exact path="/users" component={Users} isPrivate />
<Route

View File

@ -11,6 +11,8 @@ const rules = {
"user-modal:editQueues",
"ticket-options:deleteTicket",
"contacts-page:deleteContact",
"connections-view:show",
],
},
};