Last active
October 9, 2020 18:39
-
-
Save marcaum54/1a6f0fcdbd51fe069727883a281d427c to your computer and use it in GitHub Desktop.
withAuth.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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