Skip to content

Commit

Permalink
chore: add token expiry time to demo
Browse files Browse the repository at this point in the history
Signed-off-by: Vaibhav Upreti <[email protected]>
  • Loading branch information
VaibhavUpreti committed Dec 31, 2024
1 parent 351fd92 commit 625b0ed
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions demo/react-spa-demo/src/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ function App() {
const [userInfo, setUserInfo] = useState(null);
const [authToken, setAuthToken] = useState(null);
const [refreshMessage, setRefreshMessage] = useState(""); // State to show refresh token message
const [expiresIn, setExpiresIn] = useState(null); // State to display the expires_in time

const oauthClient = new OAuthClient(config);

Expand All @@ -43,6 +44,14 @@ function App() {
if (refreshedToken) {
setAuthToken(refreshedToken);
setRefreshMessage("Token successfully refreshed!");

// Save the new token and its expiration time in localStorage
const expirationTime = new Date().getTime() + refreshedToken.expires_in * 1000; // Convert seconds to milliseconds
localStorage.setItem("authToken", JSON.stringify(refreshedToken));
localStorage.setItem("tokenExpiration", expirationTime.toString());

// Update the expiresIn state
setExpiresIn(refreshedToken.expires_in);
} else {
setRefreshMessage("Failed to refresh token.");
}
Expand All @@ -58,6 +67,22 @@ function App() {
setUserInfo(JSON.parse(storedUser));
}

// Check for the stored token and its expiration time
const storedToken = localStorage.getItem("authToken");
const storedExpiration = localStorage.getItem("tokenExpiration");

if (storedToken && storedExpiration) {
const currentTime = new Date().getTime();
if (currentTime < storedExpiration) {
setAuthToken(JSON.parse(storedToken));
setExpiresIn((storedExpiration - currentTime) / 1000); // Convert ms to seconds
} else {
// Token expired, clear from localStorage
localStorage.removeItem("authToken");
localStorage.removeItem("tokenExpiration");
}
}

// Handle the OAuth callback after redirect with code in URL
const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get("code");
Expand Down Expand Up @@ -162,6 +187,13 @@ function App() {
{refreshMessage}
</p>
)}

{/* Display expires in time */}
{expiresIn && (
<p style={{ marginTop: "15px", fontSize: "14px", color: "#7f8c8d" }}>
Token expires in {expiresIn} seconds.
</p>
)}
</div>

<p className="read-the-docs" style={{ marginTop: "20px", fontSize: "14px", color: "#7f8c8d" }}>
Expand Down

0 comments on commit 625b0ed

Please sign in to comment.