VirgilSecurity / virgil-e3kit-js

E3Kit is a security framework that simplifies work with Virgil services and presents the easiest way to add full end-to-end security to your chat application to become HIPAA and GDPR compliant and more.
https://virgilsecurity.com/e3kit/
BSD 3-Clause "New" or "Revised" License
58 stars 19 forks source link

KeyEntryAlreadyExistsError: Key entry named RoSvYoIKEMM6NoecPtv0SQK0uWD3already exists #144

Closed berbaroovez closed 1 year ago

berbaroovez commented 3 years ago

I keep getting this error and the one about multiple cards am i doing something wrong in my code?

I'm using firebase


import Router from "next/router";
import firebase from "./firebase";
import { createUser, getUserInfo } from "./db";
import { EThree } from "@virgilsecurity/e3kit-browser";
const authContext = createContext();

export function AuthProvider({ children }) {
  const auth = useProvideAuth();
  return <authContext.Provider value={auth}>{children}</authContext.Provider>;
}

export const useAuth = () => {
  return useContext(authContext);
};

//A lot of the problems in this are file are due to the component being updated which causes things to lose state
// I either need to save all info passed in state right away or find the piece that is updating the component

function useProvideAuth() {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  const [eThreeToken, seteThreeToken] = useState(null);

  const [backupkeyState, setBackupkeyState] = useState("");
  const [signingIn, setSigningIn] = useState(false);
  const [signingUp, setSigningUp] = useState(false);
  const [wantsAdmin, setWantsAdmin] = useState(false);
  const [adminIDKey, setAdminIDKey] = useState("");

  //we send in the raw data from signing in, up, or out and we can also send what part of the flow where
  //in with the same values "signin" | "signup" | "signout"

  const handleUser = (user) => {
    if (user) {
      console.log("THIS USER IS SIGNEDIN", user);
      console.log(user.schoolID);
      setUser(user);
    } else {
      console.log("NO USER SIGNED IN");
      if (eThreeToken) {
        eThreeToken
          .cleanup()
          .then(() => console.log("so-successfly cleared token"))
          .catch((e) => console.error("so-error: ", e));
      }
      seteThreeToken(null);
    }
  };
  const signinWithEmail = (email, password, backupkey) => {
    setBackupkeyState(backupkey);
    setLoading(true);
    setSigningIn(true);
    return firebase
      .auth()
      .signInWithEmailAndPassword(email, password)
      .then((response) => {
        console.log("Sign in function");
        const { schoolID, name } = getUserInfo(email);

        setUser({ ...response.user, schoolID, name });
      });
  };

  const AdminSignUp = (email, password, name, schoolID, backupkey, adminID) => {
    setBackupkeyState(backupkey);
    setWantsAdmin(true);
    setAdminIDKey(adminID);
    setLoading(true);
    console.log(`Admin signup with email ${email}`);
    return firebase
      .auth()
      .createUserWithEmailAndPassword(email, password)
      .then((response) => {
        console.log("Creating an admin");
        setUser({ ...response.user, schoolID, name });
      });
  };

  const signupWithEmail = (email, password, schoolID, name, backupkey) => {
    setBackupkeyState(backupkey);
    console.log("School ID", schoolID);
    setSigningUp(true);
    setLoading(true);
    return firebase
      .auth()
      .createUserWithEmailAndPassword(email, password)
      .then(async (response) => {
        createUser({
          email: response.user.email,
          name,
          schoolID,
          UID: response.user.uid,
        });
        setUser({ ...response.user, schoolID });
        // handleUser({ ...response.user, schoolID, name, backupkey }, "signup");

        // Router.push("/dashboard");
      });
  };

  const signout = () => {
    return firebase
      .auth()
      .signOut()
      .then(() => {
        if (eThreeToken) {
          eThreeToken
            .cleanup()
            .then(() => console.log("so-successfly cleared token"))
            .catch((e) => console.error("so-error: ", e));
        }
        seteThreeToken(null);
        setUser(null);
      });
  };

  useEffect(() => {
    const unsubscribe = firebase.auth().onIdTokenChanged(handleUser);
    return () => unsubscribe();
  }, []);

  useEffect(() => {
    console.log("USER UPDATED--------------------", user);
    if (user) {
      if (!eThreeToken) {
        const getToken = firebase.functions().httpsCallable("getVirgilJwt");
        const initializeFunction = () =>
          getToken().then((result) => result.data.token);

        console.log("Get Token TEST", getToken);

        EThree.initialize(initializeFunction)
          .then((eThree) => {
            console.log("se3-eThree initialized", eThree);

            seteThreeToken(eThree);
          })
          .catch((error) => {
            // Error handling
            const code = error.code;
            console.log("se3-Error: ", error);
          });
      }
    }
  }, [user]);

  useEffect(() => {
    const ethreeChecks = async () => {
      if (eThreeToken) {
        if (signingIn) {
          //check to see if user already has a local private key
          console.log("se3-signing in");
          const hasLocalPrivateKey = await eThreeToken.hasLocalPrivateKey();
          try {
            if (!hasLocalPrivateKey) {
              console.log("se3-Does not have private key restoring now: ");
              await eThreeToken.restorePrivateKey(backupkeyState);
            } else {
              console.log("se3-Does have private key");
            }
          } catch (e) {
            firebase.auth().signOut();
            // throw e;
          }
        } else if (signingUp) {
          console.log("se3-signing up");
          try {
            await eThreeToken.register();
            await eThreeToken.backupPrivateKey(backupkeyState);
          } catch (error) {
            console.error(error);
            // throw error;
          }
        } else {
          console.log("se3-ELSE");
          try {
            await eThreeToken.register();
            await eThreeToken.backupPrivateKey(backupkeyState);
          } catch (error) {
            console.error(error);
            // throw error;
          }
        }
      }
    };

    ethreeChecks();
  }, [eThreeToken]);
  return {
    user,
    loading,
    signinWithEmail,
    signout,
    signupWithEmail,
    eThreeToken,
    AdminSignUp,
  };
}
``
rstp-god commented 1 year ago

Closing as outdated