2023-10-07 15:32:11 +00:00
|
|
|
import React from "react";
|
|
|
|
|
|
|
|
export type Session = string;
|
2023-10-09 12:55:16 +00:00
|
|
|
export const LumeIdentityContext = React.createContext<
|
|
|
|
| {
|
|
|
|
session: Session | undefined;
|
|
|
|
setSession: React.Dispatch<React.SetStateAction<Session | undefined>>;
|
|
|
|
}
|
|
|
|
| undefined
|
|
|
|
>(undefined);
|
2023-10-07 15:32:11 +00:00
|
|
|
export function useLumeIndentity() {
|
|
|
|
const contextValue = React.useContext(LumeIdentityContext);
|
|
|
|
|
|
|
|
// When the `session` changes we want to update the `session` in the local storage?
|
|
|
|
React.useEffect(() => {
|
|
|
|
if (contextValue?.session) {
|
2023-10-09 12:55:16 +00:00
|
|
|
localStorage.setItem("lume-session", contextValue.session);
|
2023-10-07 15:32:11 +00:00
|
|
|
} else {
|
2023-10-09 12:55:16 +00:00
|
|
|
localStorage.removeItem("lume-session");
|
2023-10-07 15:32:11 +00:00
|
|
|
}
|
|
|
|
}, [contextValue?.session]);
|
|
|
|
|
|
|
|
// Get the session from the local storage
|
|
|
|
React.useEffect(() => {
|
2023-10-09 12:55:16 +00:00
|
|
|
const session = localStorage.getItem("lume-session");
|
2023-10-07 15:32:11 +00:00
|
|
|
if (session) {
|
|
|
|
contextValue?.setSession(session);
|
|
|
|
}
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
if (contextValue === undefined) {
|
2023-10-09 12:55:16 +00:00
|
|
|
throw new Error(
|
|
|
|
"useLumeIdentity hook is being used outside of its context. Please ensure that it is wrapped within a <LumeIdentityProvider>."
|
|
|
|
);
|
2023-10-07 15:32:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
isSignedIn: !!contextValue.session,
|
|
|
|
signIn: (key: string) => {
|
2023-10-09 12:55:16 +00:00
|
|
|
console.log("signing in with key", key);
|
2023-10-07 15:32:11 +00:00
|
|
|
// TODO: From the key generate a session, and store it
|
2023-10-09 12:55:16 +00:00
|
|
|
contextValue.setSession("session");
|
2023-10-07 15:32:11 +00:00
|
|
|
},
|
|
|
|
signOut: () => {
|
|
|
|
contextValue.setSession(undefined);
|
|
|
|
},
|
|
|
|
};
|
2023-10-09 12:55:16 +00:00
|
|
|
}
|