UNPKG

@nerdlat/auth

Version:

Authentication library similar to Clerk for React and Express applications

57 lines (56 loc) 2.02 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.AuthContext = void 0; exports.AuthProvider = AuthProvider; exports.withAuth = withAuth; const jsx_runtime_1 = require("react/jsx-runtime"); // src/client/AuthProvider.tsx const react_1 = require("react"); const authApi_1 = require("./authApi"); exports.AuthContext = (0, react_1.createContext)(null); function AuthProvider({ children, fallback }) { const [user, setUser] = (0, react_1.useState)(null); const [isLoading, setIsLoading] = (0, react_1.useState)(true); (0, react_1.useEffect)(() => { const checkAuth = async () => { try { const userData = await (0, authApi_1.getMe)(); setUser(userData); } catch (error) { setUser(null); } finally { setIsLoading(false); } }; checkAuth(); }, []); const contextValue = { user, setUser, isLoading, isSignedIn: !!user }; if (isLoading && fallback) { return (0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: fallback }); } return ((0, jsx_runtime_1.jsx)(exports.AuthContext.Provider, { value: contextValue, children: children })); } // HOC para proteger rutas function withAuth(Component) { return function AuthenticatedComponent(props) { const context = (0, react_1.useContext)(exports.AuthContext); if (!context) { throw new Error('withAuth must be used within an AuthProvider'); } const { isLoading, isSignedIn } = context; if (isLoading) { return (0, jsx_runtime_1.jsx)("div", { children: "Loading..." }); // O tu componente de loading } if (!isSignedIn) { return (0, jsx_runtime_1.jsx)("div", { children: "Please sign in to access this page" }); // O redireccionar } return (0, jsx_runtime_1.jsx)(Component, { ...props }); }; }