Typescript React - authentication fails

53 Views Asked by At

Authentication to my application fails which result in not being able to login to my API. I have narrowed the errors down to two files but I can't find the problem.

Authentication happens in useAuthApi.js:

import { useCallback } from "react";
import { useAuthContext } from "../../components/App/Auth/AuthProvider";
import ApiError from "../error/ApiError";
import AppError from "../error/AppError";
import { handleErrors } from "../helpers/api";

const useAuthApi = () => {
  const { auth, logout } = useAuthContext();

  const authFetch = useCallback(
    (url, config = {}) => {
      // add authorization header
      // hier zit een fout!!!!
      console.log("test")
      console.log(auth)
      if (auth && auth.token) {
        config.headers = {
          ...(config.headers || {}),
          Authorization: `Bearer ${auth.token}`,
        };
      console.log("url: " + url + " config: " + JSON.stringify(config))

      }

      return fetch(url, config)
        .then(handleErrors)
        .catch((error) => {
          if (error instanceof ApiError) {
            if (error.isUnauthorized()) {
              logout();
            }
            throw error;
          } else {
            throw new AppError(error);
          }
        });
    },
    [logout, auth]
  );

  return {
    authFetch,
  };
};

export default useAuthApi;

This code does add "test" to my console, so I do get into my authFetch function. However it doesn't get any auth back from my AuthContext, which is called from AuthProvider.js:

import { createContext, useContext, useEffect, useState } from "react";

const KEY = "VLOT_TAALPORTFOLIO_AUTH";

const AuthContext = createContext();

const getAuthFromStorage = () => {
  console.log("getauthfromstorage")
  const auth = localStorage.getItem(KEY);
  if (auth) {
    // base64 encode
    return JSON.parse(atob(auth));
  }
  return null;
};

const saveAuthToStorage = (auth) => {
  // base67 encode
  localStorage.setItem(KEY, btoa(JSON.stringify(auth)));
};

// This is a provider that will be keeping track of the current user
const AuthProvider = ({ children }) => {
  const [auth, setAuth] = useState(getAuthFromStorage());

  useEffect(() => {
    if (auth) {
      saveAuthToStorage(auth);
    } else {
      localStorage.removeItem(KEY);
    }
  }, [auth]);

  const handleLogout = () => {
    setAuth(null);
  };

  const handleLogin = (auth) => {
    setAuth(auth);
  };

  return (
    <AuthContext.Provider
      value={{ auth, login: handleLogin, logout: handleLogout }}
    >
      {children}
    </AuthContext.Provider>
  );
};

export const useAuthContext = () => {
  return useContext(AuthContext);
};

export const useUser = () => {
  const { auth } = useAuthContext();
  return auth?.user;
};

export default AuthProvider;

Any help on what to add in my AuthProvider to get this working? I have been breaking my head over this a couple of days.

0

There are 0 best solutions below