useAuthWindow.ts 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import { useEffect, useState } from "react";
  2. /**
  3. * Hook to open an authentication window at a given url.
  4. * Once the auth flow redirects back to Porter, the window is closed.
  5. */
  6. export const useAuthWindow = ({
  7. authUrl,
  8. }: {
  9. authUrl: string;
  10. }): {
  11. openAuthWindow: () => void;
  12. } => {
  13. const [authWindow, setAuthWindow] = useState<Window | null>(null);
  14. const openAuthWindow = (): void => {
  15. const windowObjectReference = window.open(
  16. authUrl,
  17. "porterAuthWindow",
  18. "width=600,height=700,left=200,top=200"
  19. );
  20. setAuthWindow(windowObjectReference);
  21. };
  22. useEffect(() => {
  23. const interval = setInterval(() => {
  24. if (authWindow) {
  25. try {
  26. if (
  27. authWindow.location.hostname.includes("dashboard.getporter.dev") ||
  28. authWindow.location.hostname.includes("cloud.porter.run") ||
  29. authWindow.location.hostname.includes("localhost")
  30. ) {
  31. authWindow.close();
  32. setAuthWindow(null);
  33. clearInterval(interval);
  34. }
  35. } catch (e) {
  36. console.log("Error accessing the authentication window.", e);
  37. }
  38. }
  39. }, 1000);
  40. return () => {
  41. clearInterval(interval);
  42. if (authWindow) {
  43. authWindow.close();
  44. }
  45. };
  46. }, [authWindow]);
  47. return { openAuthWindow };
  48. };