Newer
Older
import React, { useEffect, useState } from "react";
import axios from "axios";
import { jwtDecode } from "jwt-decode";
const [username, setUsername] = useState("");
const [privilege, setPrivilege] = useState("");
const [protectedData, setProtectedData] = useState(null);
const [unprotectedData, setUnprotectedData] = useState(null);
Federico Hurtado
committed
const extractTokenFromUrl = () => {
const params = new URLSearchParams(window.location.search);
const token = params.get("token");
Federico Hurtado
committed
// no token found
if (!token) {
Federico Hurtado
committed
console.log("No token found in URL");
return;
}
Federico Hurtado
committed
// decode the token and set the user info
try {
const decoded = jwtDecode(token);
setUsername(decoded.username);
setPrivilege(decoded.role);
} catch (error) {
console.error("Error decoding token: ", error);
}
};
// function to make call to unprotected backend endpoint
const fetchUnprotectedData = async () => {
// since the endpoint is unprotected, do not need token
// this would be for all guest methods (search, login, etc)
try {
const response = await axios.get(
`${process.env.REACT_APP_API_URL}/user/public`
);
setUnprotectedData(response.data);
} catch (error) {
console.error("error fetching public endpoint: ", error);
}
};
const fetchProtectedData = async () => {
Federico Hurtado
committed
// get the token from the URL
const params = new URLSearchParams(window.location.search);
const token = params.get("token");
Federico Hurtado
committed
// no token found, return early
if (!token) {
console.error("no token found. ");
return;
}
Federico Hurtado
committed
// try calling method that needs JWT token in the backend with
// admin privilages to work
try {
const response = await axios.get(
Federico Hurtado
committed
`${process.env.REACT_APP_API_URL}/user/admin`,
{
headers: {
Authorization: `Bearer ${token}`,
},
}
);
setProtectedData(response.data);
} catch (error) {
console.error("Error fetching protected data: ", error);
}
};
// Fetch data on component mount
useEffect(() => {
Federico Hurtado
committed
extractTokenFromUrl();
fetchUnprotectedData();
}, []);
<h1>Welcome to the Practice Home Page</h1>
{/* Display user information from the decoded token */}
{username && (
<div>
<h2>User Info</h2>
<p>Username: {username}</p>
<p>Privilege: {privilege}</p>
</div>
<div>
<h2>Unprotected API Data</h2>
<button onClick={fetchUnprotectedData}>Fetch Unprotected Data</button>
{unprotectedData && (
<pre>{JSON.stringify(unprotectedData, null, 2)}</pre>
)}
</div>
<div>
<h2>Protected API Data</h2>
<button onClick={fetchProtectedData}>Fetch Protected Data</button>
{protectedData && <pre>{JSON.stringify(protectedData, null, 2)}</pre>}
</div>
</div>
);
}
export default PracticeHome;