From c3f1204fd0646708c7ca3879cb6aa00754b043e2 Mon Sep 17 00:00:00 2001 From: meskio <meskio@sindominio.net> Date: Tue, 29 Sep 2020 11:21:50 +0200 Subject: [PATCH] Detect if token is expired --- src/App.js | 29 ++++++++++++++++++++++------- src/SignIn.js | 4 ++-- 2 files changed, 24 insertions(+), 9 deletions(-) diff --git a/src/App.js b/src/App.js index ef761f9..1b9fdea 100644 --- a/src/App.js +++ b/src/App.js @@ -40,7 +40,6 @@ class App extends React.Component { constructor(props) { super(props); this.state = { - isLoged: false, num: null, role: null, token: null @@ -55,7 +54,7 @@ class App extends React.Component { if (token) { const num = localStorage.getItem("num"); const role = localStorage.getItem("role"); - this.setState({ isLoged: true, num, role, token }); + this.setState({ num, role, token }); } } @@ -67,7 +66,6 @@ class App extends React.Component { login(token, member) { this.setState({ - isLoged: true, num: member.num, role: member.role, token: token @@ -75,9 +73,12 @@ class App extends React.Component { this.storeState(token, member.num, member.role); } + isLoged() { + return this.state.token !== null && !this.tokenExpired(); + } + logout() { this.setState({ - isLoged: false, num: null, role: null, token: null @@ -85,10 +86,24 @@ class App extends React.Component { this.storeState("", "", ""); } + tokenExpired() { + const token = this.state.token; + const base64Url = token.split('.')[1]; + const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/'); + const jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) { + return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); + }).join('')); + const claims = JSON.parse(jsonPayload); + + return claims["exp"] < Date.now(); + }; + render() { - const component = this.state.isLoged ? - <Panel onLogout={this.logout} /> : - <SignIn onLogin={this.login} />; + let component = <Panel onLogout={this.logout} />; + if (!this.isLoged()) { + component = <SignIn onLogin={this.login} />; + } + return ( <AuthContext.Provider value={this.state}> {component} diff --git a/src/SignIn.js b/src/SignIn.js index 46e42aa..3efae07 100644 --- a/src/SignIn.js +++ b/src/SignIn.js @@ -98,11 +98,11 @@ class SignIn extends React.Component { return ( <Container> - <Row className="justify-content-md-center"> + <Row className="justify-content-center"> <img src={logo} alt="Garbanzo Negro" /> </Row> {alert} - <Row className="justify-content-md-center"> + <Row className="justify-content-center"> {form} </Row> </Container> -- GitLab