Skip to content

Commit

Permalink
better handling of jwt and socket connections
Browse files Browse the repository at this point in the history
  • Loading branch information
allgood committed Oct 11, 2024
1 parent 9642603 commit 579f120
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 37 deletions.
57 changes: 23 additions & 34 deletions frontend/src/context/Socket/SocketContext.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@
import { createContext } from "react";
import openSocket from "socket.io-client";
import { getBackendSocketURL } from "../../services/config";
import { isExpired } from "react-jwt";
import { decodeToken, isExpired } from "react-jwt";
import api from "../../services/api";

class ManagedSocket {
constructor(socketManager) {
Expand Down Expand Up @@ -117,20 +118,26 @@ const socketManager = {
currentSocket: null,
socketReady: false,

GetSocket: function(companyId) {
let userId = null;
if (localStorage.getItem("userId")) {
userId = localStorage.getItem("userId");
}
GetSocket: function(_discardCompanyId = null) {

if (!companyId && !this.currentSocket) {
const token = JSON.parse(localStorage.getItem("token"));
if (!token) {
return new DummySocket();
}

if (companyId && typeof companyId !== "string") {
companyId = `${companyId}`;
}
if ( isExpired(token) ) {
console.debug("Expired token, refreshing token");

api.get("/auth/me").then((response) => {
console.debug("Token refreshed", response);
window.location.reload();
});

return new DummySocket();
}

const { userId, companyId } = decodeToken(token);

if (companyId !== this.currentCompanyId || userId !== this.currentUserId) {
if (this.currentSocket) {
console.debug("closing old socket - company or user changed");
Expand All @@ -141,24 +148,6 @@ const socketManager = {
this.currentUserId = null;
}

let token = JSON.parse(localStorage.getItem("token"));
if (!token) {
return new DummySocket();
}

if ( isExpired(token) ) {
console.debug("Expired token, waiting for refresh");
setTimeout(() => {
const currentToken = JSON.parse(localStorage.getItem("token"));
if (isExpired(currentToken)) {
localStorage.removeItem("token");
localStorage.removeItem("companyId");
}
window.location.reload();
},1000);
return new DummySocket();
}

this.currentCompanyId = companyId;
this.currentUserId = userId;

Expand All @@ -171,29 +160,29 @@ const socketManager = {

this.currentSocket.io.on("reconnect_attempt", () => {
this.currentSocket.io.opts.query.r = 1;
token = JSON.parse(localStorage.getItem("token"));
if ( isExpired(token) ) {
const newToken = JSON.parse(localStorage.getItem("token"));
if ( isExpired(newToken) ) {
console.debug("Refreshing");
window.location.reload();
} else {
console.debug("Using new token");
this.currentSocket.io.opts.query.token = token;
this.currentSocket.io.opts.query.token = newToken;
}
});

this.currentSocket.on("disconnect", (reason) => {
console.debug(`socket disconnected because: ${reason}`);
if (reason.startsWith("io server disconnect")) {
console.debug("tryng to reconnect", this.currentSocket);
token = JSON.parse(localStorage.getItem("token"));
const newToken = JSON.parse(localStorage.getItem("token"));

if ( isExpired(token) ) {
if ( isExpired(newToken) ) {
console.debug("Expired token - refreshing");
window.location.reload();
return;
}
console.debug("Reconnecting using refreshed token");
this.currentSocket.io.opts.query.token = token;
this.currentSocket.io.opts.query.token = newToken;
this.currentSocket.io.opts.query.r = 1;
this.currentSocket.connect();
}
Expand Down
11 changes: 8 additions & 3 deletions frontend/src/hooks/useAuth.js/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import api from "../../services/api";
import toastError from "../../errors/toastError";
import { SocketContext } from "../../context/Socket/SocketContext";
import moment from "moment";
import { decodeToken } from "react-jwt";

const useAuth = () => {
const history = useHistory();
const [isAuth, setIsAuth] = useState(false);
Expand Down Expand Up @@ -101,9 +103,12 @@ const useAuth = () => {
try {
const { data } = await api.post("/auth/login", userData);
const {
user: { companyId, id, company },
user: { company },
token
} = data;

const { companyId, userId } = decodeToken(token);

if (has(company, "settings") && isArray(company.settings)) {
const setting = company.settings.find(
(s) => s.key === "campaignsEnabled"
Expand All @@ -124,9 +129,9 @@ const useAuth = () => {
var dias = moment.duration(diff).asDays();

if (before === true) {
localStorage.setItem("token", JSON.stringify(data.token));
localStorage.setItem("token", JSON.stringify(token));
localStorage.setItem("companyId", companyId);
localStorage.setItem("userId", id);
localStorage.setItem("userId", userId);
localStorage.setItem("companyDueDate", vencimento);
api.defaults.headers.Authorization = `Bearer ${data.token}`;
setUser(data.user);
Expand Down

0 comments on commit 579f120

Please sign in to comment.