(WrappedComponent: React.ComponentType<P>)
| 50 | * export default WithAuth(MyComponent); |
| 51 | */ |
| 52 | const WithAuth = <P extends WithAuthProps>(WrappedComponent: React.ComponentType<P>) => { |
| 53 | return (props: Omit<P, keyof WithAuthProps>) => { |
| 54 | const { isAuthenticated } = useAuthState(); |
| 55 | const [showAuthModal, setShowAuthModal] = React.useState(false); |
| 56 | const [redirectUrl, setRedirectUrl] = React.useState<RedirectUrl>({ |
| 57 | pathname: '/', |
| 58 | }); // The URL to redirect to after the user logs in |
| 59 | |
| 60 | /** Function to call when the user tries to perform an action that requires authentication |
| 61 | * This function should be called before the action that requires authentication is performed and will throw an error if the user is not authenticated |
| 62 | * |
| 63 | * @param redirectUrl - The URL to redirect to after the user logs in |
| 64 | * |
| 65 | * @throws {UserNotLoggedInError} - If the user is not authenticated |
| 66 | * |
| 67 | * @example |
| 68 | * const handleSaveGraph = () => { |
| 69 | * handleActionRequiringAuth({ |
| 70 | * pathname: 'graph', |
| 71 | * queryParams: { |
| 72 | * save_graph: "true" |
| 73 | * } |
| 74 | * }); |
| 75 | * |
| 76 | * // Save the graph |
| 77 | * // This code will only be executed if the user is authenticated |
| 78 | * saveGraph(); |
| 79 | * }; |
| 80 | */ |
| 81 | const handleActionRequiringAuth = (redirectUrl: RedirectUrl) => { |
| 82 | if (!isAuthenticated) { |
| 83 | setShowAuthModal(true); |
| 84 | setRedirectUrl(redirectUrl); |
| 85 | throw new UserNotLoggedInError("User is not logged in"); |
| 86 | } |
| 87 | }; |
| 88 | |
| 89 | return ( |
| 90 | <> |
| 91 | <WrappedComponent {...(props as P)} handleActionRequiringAuth={handleActionRequiringAuth} /> |
| 92 | { |
| 93 | showAuthModal && |
| 94 | <AuthDialog isOpen={showAuthModal} setIsOpen={setShowAuthModal} redirectUrl={redirectUrl} /> |
| 95 | } |
| 96 | </> |
| 97 | ); |
| 98 | }; |
| 99 | }; |
| 100 | |
| 101 | export default WithAuth; |
no test coverage detected