Skip to content

Instantly share code, notes, and snippets.

@marcaum54
Last active October 9, 2020 18:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcaum54/1a6f0fcdbd51fe069727883a281d427c to your computer and use it in GitHub Desktop.
Save marcaum54/1a6f0fcdbd51fe069727883a281d427c to your computer and use it in GitHub Desktop.
withAuth.js
import React from "react";
import acesso_login_api from "../../services/AcessoLoginApi"
import redirect from "../../helpers/redirect"
export const withAuth = <T extends object>(C: React.ComponentClass<T>) => {
return class AuthComponent extends React.Component<T> {
static async getInitialProps(ctx) {
const hasCurrentUser = localStorage.getItem("current-user");
if (hasCurrentUser) {
const lastCheck = localStorage.getItem("current-user-last-check");
const diff = Math.abs(lastCheck - Date.now());
const isTimeToCheck = true; //Math.floor((diff / 1000) / 60) >= 10; //10 min after last check
if (isTimeToCheck) {
const { data } = await acesso_login_api.post("user");
if (data && data.is_ativo) {
localStorage.setItem("current-user-last-check", Date.now());
return data;
}
else {
localStorage.removeItem("current-user");
localStorage.removeItem("current-user-last-check");
return redirect(ctx, "/auth/login");
}
}
}
else {
return redirect(ctx, "/auth/login");
}
}
render() {
return <C {...this.props} />;
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment