Skip to content
Snippets Groups Projects
PracticeHome.js 2.96 KiB
Newer Older
import React, { useEffect, useState } from "react";
import axios from "axios";
import { jwtDecode } from "jwt-decode";

function PracticeHome() {
  const [username, setUsername] = useState("");
  const [privilege, setPrivilege] = useState("");
  const [protectedData, setProtectedData] = useState(null);
  const [unprotectedData, setUnprotectedData] = useState(null);

  const extractTokenFromUrl = () => {
    const params = new URLSearchParams(window.location.search);
    const token = params.get("token");
      console.log("No token found in URL");
    // 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 () => {
    // get the token from the URL
    const params = new URLSearchParams(window.location.search);
    const token = params.get("token");
    if (!token) {
      console.error("no token found. ");
      return;
    }

    // try calling method that needs JWT token in the backend with
    // admin privilages to work
    try {
      const response = await axios.get(
        `${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(() => {
      <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;