mirror of
https://github.com/cheveguerra/whaticket-community.git
synced 2026-04-17 19:37:02 +00:00
improvement: moved user data from localstorage to context
This commit is contained in:
@@ -8,7 +8,7 @@ import { RefreshTokenService } from "../services/AuthServices/RefreshTokenServic
|
||||
export const store = async (req: Request, res: Response): Promise<Response> => {
|
||||
const { email, password } = req.body;
|
||||
|
||||
const { token, user, refreshToken } = await AuthUserService({
|
||||
const { token, serializedUser, refreshToken } = await AuthUserService({
|
||||
email,
|
||||
password
|
||||
});
|
||||
@@ -17,9 +17,7 @@ export const store = async (req: Request, res: Response): Promise<Response> => {
|
||||
|
||||
return res.status(200).json({
|
||||
token,
|
||||
username: user.name,
|
||||
profile: user.profile,
|
||||
userId: user.id
|
||||
user: serializedUser
|
||||
});
|
||||
};
|
||||
|
||||
@@ -33,9 +31,9 @@ export const update = async (
|
||||
throw new AppError("ERR_SESSION_EXPIRED", 401);
|
||||
}
|
||||
|
||||
const { newToken, refreshToken } = await RefreshTokenService(token);
|
||||
const { user, newToken, refreshToken } = await RefreshTokenService(token);
|
||||
|
||||
SendRefreshToken(res, refreshToken);
|
||||
|
||||
return res.json({ token: newToken });
|
||||
return res.json({ token: newToken, user });
|
||||
};
|
||||
|
||||
20
backend/src/helpers/SerializeUser.ts
Normal file
20
backend/src/helpers/SerializeUser.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import Queue from "../models/Queue";
|
||||
import User from "../models/User";
|
||||
|
||||
interface SerializedUser {
|
||||
id: number;
|
||||
name: string;
|
||||
email: string;
|
||||
profile: string;
|
||||
queues: Queue[];
|
||||
}
|
||||
|
||||
export const SerializeUser = (user: User): SerializedUser => {
|
||||
return {
|
||||
id: user.id,
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
profile: user.profile,
|
||||
queues: user.queues
|
||||
};
|
||||
};
|
||||
@@ -1,4 +1,6 @@
|
||||
import { verify } from "jsonwebtoken";
|
||||
|
||||
import User from "../../models/User";
|
||||
import AppError from "../../errors/AppError";
|
||||
import ShowUserService from "../UserServices/ShowUserService";
|
||||
import authConfig from "../../config/auth";
|
||||
@@ -13,6 +15,7 @@ interface RefreshTokenPayload {
|
||||
}
|
||||
|
||||
interface Response {
|
||||
user: User;
|
||||
newToken: string;
|
||||
refreshToken: string;
|
||||
}
|
||||
@@ -37,5 +40,5 @@ export const RefreshTokenService = async (token: string): Promise<Response> => {
|
||||
const newToken = createAccessToken(user);
|
||||
const refreshToken = createRefreshToken(user);
|
||||
|
||||
return { newToken, refreshToken };
|
||||
return { user, newToken, refreshToken };
|
||||
};
|
||||
|
||||
@@ -4,6 +4,16 @@ import {
|
||||
createAccessToken,
|
||||
createRefreshToken
|
||||
} from "../../helpers/CreateTokens";
|
||||
import { SerializeUser } from "../../helpers/SerializeUser";
|
||||
import Queue from "../../models/Queue";
|
||||
|
||||
interface SerializedUser {
|
||||
id: number;
|
||||
name: string;
|
||||
email: string;
|
||||
profile: string;
|
||||
queues: Queue[];
|
||||
}
|
||||
|
||||
interface Request {
|
||||
email: string;
|
||||
@@ -11,7 +21,7 @@ interface Request {
|
||||
}
|
||||
|
||||
interface Response {
|
||||
user: User;
|
||||
serializedUser: SerializedUser;
|
||||
token: string;
|
||||
refreshToken: string;
|
||||
}
|
||||
@@ -21,7 +31,8 @@ const AuthUserService = async ({
|
||||
password
|
||||
}: Request): Promise<Response> => {
|
||||
const user = await User.findOne({
|
||||
where: { email }
|
||||
where: { email },
|
||||
include: ["queues"]
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
@@ -35,8 +46,10 @@ const AuthUserService = async ({
|
||||
const token = createAccessToken(user);
|
||||
const refreshToken = createRefreshToken(user);
|
||||
|
||||
const serializedUser = SerializeUser(user);
|
||||
|
||||
return {
|
||||
user,
|
||||
serializedUser,
|
||||
token,
|
||||
refreshToken
|
||||
};
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import * as Yup from "yup";
|
||||
|
||||
import AppError from "../../errors/AppError";
|
||||
import { SerializeUser } from "../../helpers/SerializeUser";
|
||||
import User from "../../models/User";
|
||||
|
||||
interface Request {
|
||||
@@ -63,13 +64,7 @@ const CreateUserService = async ({
|
||||
|
||||
await user.reload();
|
||||
|
||||
const serializedUser = {
|
||||
id: user.id,
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
profile: user.profile,
|
||||
queues: user.queues
|
||||
};
|
||||
const serializedUser = SerializeUser(user);
|
||||
|
||||
return serializedUser;
|
||||
};
|
||||
|
||||
11
frontend/src/accessRules.js
Normal file
11
frontend/src/accessRules.js
Normal file
@@ -0,0 +1,11 @@
|
||||
const rules = {
|
||||
user: {
|
||||
static: [],
|
||||
},
|
||||
|
||||
admin: {
|
||||
static: ["drawer-admin-items:view"],
|
||||
},
|
||||
};
|
||||
|
||||
export default rules;
|
||||
39
frontend/src/components/Can/index.js
Normal file
39
frontend/src/components/Can/index.js
Normal file
@@ -0,0 +1,39 @@
|
||||
import rules from "../../accessRules";
|
||||
|
||||
const check = (rules, role, action, data) => {
|
||||
const permissions = rules[role];
|
||||
if (!permissions) {
|
||||
// role is not present in the rules
|
||||
return false;
|
||||
}
|
||||
|
||||
const staticPermissions = permissions.static;
|
||||
|
||||
if (staticPermissions && staticPermissions.includes(action)) {
|
||||
// static rule not provided for action
|
||||
return true;
|
||||
}
|
||||
|
||||
const dynamicPermissions = permissions.dynamic;
|
||||
|
||||
if (dynamicPermissions) {
|
||||
const permissionCondition = dynamicPermissions[action];
|
||||
if (!permissionCondition) {
|
||||
// dynamic rule not provided for action
|
||||
return false;
|
||||
}
|
||||
|
||||
return permissionCondition(data);
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const Can = ({ role, perform, data, yes, no }) =>
|
||||
check(rules, role, perform, data) ? yes() : no();
|
||||
|
||||
Can.defaultProps = {
|
||||
yes: () => null,
|
||||
no: () => null,
|
||||
};
|
||||
|
||||
export default Can;
|
||||
@@ -25,6 +25,8 @@ import { i18n } from "../../translate/i18n";
|
||||
import api from "../../services/api";
|
||||
import RecordingTimer from "./RecordingTimer";
|
||||
import { ReplyMessageContext } from "../../context/ReplyingMessage/ReplyingMessageContext";
|
||||
import { AuthContext } from "../../context/Auth/AuthContext";
|
||||
import { useLocalStorage } from "../../hooks/useLocalStorage";
|
||||
import toastError from "../../errors/toastError";
|
||||
|
||||
const Mp3Recorder = new MicRecorder({ bitRate: 128 });
|
||||
@@ -164,7 +166,6 @@ const useStyles = makeStyles(theme => ({
|
||||
const MessageInput = ({ ticketStatus }) => {
|
||||
const classes = useStyles();
|
||||
const { ticketId } = useParams();
|
||||
const username = localStorage.getItem("username");
|
||||
|
||||
const [medias, setMedias] = useState([]);
|
||||
const [inputMessage, setInputMessage] = useState("");
|
||||
@@ -175,17 +176,9 @@ const MessageInput = ({ ticketStatus }) => {
|
||||
const { setReplyingMessage, replyingMessage } = useContext(
|
||||
ReplyMessageContext
|
||||
);
|
||||
const { user } = useContext(AuthContext);
|
||||
|
||||
const [signMessage, setSignMessage] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const storedSignOption = localStorage.getItem("signOption");
|
||||
if (storedSignOption === "true") setSignMessage(true);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
localStorage.setItem("signOption", signMessage);
|
||||
}, [signMessage]);
|
||||
const [signMessage, setSignMessage] = useLocalStorage("signOption", true);
|
||||
|
||||
useEffect(() => {
|
||||
inputRef.current.focus();
|
||||
@@ -255,7 +248,7 @@ const MessageInput = ({ ticketStatus }) => {
|
||||
fromMe: true,
|
||||
mediaUrl: "",
|
||||
body: signMessage
|
||||
? `*${username}:*\n${inputMessage.trim()}`
|
||||
? `*${user?.name}:*\n${inputMessage.trim()}`
|
||||
: inputMessage.trim(),
|
||||
quotedMsg: replyingMessage,
|
||||
};
|
||||
@@ -279,7 +272,7 @@ const MessageInput = ({ ticketStatus }) => {
|
||||
setRecording(true);
|
||||
setLoading(false);
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
toastError(err);
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
@@ -314,7 +307,7 @@ const MessageInput = ({ ticketStatus }) => {
|
||||
await Mp3Recorder.stop().getMp3();
|
||||
setRecording(false);
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
toastError(err);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -428,8 +421,8 @@ const MessageInput = ({ ticketStatus }) => {
|
||||
<Switch
|
||||
size="small"
|
||||
checked={signMessage}
|
||||
onChange={() => {
|
||||
setSignMessage(prevState => !prevState);
|
||||
onChange={e => {
|
||||
setSignMessage(e.target.checked);
|
||||
}}
|
||||
name="showAllTickets"
|
||||
color="primary"
|
||||
|
||||
@@ -301,7 +301,7 @@ const reducer = (state, action) => {
|
||||
}
|
||||
};
|
||||
|
||||
const MessagesList = ({ ticketId, isGroup, setReplyingMessage }) => {
|
||||
const MessagesList = ({ ticketId, isGroup }) => {
|
||||
const classes = useStyles();
|
||||
|
||||
const [messagesList, dispatch] = useReducer(reducer, []);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useState, useEffect } from "react";
|
||||
import React, { useState, useEffect, useContext } from "react";
|
||||
import { useHistory } from "react-router-dom";
|
||||
|
||||
import Button from "@material-ui/core/Button";
|
||||
@@ -18,6 +18,7 @@ import api from "../../services/api";
|
||||
import ButtonWithSpinner from "../ButtonWithSpinner";
|
||||
import ContactModal from "../ContactModal";
|
||||
import toastError from "../../errors/toastError";
|
||||
import { AuthContext } from "../../context/Auth/AuthContext";
|
||||
|
||||
const filter = createFilterOptions({
|
||||
trim: true,
|
||||
@@ -25,7 +26,6 @@ const filter = createFilterOptions({
|
||||
|
||||
const NewTicketModal = ({ modalOpen, onClose }) => {
|
||||
const history = useHistory();
|
||||
const userId = +localStorage.getItem("userId");
|
||||
|
||||
const [options, setOptions] = useState([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
@@ -33,6 +33,7 @@ const NewTicketModal = ({ modalOpen, onClose }) => {
|
||||
const [selectedContact, setSelectedContact] = useState(null);
|
||||
const [newContact, setNewContact] = useState({});
|
||||
const [contactModalOpen, setContactModalOpen] = useState(false);
|
||||
const { user } = useContext(AuthContext);
|
||||
|
||||
useEffect(() => {
|
||||
if (!modalOpen || searchParam.length < 3) {
|
||||
@@ -71,7 +72,7 @@ const NewTicketModal = ({ modalOpen, onClose }) => {
|
||||
try {
|
||||
const { data: ticket } = await api.post("/tickets", {
|
||||
contactId: contactId,
|
||||
userId: userId,
|
||||
userId: user.id,
|
||||
status: "open",
|
||||
});
|
||||
history.push(`/tickets/${ticket.id}`);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useState, useRef, useEffect } from "react";
|
||||
import React, { useState, useRef, useEffect, useContext } from "react";
|
||||
|
||||
import { useHistory } from "react-router-dom";
|
||||
import { format } from "date-fns";
|
||||
@@ -18,6 +18,7 @@ import TicketListItem from "../TicketListItem";
|
||||
import { i18n } from "../../translate/i18n";
|
||||
import useTickets from "../../hooks/useTickets";
|
||||
import alertSound from "../../assets/sound.mp3";
|
||||
import { AuthContext } from "../../context/Auth/AuthContext";
|
||||
|
||||
const useStyles = makeStyles(theme => ({
|
||||
tabContainer: {
|
||||
@@ -43,7 +44,7 @@ const NotificationsPopOver = () => {
|
||||
const classes = useStyles();
|
||||
|
||||
const history = useHistory();
|
||||
const userId = +localStorage.getItem("userId");
|
||||
const { user } = useContext(AuthContext);
|
||||
const ticketIdUrl = +history.location.pathname.split("/")[2];
|
||||
const ticketIdRef = useRef(ticketIdUrl);
|
||||
const anchorEl = useRef();
|
||||
@@ -108,7 +109,7 @@ const NotificationsPopOver = () => {
|
||||
if (
|
||||
data.action === "create" &&
|
||||
!data.message.read &&
|
||||
(data.ticket.userId === userId || !data.ticket.userId)
|
||||
(data.ticket.userId === user?.id || !data.ticket.userId)
|
||||
) {
|
||||
setNotifications(prevState => {
|
||||
const ticketIndex = prevState.findIndex(t => t.id === data.ticket.id);
|
||||
@@ -122,7 +123,7 @@ const NotificationsPopOver = () => {
|
||||
const shouldNotNotificate =
|
||||
(data.message.ticketId === ticketIdRef.current &&
|
||||
document.visibilityState === "visible") ||
|
||||
(data.ticket.userId && data.ticket.userId !== userId) ||
|
||||
(data.ticket.userId && data.ticket.userId !== user?.id) ||
|
||||
data.ticket.isGroup;
|
||||
|
||||
if (shouldNotNotificate) return;
|
||||
@@ -134,7 +135,7 @@ const NotificationsPopOver = () => {
|
||||
return () => {
|
||||
socket.disconnect();
|
||||
};
|
||||
}, [history, userId]);
|
||||
}, [history, user]);
|
||||
|
||||
const handleNotifications = (data, history) => {
|
||||
const { message, contact, ticket } = data;
|
||||
|
||||
@@ -41,7 +41,7 @@ const QueueSelector = ({ selectedQueueIds, onChange }) => {
|
||||
|
||||
return (
|
||||
<div style={{ marginTop: 6 }}>
|
||||
<FormControl fullWidth variant="outlined">
|
||||
<FormControl fullWidth margin="dense" variant="outlined">
|
||||
<InputLabel>Filas</InputLabel>
|
||||
<Select
|
||||
multiple
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useState } from "react";
|
||||
import React, { useContext, useState } from "react";
|
||||
import { useHistory } from "react-router-dom";
|
||||
|
||||
import { makeStyles } from "@material-ui/core/styles";
|
||||
@@ -10,6 +10,7 @@ import api from "../../services/api";
|
||||
import TicketOptionsMenu from "../TicketOptionsMenu";
|
||||
import ButtonWithSpinner from "../ButtonWithSpinner";
|
||||
import toastError from "../../errors/toastError";
|
||||
import { AuthContext } from "../../context/Auth/AuthContext";
|
||||
|
||||
const useStyles = makeStyles(theme => ({
|
||||
actionButtons: {
|
||||
@@ -26,10 +27,10 @@ const useStyles = makeStyles(theme => ({
|
||||
const TicketActionButtons = ({ ticket }) => {
|
||||
const classes = useStyles();
|
||||
const history = useHistory();
|
||||
const userId = +localStorage.getItem("userId");
|
||||
const [anchorEl, setAnchorEl] = useState(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const ticketOptionsMenuOpen = Boolean(anchorEl);
|
||||
const { user } = useContext(AuthContext);
|
||||
|
||||
const handleOpenTicketOptionsMenu = e => {
|
||||
setAnchorEl(e.currentTarget);
|
||||
@@ -66,7 +67,7 @@ const TicketActionButtons = ({ ticket }) => {
|
||||
loading={loading}
|
||||
startIcon={<Replay />}
|
||||
size="small"
|
||||
onClick={e => handleUpdateTicketStatus(e, "open", userId)}
|
||||
onClick={e => handleUpdateTicketStatus(e, "open", user?.id)}
|
||||
>
|
||||
{i18n.t("messagesList.header.buttons.reopen")}
|
||||
</ButtonWithSpinner>
|
||||
@@ -86,7 +87,7 @@ const TicketActionButtons = ({ ticket }) => {
|
||||
size="small"
|
||||
variant="contained"
|
||||
color="primary"
|
||||
onClick={e => handleUpdateTicketStatus(e, "closed", userId)}
|
||||
onClick={e => handleUpdateTicketStatus(e, "closed", user?.id)}
|
||||
>
|
||||
{i18n.t("messagesList.header.buttons.resolve")}
|
||||
</ButtonWithSpinner>
|
||||
@@ -107,7 +108,7 @@ const TicketActionButtons = ({ ticket }) => {
|
||||
size="small"
|
||||
variant="contained"
|
||||
color="primary"
|
||||
onClick={e => handleUpdateTicketStatus(e, "open", userId)}
|
||||
onClick={e => handleUpdateTicketStatus(e, "open", user?.id)}
|
||||
>
|
||||
{i18n.t("messagesList.header.buttons.accept")}
|
||||
</ButtonWithSpinner>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useState, useEffect, useRef } from "react";
|
||||
import React, { useState, useEffect, useRef, useContext } from "react";
|
||||
|
||||
import { useHistory, useParams } from "react-router-dom";
|
||||
import { parseISO, format, isSameDay } from "date-fns";
|
||||
@@ -20,6 +20,7 @@ import api from "../../services/api";
|
||||
import ButtonWithSpinner from "../ButtonWithSpinner";
|
||||
import MarkdownWrapper from "../MarkdownWrapper";
|
||||
import { Tooltip } from "@material-ui/core";
|
||||
import { AuthContext } from "../../context/Auth/AuthContext";
|
||||
|
||||
const useStyles = makeStyles(theme => ({
|
||||
ticket: {
|
||||
@@ -102,10 +103,10 @@ const useStyles = makeStyles(theme => ({
|
||||
const TicketListItem = ({ ticket }) => {
|
||||
const classes = useStyles();
|
||||
const history = useHistory();
|
||||
const userId = +localStorage.getItem("userId");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const { ticketId } = useParams();
|
||||
const isMounted = useRef(true);
|
||||
const { user } = useContext(AuthContext);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
@@ -118,7 +119,7 @@ const TicketListItem = ({ ticket }) => {
|
||||
try {
|
||||
await api.put(`/tickets/${ticketId}`, {
|
||||
status: "open",
|
||||
userId: userId,
|
||||
userId: user?.id,
|
||||
});
|
||||
} catch (err) {
|
||||
setLoading(false);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useState, useEffect, useReducer } from "react";
|
||||
import React, { useState, useEffect, useReducer, useContext } from "react";
|
||||
import openSocket from "socket.io-client";
|
||||
|
||||
import { makeStyles } from "@material-ui/core/styles";
|
||||
@@ -10,6 +10,7 @@ import TicketsListSkeleton from "../TicketsListSkeleton";
|
||||
import useTickets from "../../hooks/useTickets";
|
||||
import { i18n } from "../../translate/i18n";
|
||||
import { ListSubheader } from "@material-ui/core";
|
||||
import { AuthContext } from "../../context/Auth/AuthContext";
|
||||
|
||||
const useStyles = makeStyles(theme => ({
|
||||
ticketsListWrapper: {
|
||||
@@ -149,10 +150,10 @@ const reducer = (state, action) => {
|
||||
};
|
||||
|
||||
const TicketsList = ({ status, searchParam, showAll }) => {
|
||||
const userId = +localStorage.getItem("userId");
|
||||
const classes = useStyles();
|
||||
const [pageNumber, setPageNumber] = useState(1);
|
||||
const [ticketsList, dispatch] = useReducer(reducer, []);
|
||||
const { user } = useContext(AuthContext);
|
||||
|
||||
useEffect(() => {
|
||||
dispatch({ type: "RESET" });
|
||||
@@ -194,7 +195,7 @@ const TicketsList = ({ status, searchParam, showAll }) => {
|
||||
|
||||
if (
|
||||
(data.action === "updateStatus" || data.action === "create") &&
|
||||
(!data.ticket.userId || data.ticket.userId === userId || showAll)
|
||||
(!data.ticket.userId || data.ticket.userId === user?.id || showAll)
|
||||
) {
|
||||
dispatch({
|
||||
type: "UPDATE_TICKET",
|
||||
@@ -210,7 +211,7 @@ const TicketsList = ({ status, searchParam, showAll }) => {
|
||||
socket.on("appMessage", data => {
|
||||
if (
|
||||
data.action === "create" &&
|
||||
(!data.ticket.userId || data.ticket.userId === userId || showAll)
|
||||
(!data.ticket.userId || data.ticket.userId === user?.id || showAll)
|
||||
) {
|
||||
dispatch({
|
||||
type: "UPDATE_TICKET_MESSAGES_COUNT",
|
||||
@@ -234,7 +235,7 @@ const TicketsList = ({ status, searchParam, showAll }) => {
|
||||
return () => {
|
||||
socket.disconnect();
|
||||
};
|
||||
}, [status, showAll, userId, searchParam]);
|
||||
}, [status, showAll, user, searchParam]);
|
||||
|
||||
const loadMore = () => {
|
||||
setPageNumber(prevState => prevState + 1);
|
||||
|
||||
@@ -175,13 +175,13 @@ const TicketsManager = () => {
|
||||
</Paper>
|
||||
<TabPanel value={tab} name="open" className={classes.ticketsWrapper}>
|
||||
<TicketsList status="open" showAll={showAllTickets} />
|
||||
<TicketsList status="pending" showAll={true} />
|
||||
<TicketsList status="pending" />
|
||||
</TabPanel>
|
||||
<TabPanel value={tab} name="closed" className={classes.ticketsWrapper}>
|
||||
<TicketsList status="closed" showAll={true} />
|
||||
<TicketsList status="closed" showAll={showAllTickets} />
|
||||
</TabPanel>
|
||||
<TabPanel value={tab} name="search" className={classes.ticketsWrapper}>
|
||||
<TicketsList searchParam={searchParam} showAll={true} />
|
||||
<TicketsList searchParam={searchParam} showAll={showAllTickets} />
|
||||
</TabPanel>
|
||||
</Paper>
|
||||
);
|
||||
|
||||
@@ -5,11 +5,11 @@ import useAuth from "./useAuth";
|
||||
const AuthContext = createContext();
|
||||
|
||||
const AuthProvider = ({ children }) => {
|
||||
const { isAuth, loading, handleLogin, handleLogout } = useAuth();
|
||||
const { loading, user, isAuth, handleLogin, handleLogout } = useAuth();
|
||||
|
||||
return (
|
||||
<AuthContext.Provider
|
||||
value={{ loading, isAuth, handleLogin, handleLogout }}
|
||||
value={{ loading, user, isAuth, handleLogin, handleLogout }}
|
||||
>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
|
||||
@@ -6,11 +6,13 @@ import { toast } from "react-toastify";
|
||||
import { i18n } from "../../translate/i18n";
|
||||
import api from "../../services/api";
|
||||
import toastError from "../../errors/toastError";
|
||||
// import { useLocalStorage } from "../../hooks/useLocalStorage";
|
||||
|
||||
const useAuth = () => {
|
||||
const history = useHistory();
|
||||
const [isAuth, setIsAuth] = useState(false);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [user, setUser] = useState({});
|
||||
|
||||
api.interceptors.request.use(
|
||||
config => {
|
||||
@@ -44,9 +46,6 @@ const useAuth = () => {
|
||||
}
|
||||
if (error?.response?.status === 401) {
|
||||
localStorage.removeItem("token");
|
||||
localStorage.removeItem("username");
|
||||
localStorage.removeItem("profile");
|
||||
localStorage.removeItem("userId");
|
||||
api.defaults.headers.Authorization = undefined;
|
||||
setIsAuth(false);
|
||||
}
|
||||
@@ -56,11 +55,15 @@ const useAuth = () => {
|
||||
|
||||
useEffect(() => {
|
||||
const token = localStorage.getItem("token");
|
||||
if (token) {
|
||||
api.defaults.headers.Authorization = `Bearer ${JSON.parse(token)}`;
|
||||
setIsAuth(true);
|
||||
}
|
||||
setLoading(false);
|
||||
(async () => {
|
||||
if (token) {
|
||||
const { data } = await api.post("/auth/refresh_token");
|
||||
api.defaults.headers.Authorization = `Bearer ${JSON.parse(token)}`;
|
||||
setIsAuth(true);
|
||||
setUser(data.user);
|
||||
}
|
||||
setLoading(false);
|
||||
})();
|
||||
}, []);
|
||||
|
||||
const handleLogin = async user => {
|
||||
@@ -69,11 +72,8 @@ const useAuth = () => {
|
||||
try {
|
||||
const { data } = await api.post("/auth/login", user);
|
||||
localStorage.setItem("token", JSON.stringify(data.token));
|
||||
localStorage.setItem("username", data.username);
|
||||
localStorage.setItem("profile", data.profile);
|
||||
localStorage.setItem("userId", data.userId);
|
||||
api.defaults.headers.Authorization = `Bearer ${data.token}`;
|
||||
|
||||
setUser(data.user);
|
||||
setIsAuth(true);
|
||||
toast.success(i18n.t("auth.toasts.success"));
|
||||
history.push("/tickets");
|
||||
@@ -84,20 +84,17 @@ const useAuth = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const handleLogout = e => {
|
||||
const handleLogout = () => {
|
||||
setLoading(true);
|
||||
e.preventDefault();
|
||||
setIsAuth(false);
|
||||
setUser({});
|
||||
localStorage.removeItem("token");
|
||||
localStorage.removeItem("username");
|
||||
localStorage.removeItem("profile");
|
||||
localStorage.removeItem("userId");
|
||||
api.defaults.headers.Authorization = undefined;
|
||||
setLoading(false);
|
||||
history.push("/login");
|
||||
};
|
||||
|
||||
return { isAuth, setIsAuth, loading, handleLogin, handleLogout };
|
||||
return { isAuth, user, setUser, loading, handleLogin, handleLogout };
|
||||
};
|
||||
|
||||
export default useAuth;
|
||||
|
||||
29
frontend/src/hooks/useLocalStorage/index.js
Normal file
29
frontend/src/hooks/useLocalStorage/index.js
Normal file
@@ -0,0 +1,29 @@
|
||||
import { useState } from "react";
|
||||
import toastError from "../../errors/toastError";
|
||||
|
||||
export function useLocalStorage(key, initialValue) {
|
||||
const [storedValue, setStoredValue] = useState(() => {
|
||||
try {
|
||||
const item = localStorage.getItem(key);
|
||||
return item ? JSON.parse(item) : initialValue;
|
||||
} catch (error) {
|
||||
toastError(error);
|
||||
return initialValue;
|
||||
}
|
||||
});
|
||||
|
||||
const setValue = value => {
|
||||
try {
|
||||
const valueToStore =
|
||||
value instanceof Function ? value(storedValue) : value;
|
||||
|
||||
setStoredValue(valueToStore);
|
||||
|
||||
localStorage.setItem(key, JSON.stringify(valueToStore));
|
||||
} catch (error) {
|
||||
toastError(error);
|
||||
}
|
||||
};
|
||||
|
||||
return [storedValue, setValue];
|
||||
}
|
||||
@@ -17,6 +17,8 @@ import AccountTreeOutlinedIcon from "@material-ui/icons/AccountTreeOutlined";
|
||||
|
||||
import { i18n } from "../translate/i18n";
|
||||
import { WhatsAppsContext } from "../context/WhatsApp/WhatsAppsContext";
|
||||
import { AuthContext } from "../context/Auth/AuthContext";
|
||||
import Can from "../components/Can";
|
||||
|
||||
function ListItemLink(props) {
|
||||
const { icon, primary, to, className } = props;
|
||||
@@ -40,8 +42,8 @@ function ListItemLink(props) {
|
||||
}
|
||||
|
||||
const MainListItems = () => {
|
||||
const userProfile = localStorage.getItem("profile");
|
||||
const { whatsApps } = useContext(WhatsAppsContext);
|
||||
const { user } = useContext(AuthContext);
|
||||
const [connectionWarning, setConnectionWarning] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -95,29 +97,33 @@ const MainListItems = () => {
|
||||
primary={i18n.t("mainDrawer.listItems.contacts")}
|
||||
icon={<ContactPhoneOutlinedIcon />}
|
||||
/>
|
||||
{userProfile === "admin" && (
|
||||
<>
|
||||
<Divider />
|
||||
<ListSubheader inset>
|
||||
{i18n.t("mainDrawer.listItems.administration")}
|
||||
</ListSubheader>
|
||||
<ListItemLink
|
||||
to="/users"
|
||||
primary={i18n.t("mainDrawer.listItems.users")}
|
||||
icon={<PeopleAltOutlinedIcon />}
|
||||
/>
|
||||
<ListItemLink
|
||||
to="/queues"
|
||||
primary={i18n.t("mainDrawer.listItems.queues")}
|
||||
icon={<AccountTreeOutlinedIcon />}
|
||||
/>
|
||||
<ListItemLink
|
||||
to="/settings"
|
||||
primary={i18n.t("mainDrawer.listItems.settings")}
|
||||
icon={<SettingsOutlinedIcon />}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
<Can
|
||||
role={user.profile}
|
||||
perform="drawer-admin-items:view"
|
||||
yes={() => (
|
||||
<>
|
||||
<Divider />
|
||||
<ListSubheader inset>
|
||||
{i18n.t("mainDrawer.listItems.administration")}
|
||||
</ListSubheader>
|
||||
<ListItemLink
|
||||
to="/users"
|
||||
primary={i18n.t("mainDrawer.listItems.users")}
|
||||
icon={<PeopleAltOutlinedIcon />}
|
||||
/>
|
||||
<ListItemLink
|
||||
to="/queues"
|
||||
primary={i18n.t("mainDrawer.listItems.queues")}
|
||||
icon={<AccountTreeOutlinedIcon />}
|
||||
/>
|
||||
<ListItemLink
|
||||
to="/settings"
|
||||
primary={i18n.t("mainDrawer.listItems.settings")}
|
||||
icon={<SettingsOutlinedIcon />}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useState, useContext, useEffect } from "react";
|
||||
import React, { useState, useContext } from "react";
|
||||
import clsx from "clsx";
|
||||
|
||||
import {
|
||||
@@ -24,6 +24,7 @@ import UserModal from "../components/UserModal";
|
||||
import { AuthContext } from "../context/Auth/AuthContext";
|
||||
import BackdropLoading from "../components/BackdropLoading";
|
||||
import { i18n } from "../translate/i18n";
|
||||
import { useLocalStorage } from "../hooks/useLocalStorage";
|
||||
|
||||
const drawerWidth = 240;
|
||||
|
||||
@@ -107,30 +108,13 @@ const useStyles = makeStyles(theme => ({
|
||||
}));
|
||||
|
||||
const LoggedInLayout = ({ children }) => {
|
||||
const drawerState = localStorage.getItem("drawerOpen");
|
||||
const userId = +localStorage.getItem("userId");
|
||||
const classes = useStyles();
|
||||
const [open, setOpen] = useState(true);
|
||||
const [userModalOpen, setUserModalOpen] = useState(false);
|
||||
const [anchorEl, setAnchorEl] = useState(null);
|
||||
const [menuOpen, setMenuOpen] = useState(false);
|
||||
const { handleLogout, loading } = useContext(AuthContext);
|
||||
|
||||
useEffect(() => {
|
||||
if (drawerState === "0") {
|
||||
setOpen(false);
|
||||
}
|
||||
}, [drawerState]);
|
||||
|
||||
const handleDrawerOpen = () => {
|
||||
setOpen(true);
|
||||
localStorage.setItem("drawerOpen", 1);
|
||||
};
|
||||
|
||||
const handleDrawerClose = () => {
|
||||
setOpen(false);
|
||||
localStorage.setItem("drawerOpen", 0);
|
||||
};
|
||||
const [drawerOpen, setDrawerOpen] = useLocalStorage("drawerOpen", true);
|
||||
const { user } = useContext(AuthContext);
|
||||
|
||||
const handleMenu = event => {
|
||||
setAnchorEl(event.currentTarget);
|
||||
@@ -156,12 +140,15 @@ const LoggedInLayout = ({ children }) => {
|
||||
<Drawer
|
||||
variant="permanent"
|
||||
classes={{
|
||||
paper: clsx(classes.drawerPaper, !open && classes.drawerPaperClose),
|
||||
paper: clsx(
|
||||
classes.drawerPaper,
|
||||
!drawerOpen && classes.drawerPaperClose
|
||||
),
|
||||
}}
|
||||
open={open}
|
||||
open={drawerOpen}
|
||||
>
|
||||
<div className={classes.toolbarIcon}>
|
||||
<IconButton onClick={handleDrawerClose}>
|
||||
<IconButton onClick={() => setDrawerOpen(!drawerOpen)}>
|
||||
<ChevronLeftIcon />
|
||||
</IconButton>
|
||||
</div>
|
||||
@@ -174,11 +161,11 @@ const LoggedInLayout = ({ children }) => {
|
||||
<UserModal
|
||||
open={userModalOpen}
|
||||
onClose={() => setUserModalOpen(false)}
|
||||
userId={userId}
|
||||
userId={user?.id}
|
||||
/>
|
||||
<AppBar
|
||||
position="absolute"
|
||||
className={clsx(classes.appBar, open && classes.appBarShift)}
|
||||
className={clsx(classes.appBar, drawerOpen && classes.appBarShift)}
|
||||
color={process.env.NODE_ENV === "development" ? "inherit" : "primary"}
|
||||
>
|
||||
<Toolbar variant="dense" className={classes.toolbar}>
|
||||
@@ -186,10 +173,10 @@ const LoggedInLayout = ({ children }) => {
|
||||
edge="start"
|
||||
color="inherit"
|
||||
aria-label="open drawer"
|
||||
onClick={handleDrawerOpen}
|
||||
onClick={() => setDrawerOpen(!drawerOpen)}
|
||||
className={clsx(
|
||||
classes.menuButton,
|
||||
open && classes.menuButtonHidden
|
||||
drawerOpen && classes.menuButtonHidden
|
||||
)}
|
||||
>
|
||||
<MenuIcon />
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useState, useEffect, useReducer } from "react";
|
||||
import React, { useState, useEffect, useReducer, useContext } from "react";
|
||||
import openSocket from "socket.io-client";
|
||||
import { toast } from "react-toastify";
|
||||
import { useHistory } from "react-router-dom";
|
||||
@@ -32,6 +32,7 @@ import Title from "../../components/Title";
|
||||
import MainHeaderButtonsWrapper from "../../components/MainHeaderButtonsWrapper";
|
||||
import MainContainer from "../../components/MainContainer";
|
||||
import toastError from "../../errors/toastError";
|
||||
import { AuthContext } from "../../context/Auth/AuthContext";
|
||||
|
||||
const reducer = (state, action) => {
|
||||
if (action.type === "LOAD_CONTACTS") {
|
||||
@@ -89,7 +90,8 @@ const useStyles = makeStyles(theme => ({
|
||||
const Contacts = () => {
|
||||
const classes = useStyles();
|
||||
const history = useHistory();
|
||||
const userId = +localStorage.getItem("userId");
|
||||
|
||||
const { user } = useContext(AuthContext);
|
||||
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [pageNumber, setPageNumber] = useState(1);
|
||||
@@ -164,7 +166,7 @@ const Contacts = () => {
|
||||
try {
|
||||
const { data: ticket } = await api.post("/tickets", {
|
||||
contactId: contactId,
|
||||
userId: userId,
|
||||
userId: user?.id,
|
||||
status: "open",
|
||||
});
|
||||
history.push(`/tickets/${ticket.id}`);
|
||||
|
||||
@@ -74,7 +74,6 @@ const reducer = (state, action) => {
|
||||
|
||||
if (action.type === "DELETE_QUEUE") {
|
||||
const queueId = action.payload;
|
||||
console.log("QUEUEID", queueId);
|
||||
const queueIndex = state.findIndex(q => q.id === queueId);
|
||||
if (queueIndex !== -1) {
|
||||
state.splice(queueIndex, 1);
|
||||
|
||||
Reference in New Issue
Block a user