improvement: moved user data from localstorage to context

This commit is contained in:
canove
2021-01-13 08:08:25 -03:00
parent 2bec877e4f
commit 3aa287d394
23 changed files with 231 additions and 134 deletions

View File

@@ -8,7 +8,7 @@ import { RefreshTokenService } from "../services/AuthServices/RefreshTokenServic
export const store = async (req: Request, res: Response): Promise<Response> => { export const store = async (req: Request, res: Response): Promise<Response> => {
const { email, password } = req.body; const { email, password } = req.body;
const { token, user, refreshToken } = await AuthUserService({ const { token, serializedUser, refreshToken } = await AuthUserService({
email, email,
password password
}); });
@@ -17,9 +17,7 @@ export const store = async (req: Request, res: Response): Promise<Response> => {
return res.status(200).json({ return res.status(200).json({
token, token,
username: user.name, user: serializedUser
profile: user.profile,
userId: user.id
}); });
}; };
@@ -33,9 +31,9 @@ export const update = async (
throw new AppError("ERR_SESSION_EXPIRED", 401); throw new AppError("ERR_SESSION_EXPIRED", 401);
} }
const { newToken, refreshToken } = await RefreshTokenService(token); const { user, newToken, refreshToken } = await RefreshTokenService(token);
SendRefreshToken(res, refreshToken); SendRefreshToken(res, refreshToken);
return res.json({ token: newToken }); return res.json({ token: newToken, user });
}; };

View 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
};
};

View File

@@ -1,4 +1,6 @@
import { verify } from "jsonwebtoken"; import { verify } from "jsonwebtoken";
import User from "../../models/User";
import AppError from "../../errors/AppError"; import AppError from "../../errors/AppError";
import ShowUserService from "../UserServices/ShowUserService"; import ShowUserService from "../UserServices/ShowUserService";
import authConfig from "../../config/auth"; import authConfig from "../../config/auth";
@@ -13,6 +15,7 @@ interface RefreshTokenPayload {
} }
interface Response { interface Response {
user: User;
newToken: string; newToken: string;
refreshToken: string; refreshToken: string;
} }
@@ -37,5 +40,5 @@ export const RefreshTokenService = async (token: string): Promise<Response> => {
const newToken = createAccessToken(user); const newToken = createAccessToken(user);
const refreshToken = createRefreshToken(user); const refreshToken = createRefreshToken(user);
return { newToken, refreshToken }; return { user, newToken, refreshToken };
}; };

View File

@@ -4,6 +4,16 @@ import {
createAccessToken, createAccessToken,
createRefreshToken createRefreshToken
} from "../../helpers/CreateTokens"; } 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 { interface Request {
email: string; email: string;
@@ -11,7 +21,7 @@ interface Request {
} }
interface Response { interface Response {
user: User; serializedUser: SerializedUser;
token: string; token: string;
refreshToken: string; refreshToken: string;
} }
@@ -21,7 +31,8 @@ const AuthUserService = async ({
password password
}: Request): Promise<Response> => { }: Request): Promise<Response> => {
const user = await User.findOne({ const user = await User.findOne({
where: { email } where: { email },
include: ["queues"]
}); });
if (!user) { if (!user) {
@@ -35,8 +46,10 @@ const AuthUserService = async ({
const token = createAccessToken(user); const token = createAccessToken(user);
const refreshToken = createRefreshToken(user); const refreshToken = createRefreshToken(user);
const serializedUser = SerializeUser(user);
return { return {
user, serializedUser,
token, token,
refreshToken refreshToken
}; };

View File

@@ -1,6 +1,7 @@
import * as Yup from "yup"; import * as Yup from "yup";
import AppError from "../../errors/AppError"; import AppError from "../../errors/AppError";
import { SerializeUser } from "../../helpers/SerializeUser";
import User from "../../models/User"; import User from "../../models/User";
interface Request { interface Request {
@@ -63,13 +64,7 @@ const CreateUserService = async ({
await user.reload(); await user.reload();
const serializedUser = { const serializedUser = SerializeUser(user);
id: user.id,
name: user.name,
email: user.email,
profile: user.profile,
queues: user.queues
};
return serializedUser; return serializedUser;
}; };

View File

@@ -0,0 +1,11 @@
const rules = {
user: {
static: [],
},
admin: {
static: ["drawer-admin-items:view"],
},
};
export default rules;

View 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;

View File

@@ -25,6 +25,8 @@ import { i18n } from "../../translate/i18n";
import api from "../../services/api"; import api from "../../services/api";
import RecordingTimer from "./RecordingTimer"; import RecordingTimer from "./RecordingTimer";
import { ReplyMessageContext } from "../../context/ReplyingMessage/ReplyingMessageContext"; import { ReplyMessageContext } from "../../context/ReplyingMessage/ReplyingMessageContext";
import { AuthContext } from "../../context/Auth/AuthContext";
import { useLocalStorage } from "../../hooks/useLocalStorage";
import toastError from "../../errors/toastError"; import toastError from "../../errors/toastError";
const Mp3Recorder = new MicRecorder({ bitRate: 128 }); const Mp3Recorder = new MicRecorder({ bitRate: 128 });
@@ -164,7 +166,6 @@ const useStyles = makeStyles(theme => ({
const MessageInput = ({ ticketStatus }) => { const MessageInput = ({ ticketStatus }) => {
const classes = useStyles(); const classes = useStyles();
const { ticketId } = useParams(); const { ticketId } = useParams();
const username = localStorage.getItem("username");
const [medias, setMedias] = useState([]); const [medias, setMedias] = useState([]);
const [inputMessage, setInputMessage] = useState(""); const [inputMessage, setInputMessage] = useState("");
@@ -175,17 +176,9 @@ const MessageInput = ({ ticketStatus }) => {
const { setReplyingMessage, replyingMessage } = useContext( const { setReplyingMessage, replyingMessage } = useContext(
ReplyMessageContext ReplyMessageContext
); );
const { user } = useContext(AuthContext);
const [signMessage, setSignMessage] = useState(false); const [signMessage, setSignMessage] = useLocalStorage("signOption", true);
useEffect(() => {
const storedSignOption = localStorage.getItem("signOption");
if (storedSignOption === "true") setSignMessage(true);
}, []);
useEffect(() => {
localStorage.setItem("signOption", signMessage);
}, [signMessage]);
useEffect(() => { useEffect(() => {
inputRef.current.focus(); inputRef.current.focus();
@@ -255,7 +248,7 @@ const MessageInput = ({ ticketStatus }) => {
fromMe: true, fromMe: true,
mediaUrl: "", mediaUrl: "",
body: signMessage body: signMessage
? `*${username}:*\n${inputMessage.trim()}` ? `*${user?.name}:*\n${inputMessage.trim()}`
: inputMessage.trim(), : inputMessage.trim(),
quotedMsg: replyingMessage, quotedMsg: replyingMessage,
}; };
@@ -279,7 +272,7 @@ const MessageInput = ({ ticketStatus }) => {
setRecording(true); setRecording(true);
setLoading(false); setLoading(false);
} catch (err) { } catch (err) {
console.log(err); toastError(err);
setLoading(false); setLoading(false);
} }
}; };
@@ -314,7 +307,7 @@ const MessageInput = ({ ticketStatus }) => {
await Mp3Recorder.stop().getMp3(); await Mp3Recorder.stop().getMp3();
setRecording(false); setRecording(false);
} catch (err) { } catch (err) {
console.log(err); toastError(err);
} }
}; };
@@ -428,8 +421,8 @@ const MessageInput = ({ ticketStatus }) => {
<Switch <Switch
size="small" size="small"
checked={signMessage} checked={signMessage}
onChange={() => { onChange={e => {
setSignMessage(prevState => !prevState); setSignMessage(e.target.checked);
}} }}
name="showAllTickets" name="showAllTickets"
color="primary" color="primary"

View File

@@ -301,7 +301,7 @@ const reducer = (state, action) => {
} }
}; };
const MessagesList = ({ ticketId, isGroup, setReplyingMessage }) => { const MessagesList = ({ ticketId, isGroup }) => {
const classes = useStyles(); const classes = useStyles();
const [messagesList, dispatch] = useReducer(reducer, []); const [messagesList, dispatch] = useReducer(reducer, []);

View File

@@ -1,4 +1,4 @@
import React, { useState, useEffect } from "react"; import React, { useState, useEffect, useContext } from "react";
import { useHistory } from "react-router-dom"; import { useHistory } from "react-router-dom";
import Button from "@material-ui/core/Button"; import Button from "@material-ui/core/Button";
@@ -18,6 +18,7 @@ import api from "../../services/api";
import ButtonWithSpinner from "../ButtonWithSpinner"; import ButtonWithSpinner from "../ButtonWithSpinner";
import ContactModal from "../ContactModal"; import ContactModal from "../ContactModal";
import toastError from "../../errors/toastError"; import toastError from "../../errors/toastError";
import { AuthContext } from "../../context/Auth/AuthContext";
const filter = createFilterOptions({ const filter = createFilterOptions({
trim: true, trim: true,
@@ -25,7 +26,6 @@ const filter = createFilterOptions({
const NewTicketModal = ({ modalOpen, onClose }) => { const NewTicketModal = ({ modalOpen, onClose }) => {
const history = useHistory(); const history = useHistory();
const userId = +localStorage.getItem("userId");
const [options, setOptions] = useState([]); const [options, setOptions] = useState([]);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
@@ -33,6 +33,7 @@ const NewTicketModal = ({ modalOpen, onClose }) => {
const [selectedContact, setSelectedContact] = useState(null); const [selectedContact, setSelectedContact] = useState(null);
const [newContact, setNewContact] = useState({}); const [newContact, setNewContact] = useState({});
const [contactModalOpen, setContactModalOpen] = useState(false); const [contactModalOpen, setContactModalOpen] = useState(false);
const { user } = useContext(AuthContext);
useEffect(() => { useEffect(() => {
if (!modalOpen || searchParam.length < 3) { if (!modalOpen || searchParam.length < 3) {
@@ -71,7 +72,7 @@ const NewTicketModal = ({ modalOpen, onClose }) => {
try { try {
const { data: ticket } = await api.post("/tickets", { const { data: ticket } = await api.post("/tickets", {
contactId: contactId, contactId: contactId,
userId: userId, userId: user.id,
status: "open", status: "open",
}); });
history.push(`/tickets/${ticket.id}`); history.push(`/tickets/${ticket.id}`);

View File

@@ -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 { useHistory } from "react-router-dom";
import { format } from "date-fns"; import { format } from "date-fns";
@@ -18,6 +18,7 @@ import TicketListItem from "../TicketListItem";
import { i18n } from "../../translate/i18n"; import { i18n } from "../../translate/i18n";
import useTickets from "../../hooks/useTickets"; import useTickets from "../../hooks/useTickets";
import alertSound from "../../assets/sound.mp3"; import alertSound from "../../assets/sound.mp3";
import { AuthContext } from "../../context/Auth/AuthContext";
const useStyles = makeStyles(theme => ({ const useStyles = makeStyles(theme => ({
tabContainer: { tabContainer: {
@@ -43,7 +44,7 @@ const NotificationsPopOver = () => {
const classes = useStyles(); const classes = useStyles();
const history = useHistory(); const history = useHistory();
const userId = +localStorage.getItem("userId"); const { user } = useContext(AuthContext);
const ticketIdUrl = +history.location.pathname.split("/")[2]; const ticketIdUrl = +history.location.pathname.split("/")[2];
const ticketIdRef = useRef(ticketIdUrl); const ticketIdRef = useRef(ticketIdUrl);
const anchorEl = useRef(); const anchorEl = useRef();
@@ -108,7 +109,7 @@ const NotificationsPopOver = () => {
if ( if (
data.action === "create" && data.action === "create" &&
!data.message.read && !data.message.read &&
(data.ticket.userId === userId || !data.ticket.userId) (data.ticket.userId === user?.id || !data.ticket.userId)
) { ) {
setNotifications(prevState => { setNotifications(prevState => {
const ticketIndex = prevState.findIndex(t => t.id === data.ticket.id); const ticketIndex = prevState.findIndex(t => t.id === data.ticket.id);
@@ -122,7 +123,7 @@ const NotificationsPopOver = () => {
const shouldNotNotificate = const shouldNotNotificate =
(data.message.ticketId === ticketIdRef.current && (data.message.ticketId === ticketIdRef.current &&
document.visibilityState === "visible") || document.visibilityState === "visible") ||
(data.ticket.userId && data.ticket.userId !== userId) || (data.ticket.userId && data.ticket.userId !== user?.id) ||
data.ticket.isGroup; data.ticket.isGroup;
if (shouldNotNotificate) return; if (shouldNotNotificate) return;
@@ -134,7 +135,7 @@ const NotificationsPopOver = () => {
return () => { return () => {
socket.disconnect(); socket.disconnect();
}; };
}, [history, userId]); }, [history, user]);
const handleNotifications = (data, history) => { const handleNotifications = (data, history) => {
const { message, contact, ticket } = data; const { message, contact, ticket } = data;

View File

@@ -41,7 +41,7 @@ const QueueSelector = ({ selectedQueueIds, onChange }) => {
return ( return (
<div style={{ marginTop: 6 }}> <div style={{ marginTop: 6 }}>
<FormControl fullWidth variant="outlined"> <FormControl fullWidth margin="dense" variant="outlined">
<InputLabel>Filas</InputLabel> <InputLabel>Filas</InputLabel>
<Select <Select
multiple multiple

View File

@@ -1,4 +1,4 @@
import React, { useState } from "react"; import React, { useContext, useState } from "react";
import { useHistory } from "react-router-dom"; import { useHistory } from "react-router-dom";
import { makeStyles } from "@material-ui/core/styles"; import { makeStyles } from "@material-ui/core/styles";
@@ -10,6 +10,7 @@ import api from "../../services/api";
import TicketOptionsMenu from "../TicketOptionsMenu"; import TicketOptionsMenu from "../TicketOptionsMenu";
import ButtonWithSpinner from "../ButtonWithSpinner"; import ButtonWithSpinner from "../ButtonWithSpinner";
import toastError from "../../errors/toastError"; import toastError from "../../errors/toastError";
import { AuthContext } from "../../context/Auth/AuthContext";
const useStyles = makeStyles(theme => ({ const useStyles = makeStyles(theme => ({
actionButtons: { actionButtons: {
@@ -26,10 +27,10 @@ const useStyles = makeStyles(theme => ({
const TicketActionButtons = ({ ticket }) => { const TicketActionButtons = ({ ticket }) => {
const classes = useStyles(); const classes = useStyles();
const history = useHistory(); const history = useHistory();
const userId = +localStorage.getItem("userId");
const [anchorEl, setAnchorEl] = useState(null); const [anchorEl, setAnchorEl] = useState(null);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const ticketOptionsMenuOpen = Boolean(anchorEl); const ticketOptionsMenuOpen = Boolean(anchorEl);
const { user } = useContext(AuthContext);
const handleOpenTicketOptionsMenu = e => { const handleOpenTicketOptionsMenu = e => {
setAnchorEl(e.currentTarget); setAnchorEl(e.currentTarget);
@@ -66,7 +67,7 @@ const TicketActionButtons = ({ ticket }) => {
loading={loading} loading={loading}
startIcon={<Replay />} startIcon={<Replay />}
size="small" size="small"
onClick={e => handleUpdateTicketStatus(e, "open", userId)} onClick={e => handleUpdateTicketStatus(e, "open", user?.id)}
> >
{i18n.t("messagesList.header.buttons.reopen")} {i18n.t("messagesList.header.buttons.reopen")}
</ButtonWithSpinner> </ButtonWithSpinner>
@@ -86,7 +87,7 @@ const TicketActionButtons = ({ ticket }) => {
size="small" size="small"
variant="contained" variant="contained"
color="primary" color="primary"
onClick={e => handleUpdateTicketStatus(e, "closed", userId)} onClick={e => handleUpdateTicketStatus(e, "closed", user?.id)}
> >
{i18n.t("messagesList.header.buttons.resolve")} {i18n.t("messagesList.header.buttons.resolve")}
</ButtonWithSpinner> </ButtonWithSpinner>
@@ -107,7 +108,7 @@ const TicketActionButtons = ({ ticket }) => {
size="small" size="small"
variant="contained" variant="contained"
color="primary" color="primary"
onClick={e => handleUpdateTicketStatus(e, "open", userId)} onClick={e => handleUpdateTicketStatus(e, "open", user?.id)}
> >
{i18n.t("messagesList.header.buttons.accept")} {i18n.t("messagesList.header.buttons.accept")}
</ButtonWithSpinner> </ButtonWithSpinner>

View File

@@ -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 { useHistory, useParams } from "react-router-dom";
import { parseISO, format, isSameDay } from "date-fns"; import { parseISO, format, isSameDay } from "date-fns";
@@ -20,6 +20,7 @@ import api from "../../services/api";
import ButtonWithSpinner from "../ButtonWithSpinner"; import ButtonWithSpinner from "../ButtonWithSpinner";
import MarkdownWrapper from "../MarkdownWrapper"; import MarkdownWrapper from "../MarkdownWrapper";
import { Tooltip } from "@material-ui/core"; import { Tooltip } from "@material-ui/core";
import { AuthContext } from "../../context/Auth/AuthContext";
const useStyles = makeStyles(theme => ({ const useStyles = makeStyles(theme => ({
ticket: { ticket: {
@@ -102,10 +103,10 @@ const useStyles = makeStyles(theme => ({
const TicketListItem = ({ ticket }) => { const TicketListItem = ({ ticket }) => {
const classes = useStyles(); const classes = useStyles();
const history = useHistory(); const history = useHistory();
const userId = +localStorage.getItem("userId");
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const { ticketId } = useParams(); const { ticketId } = useParams();
const isMounted = useRef(true); const isMounted = useRef(true);
const { user } = useContext(AuthContext);
useEffect(() => { useEffect(() => {
return () => { return () => {
@@ -118,7 +119,7 @@ const TicketListItem = ({ ticket }) => {
try { try {
await api.put(`/tickets/${ticketId}`, { await api.put(`/tickets/${ticketId}`, {
status: "open", status: "open",
userId: userId, userId: user?.id,
}); });
} catch (err) { } catch (err) {
setLoading(false); setLoading(false);

View File

@@ -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 openSocket from "socket.io-client";
import { makeStyles } from "@material-ui/core/styles"; import { makeStyles } from "@material-ui/core/styles";
@@ -10,6 +10,7 @@ import TicketsListSkeleton from "../TicketsListSkeleton";
import useTickets from "../../hooks/useTickets"; import useTickets from "../../hooks/useTickets";
import { i18n } from "../../translate/i18n"; import { i18n } from "../../translate/i18n";
import { ListSubheader } from "@material-ui/core"; import { ListSubheader } from "@material-ui/core";
import { AuthContext } from "../../context/Auth/AuthContext";
const useStyles = makeStyles(theme => ({ const useStyles = makeStyles(theme => ({
ticketsListWrapper: { ticketsListWrapper: {
@@ -149,10 +150,10 @@ const reducer = (state, action) => {
}; };
const TicketsList = ({ status, searchParam, showAll }) => { const TicketsList = ({ status, searchParam, showAll }) => {
const userId = +localStorage.getItem("userId");
const classes = useStyles(); const classes = useStyles();
const [pageNumber, setPageNumber] = useState(1); const [pageNumber, setPageNumber] = useState(1);
const [ticketsList, dispatch] = useReducer(reducer, []); const [ticketsList, dispatch] = useReducer(reducer, []);
const { user } = useContext(AuthContext);
useEffect(() => { useEffect(() => {
dispatch({ type: "RESET" }); dispatch({ type: "RESET" });
@@ -194,7 +195,7 @@ const TicketsList = ({ status, searchParam, showAll }) => {
if ( if (
(data.action === "updateStatus" || data.action === "create") && (data.action === "updateStatus" || data.action === "create") &&
(!data.ticket.userId || data.ticket.userId === userId || showAll) (!data.ticket.userId || data.ticket.userId === user?.id || showAll)
) { ) {
dispatch({ dispatch({
type: "UPDATE_TICKET", type: "UPDATE_TICKET",
@@ -210,7 +211,7 @@ const TicketsList = ({ status, searchParam, showAll }) => {
socket.on("appMessage", data => { socket.on("appMessage", data => {
if ( if (
data.action === "create" && data.action === "create" &&
(!data.ticket.userId || data.ticket.userId === userId || showAll) (!data.ticket.userId || data.ticket.userId === user?.id || showAll)
) { ) {
dispatch({ dispatch({
type: "UPDATE_TICKET_MESSAGES_COUNT", type: "UPDATE_TICKET_MESSAGES_COUNT",
@@ -234,7 +235,7 @@ const TicketsList = ({ status, searchParam, showAll }) => {
return () => { return () => {
socket.disconnect(); socket.disconnect();
}; };
}, [status, showAll, userId, searchParam]); }, [status, showAll, user, searchParam]);
const loadMore = () => { const loadMore = () => {
setPageNumber(prevState => prevState + 1); setPageNumber(prevState => prevState + 1);

View File

@@ -175,13 +175,13 @@ const TicketsManager = () => {
</Paper> </Paper>
<TabPanel value={tab} name="open" className={classes.ticketsWrapper}> <TabPanel value={tab} name="open" className={classes.ticketsWrapper}>
<TicketsList status="open" showAll={showAllTickets} /> <TicketsList status="open" showAll={showAllTickets} />
<TicketsList status="pending" showAll={true} /> <TicketsList status="pending" />
</TabPanel> </TabPanel>
<TabPanel value={tab} name="closed" className={classes.ticketsWrapper}> <TabPanel value={tab} name="closed" className={classes.ticketsWrapper}>
<TicketsList status="closed" showAll={true} /> <TicketsList status="closed" showAll={showAllTickets} />
</TabPanel> </TabPanel>
<TabPanel value={tab} name="search" className={classes.ticketsWrapper}> <TabPanel value={tab} name="search" className={classes.ticketsWrapper}>
<TicketsList searchParam={searchParam} showAll={true} /> <TicketsList searchParam={searchParam} showAll={showAllTickets} />
</TabPanel> </TabPanel>
</Paper> </Paper>
); );

View File

@@ -5,11 +5,11 @@ import useAuth from "./useAuth";
const AuthContext = createContext(); const AuthContext = createContext();
const AuthProvider = ({ children }) => { const AuthProvider = ({ children }) => {
const { isAuth, loading, handleLogin, handleLogout } = useAuth(); const { loading, user, isAuth, handleLogin, handleLogout } = useAuth();
return ( return (
<AuthContext.Provider <AuthContext.Provider
value={{ loading, isAuth, handleLogin, handleLogout }} value={{ loading, user, isAuth, handleLogin, handleLogout }}
> >
{children} {children}
</AuthContext.Provider> </AuthContext.Provider>

View File

@@ -6,11 +6,13 @@ import { toast } from "react-toastify";
import { i18n } from "../../translate/i18n"; import { i18n } from "../../translate/i18n";
import api from "../../services/api"; import api from "../../services/api";
import toastError from "../../errors/toastError"; import toastError from "../../errors/toastError";
// import { useLocalStorage } from "../../hooks/useLocalStorage";
const useAuth = () => { const useAuth = () => {
const history = useHistory(); const history = useHistory();
const [isAuth, setIsAuth] = useState(false); const [isAuth, setIsAuth] = useState(false);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [user, setUser] = useState({});
api.interceptors.request.use( api.interceptors.request.use(
config => { config => {
@@ -44,9 +46,6 @@ const useAuth = () => {
} }
if (error?.response?.status === 401) { if (error?.response?.status === 401) {
localStorage.removeItem("token"); localStorage.removeItem("token");
localStorage.removeItem("username");
localStorage.removeItem("profile");
localStorage.removeItem("userId");
api.defaults.headers.Authorization = undefined; api.defaults.headers.Authorization = undefined;
setIsAuth(false); setIsAuth(false);
} }
@@ -56,11 +55,15 @@ const useAuth = () => {
useEffect(() => { useEffect(() => {
const token = localStorage.getItem("token"); const token = localStorage.getItem("token");
if (token) { (async () => {
api.defaults.headers.Authorization = `Bearer ${JSON.parse(token)}`; if (token) {
setIsAuth(true); const { data } = await api.post("/auth/refresh_token");
} api.defaults.headers.Authorization = `Bearer ${JSON.parse(token)}`;
setLoading(false); setIsAuth(true);
setUser(data.user);
}
setLoading(false);
})();
}, []); }, []);
const handleLogin = async user => { const handleLogin = async user => {
@@ -69,11 +72,8 @@ const useAuth = () => {
try { try {
const { data } = await api.post("/auth/login", user); const { data } = await api.post("/auth/login", user);
localStorage.setItem("token", JSON.stringify(data.token)); 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}`; api.defaults.headers.Authorization = `Bearer ${data.token}`;
setUser(data.user);
setIsAuth(true); setIsAuth(true);
toast.success(i18n.t("auth.toasts.success")); toast.success(i18n.t("auth.toasts.success"));
history.push("/tickets"); history.push("/tickets");
@@ -84,20 +84,17 @@ const useAuth = () => {
} }
}; };
const handleLogout = e => { const handleLogout = () => {
setLoading(true); setLoading(true);
e.preventDefault();
setIsAuth(false); setIsAuth(false);
setUser({});
localStorage.removeItem("token"); localStorage.removeItem("token");
localStorage.removeItem("username");
localStorage.removeItem("profile");
localStorage.removeItem("userId");
api.defaults.headers.Authorization = undefined; api.defaults.headers.Authorization = undefined;
setLoading(false); setLoading(false);
history.push("/login"); history.push("/login");
}; };
return { isAuth, setIsAuth, loading, handleLogin, handleLogout }; return { isAuth, user, setUser, loading, handleLogin, handleLogout };
}; };
export default useAuth; export default useAuth;

View 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];
}

View File

@@ -17,6 +17,8 @@ import AccountTreeOutlinedIcon from "@material-ui/icons/AccountTreeOutlined";
import { i18n } from "../translate/i18n"; import { i18n } from "../translate/i18n";
import { WhatsAppsContext } from "../context/WhatsApp/WhatsAppsContext"; import { WhatsAppsContext } from "../context/WhatsApp/WhatsAppsContext";
import { AuthContext } from "../context/Auth/AuthContext";
import Can from "../components/Can";
function ListItemLink(props) { function ListItemLink(props) {
const { icon, primary, to, className } = props; const { icon, primary, to, className } = props;
@@ -40,8 +42,8 @@ function ListItemLink(props) {
} }
const MainListItems = () => { const MainListItems = () => {
const userProfile = localStorage.getItem("profile");
const { whatsApps } = useContext(WhatsAppsContext); const { whatsApps } = useContext(WhatsAppsContext);
const { user } = useContext(AuthContext);
const [connectionWarning, setConnectionWarning] = useState(false); const [connectionWarning, setConnectionWarning] = useState(false);
useEffect(() => { useEffect(() => {
@@ -95,29 +97,33 @@ const MainListItems = () => {
primary={i18n.t("mainDrawer.listItems.contacts")} primary={i18n.t("mainDrawer.listItems.contacts")}
icon={<ContactPhoneOutlinedIcon />} icon={<ContactPhoneOutlinedIcon />}
/> />
{userProfile === "admin" && ( <Can
<> role={user.profile}
<Divider /> perform="drawer-admin-items:view"
<ListSubheader inset> yes={() => (
{i18n.t("mainDrawer.listItems.administration")} <>
</ListSubheader> <Divider />
<ListItemLink <ListSubheader inset>
to="/users" {i18n.t("mainDrawer.listItems.administration")}
primary={i18n.t("mainDrawer.listItems.users")} </ListSubheader>
icon={<PeopleAltOutlinedIcon />} <ListItemLink
/> to="/users"
<ListItemLink primary={i18n.t("mainDrawer.listItems.users")}
to="/queues" icon={<PeopleAltOutlinedIcon />}
primary={i18n.t("mainDrawer.listItems.queues")} />
icon={<AccountTreeOutlinedIcon />} <ListItemLink
/> to="/queues"
<ListItemLink primary={i18n.t("mainDrawer.listItems.queues")}
to="/settings" icon={<AccountTreeOutlinedIcon />}
primary={i18n.t("mainDrawer.listItems.settings")} />
icon={<SettingsOutlinedIcon />} <ListItemLink
/> to="/settings"
</> primary={i18n.t("mainDrawer.listItems.settings")}
)} icon={<SettingsOutlinedIcon />}
/>
</>
)}
/>
</div> </div>
); );
}; };

View File

@@ -1,4 +1,4 @@
import React, { useState, useContext, useEffect } from "react"; import React, { useState, useContext } from "react";
import clsx from "clsx"; import clsx from "clsx";
import { import {
@@ -24,6 +24,7 @@ import UserModal from "../components/UserModal";
import { AuthContext } from "../context/Auth/AuthContext"; import { AuthContext } from "../context/Auth/AuthContext";
import BackdropLoading from "../components/BackdropLoading"; import BackdropLoading from "../components/BackdropLoading";
import { i18n } from "../translate/i18n"; import { i18n } from "../translate/i18n";
import { useLocalStorage } from "../hooks/useLocalStorage";
const drawerWidth = 240; const drawerWidth = 240;
@@ -107,30 +108,13 @@ const useStyles = makeStyles(theme => ({
})); }));
const LoggedInLayout = ({ children }) => { const LoggedInLayout = ({ children }) => {
const drawerState = localStorage.getItem("drawerOpen");
const userId = +localStorage.getItem("userId");
const classes = useStyles(); const classes = useStyles();
const [open, setOpen] = useState(true);
const [userModalOpen, setUserModalOpen] = useState(false); const [userModalOpen, setUserModalOpen] = useState(false);
const [anchorEl, setAnchorEl] = useState(null); const [anchorEl, setAnchorEl] = useState(null);
const [menuOpen, setMenuOpen] = useState(false); const [menuOpen, setMenuOpen] = useState(false);
const { handleLogout, loading } = useContext(AuthContext); const { handleLogout, loading } = useContext(AuthContext);
const [drawerOpen, setDrawerOpen] = useLocalStorage("drawerOpen", true);
useEffect(() => { const { user } = useContext(AuthContext);
if (drawerState === "0") {
setOpen(false);
}
}, [drawerState]);
const handleDrawerOpen = () => {
setOpen(true);
localStorage.setItem("drawerOpen", 1);
};
const handleDrawerClose = () => {
setOpen(false);
localStorage.setItem("drawerOpen", 0);
};
const handleMenu = event => { const handleMenu = event => {
setAnchorEl(event.currentTarget); setAnchorEl(event.currentTarget);
@@ -156,12 +140,15 @@ const LoggedInLayout = ({ children }) => {
<Drawer <Drawer
variant="permanent" variant="permanent"
classes={{ classes={{
paper: clsx(classes.drawerPaper, !open && classes.drawerPaperClose), paper: clsx(
classes.drawerPaper,
!drawerOpen && classes.drawerPaperClose
),
}} }}
open={open} open={drawerOpen}
> >
<div className={classes.toolbarIcon}> <div className={classes.toolbarIcon}>
<IconButton onClick={handleDrawerClose}> <IconButton onClick={() => setDrawerOpen(!drawerOpen)}>
<ChevronLeftIcon /> <ChevronLeftIcon />
</IconButton> </IconButton>
</div> </div>
@@ -174,11 +161,11 @@ const LoggedInLayout = ({ children }) => {
<UserModal <UserModal
open={userModalOpen} open={userModalOpen}
onClose={() => setUserModalOpen(false)} onClose={() => setUserModalOpen(false)}
userId={userId} userId={user?.id}
/> />
<AppBar <AppBar
position="absolute" position="absolute"
className={clsx(classes.appBar, open && classes.appBarShift)} className={clsx(classes.appBar, drawerOpen && classes.appBarShift)}
color={process.env.NODE_ENV === "development" ? "inherit" : "primary"} color={process.env.NODE_ENV === "development" ? "inherit" : "primary"}
> >
<Toolbar variant="dense" className={classes.toolbar}> <Toolbar variant="dense" className={classes.toolbar}>
@@ -186,10 +173,10 @@ const LoggedInLayout = ({ children }) => {
edge="start" edge="start"
color="inherit" color="inherit"
aria-label="open drawer" aria-label="open drawer"
onClick={handleDrawerOpen} onClick={() => setDrawerOpen(!drawerOpen)}
className={clsx( className={clsx(
classes.menuButton, classes.menuButton,
open && classes.menuButtonHidden drawerOpen && classes.menuButtonHidden
)} )}
> >
<MenuIcon /> <MenuIcon />

View File

@@ -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 openSocket from "socket.io-client";
import { toast } from "react-toastify"; import { toast } from "react-toastify";
import { useHistory } from "react-router-dom"; import { useHistory } from "react-router-dom";
@@ -32,6 +32,7 @@ import Title from "../../components/Title";
import MainHeaderButtonsWrapper from "../../components/MainHeaderButtonsWrapper"; import MainHeaderButtonsWrapper from "../../components/MainHeaderButtonsWrapper";
import MainContainer from "../../components/MainContainer"; import MainContainer from "../../components/MainContainer";
import toastError from "../../errors/toastError"; import toastError from "../../errors/toastError";
import { AuthContext } from "../../context/Auth/AuthContext";
const reducer = (state, action) => { const reducer = (state, action) => {
if (action.type === "LOAD_CONTACTS") { if (action.type === "LOAD_CONTACTS") {
@@ -89,7 +90,8 @@ const useStyles = makeStyles(theme => ({
const Contacts = () => { const Contacts = () => {
const classes = useStyles(); const classes = useStyles();
const history = useHistory(); const history = useHistory();
const userId = +localStorage.getItem("userId");
const { user } = useContext(AuthContext);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [pageNumber, setPageNumber] = useState(1); const [pageNumber, setPageNumber] = useState(1);
@@ -164,7 +166,7 @@ const Contacts = () => {
try { try {
const { data: ticket } = await api.post("/tickets", { const { data: ticket } = await api.post("/tickets", {
contactId: contactId, contactId: contactId,
userId: userId, userId: user?.id,
status: "open", status: "open",
}); });
history.push(`/tickets/${ticket.id}`); history.push(`/tickets/${ticket.id}`);

View File

@@ -74,7 +74,6 @@ const reducer = (state, action) => {
if (action.type === "DELETE_QUEUE") { if (action.type === "DELETE_QUEUE") {
const queueId = action.payload; const queueId = action.payload;
console.log("QUEUEID", queueId);
const queueIndex = state.findIndex(q => q.id === queueId); const queueIndex = state.findIndex(q => q.id === queueId);
if (queueIndex !== -1) { if (queueIndex !== -1) {
state.splice(queueIndex, 1); state.splice(queueIndex, 1);