analytica-frontend-lib 1.3.4 → 1.3.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Auth/AuthProvider/index.d.ts +7 -2
- package/dist/Auth/AuthProvider/index.d.ts.map +1 -1
- package/dist/Auth/AuthProvider/index.js +35 -13
- package/dist/Auth/AuthProvider/index.js.map +1 -1
- package/dist/Auth/AuthProvider/index.mjs +27 -5
- package/dist/Auth/AuthProvider/index.mjs.map +1 -1
- package/dist/Auth/ProtectedRoute/index.d.ts +7 -2
- package/dist/Auth/ProtectedRoute/index.d.ts.map +1 -1
- package/dist/Auth/ProtectedRoute/index.js +35 -13
- package/dist/Auth/ProtectedRoute/index.js.map +1 -1
- package/dist/Auth/ProtectedRoute/index.mjs +27 -5
- package/dist/Auth/ProtectedRoute/index.mjs.map +1 -1
- package/dist/Auth/PublicRoute/index.d.ts +7 -2
- package/dist/Auth/PublicRoute/index.d.ts.map +1 -1
- package/dist/Auth/PublicRoute/index.js +35 -13
- package/dist/Auth/PublicRoute/index.js.map +1 -1
- package/dist/Auth/PublicRoute/index.mjs +27 -5
- package/dist/Auth/PublicRoute/index.mjs.map +1 -1
- package/dist/Auth/getRootDomain/index.d.ts +7 -2
- package/dist/Auth/getRootDomain/index.d.ts.map +1 -1
- package/dist/Auth/getRootDomain/index.js +35 -13
- package/dist/Auth/getRootDomain/index.js.map +1 -1
- package/dist/Auth/getRootDomain/index.mjs +27 -5
- package/dist/Auth/getRootDomain/index.mjs.map +1 -1
- package/dist/Auth/index.d.ts +7 -2
- package/dist/Auth/index.d.ts.map +1 -1
- package/dist/Auth/index.js +35 -13
- package/dist/Auth/index.js.map +1 -1
- package/dist/Auth/index.mjs +27 -5
- package/dist/Auth/index.mjs.map +1 -1
- package/dist/Auth/useAuth/index.d.ts +7 -2
- package/dist/Auth/useAuth/index.d.ts.map +1 -1
- package/dist/Auth/useAuth/index.js +35 -13
- package/dist/Auth/useAuth/index.js.map +1 -1
- package/dist/Auth/useAuth/index.mjs +27 -5
- package/dist/Auth/useAuth/index.mjs.map +1 -1
- package/dist/Auth/useAuthGuard/index.d.ts +7 -2
- package/dist/Auth/useAuthGuard/index.d.ts.map +1 -1
- package/dist/Auth/useAuthGuard/index.js +35 -13
- package/dist/Auth/useAuthGuard/index.js.map +1 -1
- package/dist/Auth/useAuthGuard/index.mjs +27 -5
- package/dist/Auth/useAuthGuard/index.mjs.map +1 -1
- package/dist/Auth/useRouteAuth/index.d.ts +7 -2
- package/dist/Auth/useRouteAuth/index.d.ts.map +1 -1
- package/dist/Auth/useRouteAuth/index.js +35 -13
- package/dist/Auth/useRouteAuth/index.js.map +1 -1
- package/dist/Auth/useRouteAuth/index.mjs +27 -5
- package/dist/Auth/useRouteAuth/index.mjs.map +1 -1
- package/dist/Auth/withAuth/index.d.ts +7 -2
- package/dist/Auth/withAuth/index.d.ts.map +1 -1
- package/dist/Auth/withAuth/index.js +35 -13
- package/dist/Auth/withAuth/index.js.map +1 -1
- package/dist/Auth/withAuth/index.mjs +27 -5
- package/dist/Auth/withAuth/index.mjs.map +1 -1
- package/dist/StudentLessonProgressModal/index.d.ts +1 -1
- package/dist/StudentLessonProgressModal/index.d.ts.map +1 -1
- package/dist/StudentLessonProgressModal/index.js +114 -44
- package/dist/StudentLessonProgressModal/index.js.map +1 -1
- package/dist/StudentLessonProgressModal/index.mjs +114 -44
- package/dist/StudentLessonProgressModal/index.mjs.map +1 -1
- package/dist/hooks/useSupportFeatureFlag.d.ts.map +1 -1
- package/dist/index.d.ts +6 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1557 -1380
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1262 -1088
- package/dist/index.mjs.map +1 -1
- package/package.json +3 -1
|
@@ -189,6 +189,7 @@ export declare const ProtectedRoute: ({ children, redirectTo, loadingComponent,
|
|
|
189
189
|
* @property {string} [redirectTo] - Path to redirect to (default: '/painel')
|
|
190
190
|
* @property {boolean} [redirectIfAuthenticated] - Whether to redirect if authenticated
|
|
191
191
|
* @property {boolean} [checkAuthBeforeRender] - Whether to check auth before rendering
|
|
192
|
+
* @property {ReactNode} [tokenValidationComponent] - Component to show while validating tokens from URL
|
|
192
193
|
*/
|
|
193
194
|
export interface PublicRouteProps {
|
|
194
195
|
children: ReactNode;
|
|
@@ -204,6 +205,10 @@ export interface PublicRouteProps {
|
|
|
204
205
|
* Se deve verificar autenticação antes de renderizar
|
|
205
206
|
*/
|
|
206
207
|
checkAuthBeforeRender?: boolean;
|
|
208
|
+
/**
|
|
209
|
+
* Componente a ser exibido enquanto valida tokens da URL
|
|
210
|
+
*/
|
|
211
|
+
tokenValidationComponent?: ReactNode;
|
|
207
212
|
}
|
|
208
213
|
/**
|
|
209
214
|
* Componente para rotas públicas (login, recuperação de senha, etc.)
|
|
@@ -216,7 +221,7 @@ export interface PublicRouteProps {
|
|
|
216
221
|
* </PublicRoute>
|
|
217
222
|
* ```
|
|
218
223
|
*/
|
|
219
|
-
export declare const PublicRoute: ({ children, redirectTo, redirectIfAuthenticated, checkAuthBeforeRender, }: PublicRouteProps) => import("react/jsx-runtime").JSX.Element;
|
|
224
|
+
export declare const PublicRoute: ({ children, redirectTo, redirectIfAuthenticated, checkAuthBeforeRender, tokenValidationComponent, }: PublicRouteProps) => import("react/jsx-runtime").JSX.Element;
|
|
220
225
|
/**
|
|
221
226
|
* Higher-Order Component to protect components with authentication
|
|
222
227
|
*
|
|
@@ -303,7 +308,7 @@ export declare const getRootDomain: () => string;
|
|
|
303
308
|
declare const _default: {
|
|
304
309
|
AuthProvider: ({ children, checkAuthFn, signOutFn, initialAuthState, getUserFn, getSessionFn, getTokensFn, }: AuthProviderProps) => import("react/jsx-runtime").JSX.Element;
|
|
305
310
|
ProtectedRoute: ({ children, redirectTo, loadingComponent, additionalCheck, }: ProtectedRouteProps) => import("react/jsx-runtime").JSX.Element | null;
|
|
306
|
-
PublicRoute: ({ children, redirectTo, redirectIfAuthenticated, checkAuthBeforeRender, }: PublicRouteProps) => import("react/jsx-runtime").JSX.Element;
|
|
311
|
+
PublicRoute: ({ children, redirectTo, redirectIfAuthenticated, checkAuthBeforeRender, tokenValidationComponent, }: PublicRouteProps) => import("react/jsx-runtime").JSX.Element;
|
|
307
312
|
withAuth: <P extends object>(Component: ComponentType<P>, options?: Omit<ProtectedRouteProps, "children">) => (props: P) => import("react/jsx-runtime").JSX.Element;
|
|
308
313
|
useAuth: () => AuthContextType;
|
|
309
314
|
useAuthGuard: (options?: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Auth.d.ts","sourceRoot":"","sources":["../../../src/components/Auth/Auth.tsx"],"names":[],"mappings":"AAAA,OAAO,EAKL,SAAS,EACT,aAAa,EAGd,MAAM,OAAO,CAAC;
|
|
1
|
+
{"version":3,"file":"Auth.d.ts","sourceRoot":"","sources":["../../../src/components/Auth/Auth.tsx"],"names":[],"mappings":"AAAA,OAAO,EAKL,SAAS,EACT,aAAa,EAGd,MAAM,OAAO,CAAC;AAIf;;;;;;;GAOG;AACH,MAAM,WAAW,UAAU;IACzB,KAAK,EAAE,MAAM,CAAC;IACd,YAAY,EAAE,MAAM,CAAC;IACrB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB;AAED;;;;;;;;GAQG;AACH,MAAM,WAAW,QAAQ;IACvB,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB;AAED;;;;;;;;;;GAUG;AACH,MAAM,WAAW,WAAW;IAC1B,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,CAAC,GAAG,EAAE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5B,aAAa,CAAC,CAAC,CAAC,YAClB,IAAI,CAAC,mBAAmB,EAAE,UAAU,CAAC,MAEtC,OAAO,CAAC;mBArLS,eAAe;6BA6M/B;QACP,WAAW,CAAC,EAAE,OAAO,CAAC;QACtB,WAAW,CAAC,EAAE,CAAC,SAAS,EAAE,SAAS,KAAK,OAAO,CAAC;KACjD;;;;;;;;;;;AAgHH,wBAQE"}
|
|
@@ -31,10 +31,27 @@ __export(Auth_exports, {
|
|
|
31
31
|
withAuth: () => withAuth
|
|
32
32
|
});
|
|
33
33
|
module.exports = __toCommonJS(Auth_exports);
|
|
34
|
+
var import_react2 = require("react");
|
|
35
|
+
var import_react_router_dom2 = require("react-router-dom");
|
|
36
|
+
|
|
37
|
+
// src/components/Auth/useTokenInUrl.ts
|
|
34
38
|
var import_react = require("react");
|
|
35
39
|
var import_react_router_dom = require("react-router-dom");
|
|
40
|
+
function useTokenInUrl() {
|
|
41
|
+
const location = (0, import_react_router_dom.useLocation)();
|
|
42
|
+
const hasTokenInUrl = (0, import_react.useMemo)(() => {
|
|
43
|
+
const searchParams = new URLSearchParams(location.search);
|
|
44
|
+
const token = searchParams.get("token");
|
|
45
|
+
const refreshToken = searchParams.get("refreshToken");
|
|
46
|
+
const sessionId = searchParams.get("sessionId");
|
|
47
|
+
return !!(token && refreshToken && sessionId);
|
|
48
|
+
}, [location.search]);
|
|
49
|
+
return { hasTokenInUrl };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// src/components/Auth/Auth.tsx
|
|
36
53
|
var import_jsx_runtime = require("react/jsx-runtime");
|
|
37
|
-
var AuthContext = (0,
|
|
54
|
+
var AuthContext = (0, import_react2.createContext)(void 0);
|
|
38
55
|
var AuthProvider = ({
|
|
39
56
|
children,
|
|
40
57
|
checkAuthFn,
|
|
@@ -44,12 +61,12 @@ var AuthProvider = ({
|
|
|
44
61
|
getSessionFn,
|
|
45
62
|
getTokensFn
|
|
46
63
|
}) => {
|
|
47
|
-
const [authState, setAuthState] = (0,
|
|
64
|
+
const [authState, setAuthState] = (0, import_react2.useState)({
|
|
48
65
|
isAuthenticated: false,
|
|
49
66
|
isLoading: true,
|
|
50
67
|
...initialAuthState
|
|
51
68
|
});
|
|
52
|
-
const checkAuth = (0,
|
|
69
|
+
const checkAuth = (0, import_react2.useCallback)(async () => {
|
|
53
70
|
try {
|
|
54
71
|
setAuthState((prev) => ({ ...prev, isLoading: true }));
|
|
55
72
|
if (!checkAuthFn) {
|
|
@@ -80,7 +97,7 @@ var AuthProvider = ({
|
|
|
80
97
|
return false;
|
|
81
98
|
}
|
|
82
99
|
}, [checkAuthFn, getUserFn, getSessionFn, getTokensFn]);
|
|
83
|
-
const signOut = (0,
|
|
100
|
+
const signOut = (0, import_react2.useCallback)(() => {
|
|
84
101
|
if (signOutFn) {
|
|
85
102
|
signOutFn();
|
|
86
103
|
}
|
|
@@ -92,10 +109,10 @@ var AuthProvider = ({
|
|
|
92
109
|
tokens: void 0
|
|
93
110
|
}));
|
|
94
111
|
}, [signOutFn]);
|
|
95
|
-
(0,
|
|
112
|
+
(0, import_react2.useEffect)(() => {
|
|
96
113
|
checkAuth();
|
|
97
114
|
}, [checkAuth]);
|
|
98
|
-
const contextValue = (0,
|
|
115
|
+
const contextValue = (0, import_react2.useMemo)(
|
|
99
116
|
() => ({
|
|
100
117
|
...authState,
|
|
101
118
|
checkAuth,
|
|
@@ -106,7 +123,7 @@ var AuthProvider = ({
|
|
|
106
123
|
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AuthContext.Provider, { value: contextValue, children });
|
|
107
124
|
};
|
|
108
125
|
var useAuth = () => {
|
|
109
|
-
const context = (0,
|
|
126
|
+
const context = (0, import_react2.useContext)(AuthContext);
|
|
110
127
|
if (context === void 0) {
|
|
111
128
|
throw new Error("useAuth deve ser usado dentro de um AuthProvider");
|
|
112
129
|
}
|
|
@@ -132,10 +149,10 @@ var ProtectedRoute = ({
|
|
|
132
149
|
return null;
|
|
133
150
|
}
|
|
134
151
|
}
|
|
135
|
-
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
|
|
152
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_router_dom2.Navigate, { to: redirectTo, replace: true });
|
|
136
153
|
}
|
|
137
154
|
if (additionalCheck && !additionalCheck({ isAuthenticated, isLoading, ...authState })) {
|
|
138
|
-
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
|
|
155
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_router_dom2.Navigate, { to: redirectTo, replace: true });
|
|
139
156
|
}
|
|
140
157
|
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, { children });
|
|
141
158
|
};
|
|
@@ -143,14 +160,19 @@ var PublicRoute = ({
|
|
|
143
160
|
children,
|
|
144
161
|
redirectTo = "/painel",
|
|
145
162
|
redirectIfAuthenticated = false,
|
|
146
|
-
checkAuthBeforeRender = false
|
|
163
|
+
checkAuthBeforeRender = false,
|
|
164
|
+
tokenValidationComponent
|
|
147
165
|
}) => {
|
|
148
166
|
const { isAuthenticated, isLoading } = useAuth();
|
|
167
|
+
const { hasTokenInUrl } = useTokenInUrl();
|
|
168
|
+
if (hasTokenInUrl && tokenValidationComponent) {
|
|
169
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, { children: tokenValidationComponent });
|
|
170
|
+
}
|
|
149
171
|
if (checkAuthBeforeRender && isLoading) {
|
|
150
172
|
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "flex items-center justify-center min-h-screen", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "text-text-950 text-lg", children: "Carregando..." }) });
|
|
151
173
|
}
|
|
152
174
|
if (isAuthenticated && redirectIfAuthenticated) {
|
|
153
|
-
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
|
|
175
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_router_dom2.Navigate, { to: redirectTo, replace: true });
|
|
154
176
|
}
|
|
155
177
|
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, { children });
|
|
156
178
|
};
|
|
@@ -169,8 +191,8 @@ var useAuthGuard = (options = {}) => {
|
|
|
169
191
|
};
|
|
170
192
|
var useRouteAuth = (fallbackPath = "/") => {
|
|
171
193
|
const { isAuthenticated, isLoading } = useAuth();
|
|
172
|
-
const location = (0,
|
|
173
|
-
const redirectToLogin = () => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
|
|
194
|
+
const location = (0, import_react_router_dom2.useLocation)();
|
|
195
|
+
const redirectToLogin = () => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_router_dom2.Navigate, { to: fallbackPath, state: { from: location }, replace: true });
|
|
174
196
|
return {
|
|
175
197
|
isAuthenticated,
|
|
176
198
|
isLoading,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/components/Auth/Auth.tsx"],"sourcesContent":["import {\n createContext,\n useContext,\n useEffect,\n useState,\n ReactNode,\n ComponentType,\n useCallback,\n useMemo,\n} from 'react';\nimport { useLocation, Navigate } from 'react-router-dom';\n\n/**\n * Interface for basic authentication tokens\n *\n * @interface AuthTokens\n * @property {string} token - Main authentication token\n * @property {string} refreshToken - Token used to refresh the main token\n * @property {unknown} [key] - Additional properties that can be included\n */\nexport interface AuthTokens {\n token: string;\n refreshToken: string;\n [key: string]: unknown;\n}\n\n/**\n * Interface for basic user information\n *\n * @interface AuthUser\n * @property {string} id - Unique user identifier\n * @property {string} [name] - Optional user name\n * @property {string} [email] - Optional user email\n * @property {unknown} [key] - Additional user properties\n */\nexport interface AuthUser {\n id: string;\n name?: string;\n email?: string;\n [key: string]: unknown;\n}\n\n/**\n * Interface for basic session information\n *\n * @interface SessionInfo\n * @property {string} [institutionId] - Optional institution identifier\n * @property {string} [profileId] - Optional profile identifier\n * @property {string} [schoolId] - Optional school identifier\n * @property {string} [schoolYearId] - Optional school year identifier\n * @property {string} [classId] - Optional class identifier\n * @property {unknown} [key] - Additional session properties\n */\nexport interface SessionInfo {\n institutionId?: string;\n profileId?: string;\n schoolId?: string;\n schoolYearId?: string;\n classId?: string;\n [key: string]: unknown;\n}\n\n/**\n * Interface for authentication state\n *\n * @interface AuthState\n * @property {boolean} isAuthenticated - Whether the user is authenticated\n * @property {boolean} isLoading - Whether authentication is being checked\n * @property {AuthUser | null} [user] - Current user information\n * @property {SessionInfo | null} [sessionInfo] - Current session information\n * @property {AuthTokens | null} [tokens] - Current authentication tokens\n */\nexport interface AuthState {\n isAuthenticated: boolean;\n isLoading: boolean;\n user?: AuthUser | null;\n sessionInfo?: SessionInfo | null;\n tokens?: AuthTokens | null;\n}\n\n/**\n * Interface for authentication context functions and state\n *\n * @interface AuthContextType\n * @extends {AuthState}\n * @property {() => Promise<boolean>} checkAuth - Function to check authentication status\n * @property {() => void} signOut - Function to sign out the user\n */\nexport interface AuthContextType extends AuthState {\n checkAuth: () => Promise<boolean>;\n signOut: () => void;\n}\n\n/**\n * Authentication context for React components\n *\n * @private\n */\nconst AuthContext = createContext<AuthContextType | undefined>(undefined);\n\n/**\n * Props for the AuthProvider component\n *\n * @interface AuthProviderProps\n * @property {ReactNode} children - Child components\n * @property {() => Promise<boolean> | boolean} [checkAuthFn] - Function to check if user is authenticated\n * @property {() => void} [signOutFn] - Function to handle logout\n * @property {Partial<AuthState>} [initialAuthState] - Initial authentication state\n * @property {() => AuthUser | null | undefined} [getUserFn] - Function to get user data\n * @property {() => SessionInfo | null | undefined} [getSessionFn] - Function to get session info\n * @property {() => AuthTokens | null | undefined} [getTokensFn] - Function to get tokens\n */\nexport interface AuthProviderProps {\n children: ReactNode;\n /**\n * Função para verificar se o usuário está autenticado\n * Deve retornar uma Promise<boolean>\n */\n checkAuthFn?: () => Promise<boolean> | boolean;\n /**\n * Função para fazer logout\n */\n signOutFn?: () => void;\n /**\n * Estado de autenticação inicial\n */\n initialAuthState?: Partial<AuthState>;\n /**\n * Função para obter dados do usuário (opcional)\n */\n getUserFn?: () => AuthUser | null | undefined;\n /**\n * Função para obter informações da sessão (opcional)\n */\n getSessionFn?: () => SessionInfo | null | undefined;\n /**\n * Função para obter tokens (opcional)\n */\n getTokensFn?: () => AuthTokens | null | undefined;\n}\n\n/**\n * Authentication provider that manages global auth state\n * Compatible with any store (Zustand, Redux, Context, etc.)\n *\n * @param {AuthProviderProps} props - The provider props\n * @returns {JSX.Element} The provider component\n *\n * @example\n * ```tsx\n * <AuthProvider\n * checkAuthFn={checkAuthFunction}\n * signOutFn={signOutFunction}\n * getUserFn={getUserFunction}\n * >\n * <App />\n * </AuthProvider>\n * ```\n */\nexport const AuthProvider = ({\n children,\n checkAuthFn,\n signOutFn,\n initialAuthState = {},\n getUserFn,\n getSessionFn,\n getTokensFn,\n}: AuthProviderProps) => {\n const [authState, setAuthState] = useState<AuthState>({\n isAuthenticated: false,\n isLoading: true,\n ...initialAuthState,\n });\n\n /**\n * Check authentication status and update state accordingly\n *\n * @returns {Promise<boolean>} Promise that resolves to authentication status\n */\n const checkAuth = useCallback(async (): Promise<boolean> => {\n try {\n setAuthState((prev) => ({ ...prev, isLoading: true }));\n\n // Se não há função de verificação, assume como não autenticado\n if (!checkAuthFn) {\n setAuthState((prev) => ({\n ...prev,\n isAuthenticated: false,\n isLoading: false,\n }));\n return false;\n }\n\n const isAuth = await checkAuthFn();\n\n setAuthState((prev) => ({\n ...prev,\n isAuthenticated: isAuth,\n isLoading: false,\n user: getUserFn ? getUserFn() : prev.user,\n sessionInfo: getSessionFn ? getSessionFn() : prev.sessionInfo,\n tokens: getTokensFn ? getTokensFn() : prev.tokens,\n }));\n\n return isAuth;\n } catch (error) {\n console.error('Erro ao verificar autenticação:', error);\n setAuthState((prev) => ({\n ...prev,\n isAuthenticated: false,\n isLoading: false,\n }));\n return false;\n }\n }, [checkAuthFn, getUserFn, getSessionFn, getTokensFn]);\n\n /**\n * Sign out the current user and clear auth state\n *\n * @returns {void}\n */\n const signOut = useCallback(() => {\n if (signOutFn) {\n signOutFn();\n }\n setAuthState((prev) => ({\n ...prev,\n isAuthenticated: false,\n user: undefined,\n sessionInfo: undefined,\n tokens: undefined,\n }));\n }, [signOutFn]);\n\n useEffect(() => {\n checkAuth();\n }, [checkAuth]);\n\n const contextValue = useMemo(\n (): AuthContextType => ({\n ...authState,\n checkAuth,\n signOut,\n }),\n [authState, checkAuth, signOut]\n );\n\n return (\n <AuthContext.Provider value={contextValue}>{children}</AuthContext.Provider>\n );\n};\n\n/**\n * Hook to use the authentication context\n *\n * @throws {Error} When used outside of AuthProvider\n * @returns {AuthContextType} The authentication context\n *\n * @example\n * ```tsx\n * const { isAuthenticated, user, signOut } = useAuth();\n * ```\n */\nexport const useAuth = (): AuthContextType => {\n const context = useContext(AuthContext);\n if (context === undefined) {\n throw new Error('useAuth deve ser usado dentro de um AuthProvider');\n }\n return context;\n};\n\n/**\n * Props for the ProtectedRoute component\n *\n * @interface ProtectedRouteProps\n * @property {ReactNode} children - Components to render when authenticated\n * @property {string} [redirectTo] - Path to redirect when not authenticated (default: '/')\n * @property {ReactNode} [loadingComponent] - Custom loading component\n * @property {(authState: AuthState) => boolean} [additionalCheck] - Additional authentication check\n */\nexport interface ProtectedRouteProps {\n children: ReactNode;\n /**\n * Path para redirecionamento quando não autenticado\n */\n redirectTo?: string;\n /**\n * Componente de loading personalizado\n */\n loadingComponent?: ReactNode;\n /**\n * Função adicional de verificação (ex: verificar permissões específicas)\n */\n additionalCheck?: (authState: AuthState) => boolean;\n}\n\n/**\n * Componente para proteger rotas que requerem autenticação\n *\n * @example\n * ```tsx\n * <ProtectedRoute redirectTo=\"/login\">\n * <PainelPage />\n * </ProtectedRoute>\n * ```\n */\nexport const ProtectedRoute = ({\n children,\n redirectTo = '/',\n loadingComponent,\n additionalCheck,\n}: ProtectedRouteProps) => {\n const { isAuthenticated, isLoading, ...authState } = useAuth();\n\n // Componente de loading padrão\n const defaultLoadingComponent = (\n <div className=\"flex items-center justify-center min-h-screen\">\n <div className=\"text-text-950 text-lg\">Carregando...</div>\n </div>\n );\n\n // Mostrar loading enquanto verifica autenticação\n if (isLoading) {\n return <>{loadingComponent || defaultLoadingComponent}</>;\n }\n\n // Verificar autenticação básica\n if (!isAuthenticated) {\n if (typeof window !== 'undefined') {\n const rootDomain = getRootDomain();\n // Only redirect if the root domain is different from current location\n const currentLocation = `${window.location.protocol}//${window.location.hostname}${window.location.port ? ':' + window.location.port : ''}`;\n if (rootDomain !== currentLocation) {\n window.location.href = rootDomain;\n return null;\n }\n }\n return <Navigate to={redirectTo} replace />;\n }\n\n // Verificação adicional (ex: permissões)\n if (\n additionalCheck &&\n !additionalCheck({ isAuthenticated, isLoading, ...authState })\n ) {\n return <Navigate to={redirectTo} replace />;\n }\n\n return <>{children}</>;\n};\n\n/**\n * Props for the PublicRoute component\n *\n * @interface PublicRouteProps\n * @property {ReactNode} children - Components to render\n * @property {string} [redirectTo] - Path to redirect to (default: '/painel')\n * @property {boolean} [redirectIfAuthenticated] - Whether to redirect if authenticated\n * @property {boolean} [checkAuthBeforeRender] - Whether to check auth before rendering\n */\nexport interface PublicRouteProps {\n children: ReactNode;\n /**\n * Path para redirecionamento\n */\n redirectTo?: string;\n /**\n * Se deve redirecionar quando usuário estiver autenticado\n */\n redirectIfAuthenticated?: boolean;\n /**\n * Se deve verificar autenticação antes de renderizar\n */\n checkAuthBeforeRender?: boolean;\n}\n\n/**\n * Componente para rotas públicas (login, recuperação de senha, etc.)\n * Opcionalmente redireciona se o usuário já estiver autenticado\n *\n * @example\n * ```tsx\n * <PublicRoute redirectTo=\"/painel\" redirectIfAuthenticated={true}>\n * <LoginPage />\n * </PublicRoute>\n * ```\n */\nexport const PublicRoute = ({\n children,\n redirectTo = '/painel',\n redirectIfAuthenticated = false,\n checkAuthBeforeRender = false,\n}: PublicRouteProps) => {\n const { isAuthenticated, isLoading } = useAuth();\n\n // Se deve aguardar verificação de auth antes de renderizar\n if (checkAuthBeforeRender && isLoading) {\n return (\n <div className=\"flex items-center justify-center min-h-screen\">\n <div className=\"text-text-950 text-lg\">Carregando...</div>\n </div>\n );\n }\n\n // Redirecionar se já autenticado e configurado para isso\n if (isAuthenticated && redirectIfAuthenticated) {\n return <Navigate to={redirectTo} replace />;\n }\n\n return <>{children}</>;\n};\n\n/**\n * Higher-Order Component to protect components with authentication\n *\n * @template P - Component props type\n * @param {ComponentType<P>} Component - Component to wrap with authentication\n * @param {Omit<ProtectedRouteProps, 'children'>} [options] - Protection options\n * @returns {(props: P) => JSX.Element} Wrapped component\n *\n * @example\n * ```tsx\n * const ProtectedComponent = withAuth(MyComponent, {\n * redirectTo: \"/login\",\n * loadingComponent: <CustomSpinner />\n * });\n * ```\n */\nexport const withAuth = <P extends object>(\n Component: ComponentType<P>,\n options: Omit<ProtectedRouteProps, 'children'> = {}\n) => {\n return (props: P) => (\n <ProtectedRoute {...options}>\n <Component {...props} />\n </ProtectedRoute>\n );\n};\n\n/**\n * Hook for authentication guard with custom checks\n *\n * @param {object} [options] - Guard options\n * @param {boolean} [options.requireAuth=true] - Whether authentication is required\n * @param {(authState: AuthState) => boolean} [options.customCheck] - Custom check function\n * @returns {object} Guard result with canAccess, isLoading, and authState\n *\n * @example\n * ```tsx\n * const { canAccess, isLoading } = useAuthGuard({\n * requireAuth: true,\n * customCheck: (authState) => authState.user?.role === 'admin'\n * });\n * ```\n */\nexport const useAuthGuard = (\n options: {\n requireAuth?: boolean;\n customCheck?: (authState: AuthState) => boolean;\n } = {}\n) => {\n const authState = useAuth();\n const { requireAuth = true, customCheck } = options;\n\n const canAccess =\n !authState.isLoading &&\n (requireAuth\n ? authState.isAuthenticated && (!customCheck || customCheck(authState))\n : !authState.isAuthenticated || !customCheck || customCheck(authState));\n\n return {\n canAccess,\n isLoading: authState.isLoading,\n authState,\n };\n};\n\n/**\n * Hook to check authentication on specific routes\n * Useful for conditional checks within components\n *\n * @param {string} [fallbackPath='/'] - Path to redirect when not authenticated\n * @returns {object} Object with isAuthenticated, isLoading, and redirectToLogin function\n *\n * @example\n * ```tsx\n * const { isAuthenticated, redirectToLogin } = useRouteAuth();\n *\n * if (!isAuthenticated) {\n * return redirectToLogin();\n * }\n * ```\n */\nexport const useRouteAuth = (fallbackPath = '/') => {\n const { isAuthenticated, isLoading } = useAuth();\n const location = useLocation();\n\n const redirectToLogin = () => (\n <Navigate to={fallbackPath} state={{ from: location }} replace />\n );\n\n return {\n isAuthenticated,\n isLoading,\n redirectToLogin,\n };\n};\n\n/**\n * Get the root domain from the current window location\n * Handles localhost, IP addresses, and subdomain cases, including Brazilian .com.br domains\n *\n * @returns {string} The root domain URL\n *\n * @example\n * ```typescript\n * // Domain examples\n * aluno.analiticaensino.com.br -> analiticaensino.com.br\n * subdomain.example.com -> example.com\n *\n * // IP address examples\n * 127.0.0.1:3000 -> 127.0.0.1:3000\n * [::1]:8080 -> [::1]:8080\n *\n * // Localhost examples\n * localhost:3000 -> localhost:3000\n * ```\n */\nexport const getRootDomain = () => {\n const { hostname, protocol, port } = window.location;\n const portStr = port ? ':' + port : '';\n\n if (hostname === 'localhost') {\n return `${protocol}//${hostname}${portStr}`;\n }\n\n // IP literals: return as-is (no subdomain logic)\n const isIPv4 = /^\\d{1,3}(?:\\.\\d{1,3}){3}$/.test(hostname);\n const isIPv6 = hostname.includes(':'); // simple check is sufficient here\n if (isIPv4 || isIPv6) {\n return `${protocol}//${hostname}${portStr}`;\n }\n\n const parts = hostname.split('.');\n\n // Handle Brazilian .com.br domains and similar patterns\n if (\n parts.length >= 3 &&\n parts[parts.length - 2] === 'com' &&\n parts[parts.length - 1] === 'br'\n ) {\n if (parts.length === 3) {\n // Already at root level for .com.br (e.g., analiticaensino.com.br)\n return `${protocol}//${hostname}${portStr}`;\n }\n // For domains like aluno.analiticaensino.com.br, return analiticaensino.com.br\n const base = parts.slice(-3).join('.');\n return `${protocol}//${base}${portStr}`;\n }\n\n // Only treat as subdomain if there are 3+ parts (e.g., subdomain.example.com)\n if (parts.length > 2) {\n // Return the last 2 parts as the root domain (example.com)\n const base = parts.slice(-2).join('.');\n return `${protocol}//${base}${portStr}`;\n }\n\n // For 2-part domains (example.com) or single domains, return as-is\n return `${protocol}//${hostname}${portStr}`;\n};\n\nexport default {\n AuthProvider,\n ProtectedRoute,\n PublicRoute,\n withAuth,\n useAuth,\n useAuthGuard,\n useRouteAuth,\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBASO;AACP,8BAAsC;AA8OlC;AAtJJ,IAAM,kBAAc,4BAA2C,MAAS;AA6DjE,IAAM,eAAe,CAAC;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA,mBAAmB,CAAC;AAAA,EACpB;AAAA,EACA;AAAA,EACA;AACF,MAAyB;AACvB,QAAM,CAAC,WAAW,YAAY,QAAI,uBAAoB;AAAA,IACpD,iBAAiB;AAAA,IACjB,WAAW;AAAA,IACX,GAAG;AAAA,EACL,CAAC;AAOD,QAAM,gBAAY,0BAAY,YAA8B;AAC1D,QAAI;AACF,mBAAa,CAAC,UAAU,EAAE,GAAG,MAAM,WAAW,KAAK,EAAE;AAGrD,UAAI,CAAC,aAAa;AAChB,qBAAa,CAAC,UAAU;AAAA,UACtB,GAAG;AAAA,UACH,iBAAiB;AAAA,UACjB,WAAW;AAAA,QACb,EAAE;AACF,eAAO;AAAA,MACT;AAEA,YAAM,SAAS,MAAM,YAAY;AAEjC,mBAAa,CAAC,UAAU;AAAA,QACtB,GAAG;AAAA,QACH,iBAAiB;AAAA,QACjB,WAAW;AAAA,QACX,MAAM,YAAY,UAAU,IAAI,KAAK;AAAA,QACrC,aAAa,eAAe,aAAa,IAAI,KAAK;AAAA,QAClD,QAAQ,cAAc,YAAY,IAAI,KAAK;AAAA,MAC7C,EAAE;AAEF,aAAO;AAAA,IACT,SAAS,OAAO;AACd,cAAQ,MAAM,yCAAmC,KAAK;AACtD,mBAA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AQ;AAAA,EACb;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../src/components/Auth/Auth.tsx","../../../src/components/Auth/useTokenInUrl.ts"],"sourcesContent":["import {\n createContext,\n useContext,\n useEffect,\n useState,\n ReactNode,\n ComponentType,\n useCallback,\n useMemo,\n} from 'react';\nimport { useLocation, Navigate } from 'react-router-dom';\nimport { useTokenInUrl } from './useTokenInUrl';\n\n/**\n * Interface for basic authentication tokens\n *\n * @interface AuthTokens\n * @property {string} token - Main authentication token\n * @property {string} refreshToken - Token used to refresh the main token\n * @property {unknown} [key] - Additional properties that can be included\n */\nexport interface AuthTokens {\n token: string;\n refreshToken: string;\n [key: string]: unknown;\n}\n\n/**\n * Interface for basic user information\n *\n * @interface AuthUser\n * @property {string} id - Unique user identifier\n * @property {string} [name] - Optional user name\n * @property {string} [email] - Optional user email\n * @property {unknown} [key] - Additional user properties\n */\nexport interface AuthUser {\n id: string;\n name?: string;\n email?: string;\n [key: string]: unknown;\n}\n\n/**\n * Interface for basic session information\n *\n * @interface SessionInfo\n * @property {string} [institutionId] - Optional institution identifier\n * @property {string} [profileId] - Optional profile identifier\n * @property {string} [schoolId] - Optional school identifier\n * @property {string} [schoolYearId] - Optional school year identifier\n * @property {string} [classId] - Optional class identifier\n * @property {unknown} [key] - Additional session properties\n */\nexport interface SessionInfo {\n institutionId?: string;\n profileId?: string;\n schoolId?: string;\n schoolYearId?: string;\n classId?: string;\n [key: string]: unknown;\n}\n\n/**\n * Interface for authentication state\n *\n * @interface AuthState\n * @property {boolean} isAuthenticated - Whether the user is authenticated\n * @property {boolean} isLoading - Whether authentication is being checked\n * @property {AuthUser | null} [user] - Current user information\n * @property {SessionInfo | null} [sessionInfo] - Current session information\n * @property {AuthTokens | null} [tokens] - Current authentication tokens\n */\nexport interface AuthState {\n isAuthenticated: boolean;\n isLoading: boolean;\n user?: AuthUser | null;\n sessionInfo?: SessionInfo | null;\n tokens?: AuthTokens | null;\n}\n\n/**\n * Interface for authentication context functions and state\n *\n * @interface AuthContextType\n * @extends {AuthState}\n * @property {() => Promise<boolean>} checkAuth - Function to check authentication status\n * @property {() => void} signOut - Function to sign out the user\n */\nexport interface AuthContextType extends AuthState {\n checkAuth: () => Promise<boolean>;\n signOut: () => void;\n}\n\n/**\n * Authentication context for React components\n *\n * @private\n */\nconst AuthContext = createContext<AuthContextType | undefined>(undefined);\n\n/**\n * Props for the AuthProvider component\n *\n * @interface AuthProviderProps\n * @property {ReactNode} children - Child components\n * @property {() => Promise<boolean> | boolean} [checkAuthFn] - Function to check if user is authenticated\n * @property {() => void} [signOutFn] - Function to handle logout\n * @property {Partial<AuthState>} [initialAuthState] - Initial authentication state\n * @property {() => AuthUser | null | undefined} [getUserFn] - Function to get user data\n * @property {() => SessionInfo | null | undefined} [getSessionFn] - Function to get session info\n * @property {() => AuthTokens | null | undefined} [getTokensFn] - Function to get tokens\n */\nexport interface AuthProviderProps {\n children: ReactNode;\n /**\n * Função para verificar se o usuário está autenticado\n * Deve retornar uma Promise<boolean>\n */\n checkAuthFn?: () => Promise<boolean> | boolean;\n /**\n * Função para fazer logout\n */\n signOutFn?: () => void;\n /**\n * Estado de autenticação inicial\n */\n initialAuthState?: Partial<AuthState>;\n /**\n * Função para obter dados do usuário (opcional)\n */\n getUserFn?: () => AuthUser | null | undefined;\n /**\n * Função para obter informações da sessão (opcional)\n */\n getSessionFn?: () => SessionInfo | null | undefined;\n /**\n * Função para obter tokens (opcional)\n */\n getTokensFn?: () => AuthTokens | null | undefined;\n}\n\n/**\n * Authentication provider that manages global auth state\n * Compatible with any store (Zustand, Redux, Context, etc.)\n *\n * @param {AuthProviderProps} props - The provider props\n * @returns {JSX.Element} The provider component\n *\n * @example\n * ```tsx\n * <AuthProvider\n * checkAuthFn={checkAuthFunction}\n * signOutFn={signOutFunction}\n * getUserFn={getUserFunction}\n * >\n * <App />\n * </AuthProvider>\n * ```\n */\nexport const AuthProvider = ({\n children,\n checkAuthFn,\n signOutFn,\n initialAuthState = {},\n getUserFn,\n getSessionFn,\n getTokensFn,\n}: AuthProviderProps) => {\n const [authState, setAuthState] = useState<AuthState>({\n isAuthenticated: false,\n isLoading: true,\n ...initialAuthState,\n });\n\n /**\n * Check authentication status and update state accordingly\n *\n * @returns {Promise<boolean>} Promise that resolves to authentication status\n */\n const checkAuth = useCallback(async (): Promise<boolean> => {\n try {\n setAuthState((prev) => ({ ...prev, isLoading: true }));\n\n // Se não há função de verificação, assume como não autenticado\n if (!checkAuthFn) {\n setAuthState((prev) => ({\n ...prev,\n isAuthenticated: false,\n isLoading: false,\n }));\n return false;\n }\n\n const isAuth = await checkAuthFn();\n\n setAuthState((prev) => ({\n ...prev,\n isAuthenticated: isAuth,\n isLoading: false,\n user: getUserFn ? getUserFn() : prev.user,\n sessionInfo: getSessionFn ? getSessionFn() : prev.sessionInfo,\n tokens: getTokensFn ? getTokensFn() : prev.tokens,\n }));\n\n return isAuth;\n } catch (error) {\n console.error('Erro ao verificar autenticação:', error);\n setAuthState((prev) => ({\n ...prev,\n isAuthenticated: false,\n isLoading: false,\n }));\n return false;\n }\n }, [checkAuthFn, getUserFn, getSessionFn, getTokensFn]);\n\n /**\n * Sign out the current user and clear auth state\n *\n * @returns {void}\n */\n const signOut = useCallback(() => {\n if (signOutFn) {\n signOutFn();\n }\n setAuthState((prev) => ({\n ...prev,\n isAuthenticated: false,\n user: undefined,\n sessionInfo: undefined,\n tokens: undefined,\n }));\n }, [signOutFn]);\n\n useEffect(() => {\n checkAuth();\n }, [checkAuth]);\n\n const contextValue = useMemo(\n (): AuthContextType => ({\n ...authState,\n checkAuth,\n signOut,\n }),\n [authState, checkAuth, signOut]\n );\n\n return (\n <AuthContext.Provider value={contextValue}>{children}</AuthContext.Provider>\n );\n};\n\n/**\n * Hook to use the authentication context\n *\n * @throws {Error} When used outside of AuthProvider\n * @returns {AuthContextType} The authentication context\n *\n * @example\n * ```tsx\n * const { isAuthenticated, user, signOut } = useAuth();\n * ```\n */\nexport const useAuth = (): AuthContextType => {\n const context = useContext(AuthContext);\n if (context === undefined) {\n throw new Error('useAuth deve ser usado dentro de um AuthProvider');\n }\n return context;\n};\n\n/**\n * Props for the ProtectedRoute component\n *\n * @interface ProtectedRouteProps\n * @property {ReactNode} children - Components to render when authenticated\n * @property {string} [redirectTo] - Path to redirect when not authenticated (default: '/')\n * @property {ReactNode} [loadingComponent] - Custom loading component\n * @property {(authState: AuthState) => boolean} [additionalCheck] - Additional authentication check\n */\nexport interface ProtectedRouteProps {\n children: ReactNode;\n /**\n * Path para redirecionamento quando não autenticado\n */\n redirectTo?: string;\n /**\n * Componente de loading personalizado\n */\n loadingComponent?: ReactNode;\n /**\n * Função adicional de verificação (ex: verificar permissões específicas)\n */\n additionalCheck?: (authState: AuthState) => boolean;\n}\n\n/**\n * Componente para proteger rotas que requerem autenticação\n *\n * @example\n * ```tsx\n * <ProtectedRoute redirectTo=\"/login\">\n * <PainelPage />\n * </ProtectedRoute>\n * ```\n */\nexport const ProtectedRoute = ({\n children,\n redirectTo = '/',\n loadingComponent,\n additionalCheck,\n}: ProtectedRouteProps) => {\n const { isAuthenticated, isLoading, ...authState } = useAuth();\n\n // Componente de loading padrão\n const defaultLoadingComponent = (\n <div className=\"flex items-center justify-center min-h-screen\">\n <div className=\"text-text-950 text-lg\">Carregando...</div>\n </div>\n );\n\n // Mostrar loading enquanto verifica autenticação\n if (isLoading) {\n return <>{loadingComponent || defaultLoadingComponent}</>;\n }\n\n // Verificar autenticação básica\n if (!isAuthenticated) {\n if (typeof window !== 'undefined') {\n const rootDomain = getRootDomain();\n // Only redirect if the root domain is different from current location\n const currentLocation = `${window.location.protocol}//${window.location.hostname}${window.location.port ? ':' + window.location.port : ''}`;\n if (rootDomain !== currentLocation) {\n window.location.href = rootDomain;\n return null;\n }\n }\n return <Navigate to={redirectTo} replace />;\n }\n\n // Verificação adicional (ex: permissões)\n if (\n additionalCheck &&\n !additionalCheck({ isAuthenticated, isLoading, ...authState })\n ) {\n return <Navigate to={redirectTo} replace />;\n }\n\n return <>{children}</>;\n};\n\n/**\n * Props for the PublicRoute component\n *\n * @interface PublicRouteProps\n * @property {ReactNode} children - Components to render\n * @property {string} [redirectTo] - Path to redirect to (default: '/painel')\n * @property {boolean} [redirectIfAuthenticated] - Whether to redirect if authenticated\n * @property {boolean} [checkAuthBeforeRender] - Whether to check auth before rendering\n * @property {ReactNode} [tokenValidationComponent] - Component to show while validating tokens from URL\n */\nexport interface PublicRouteProps {\n children: ReactNode;\n /**\n * Path para redirecionamento\n */\n redirectTo?: string;\n /**\n * Se deve redirecionar quando usuário estiver autenticado\n */\n redirectIfAuthenticated?: boolean;\n /**\n * Se deve verificar autenticação antes de renderizar\n */\n checkAuthBeforeRender?: boolean;\n /**\n * Componente a ser exibido enquanto valida tokens da URL\n */\n tokenValidationComponent?: ReactNode;\n}\n\n/**\n * Componente para rotas públicas (login, recuperação de senha, etc.)\n * Opcionalmente redireciona se o usuário já estiver autenticado\n *\n * @example\n * ```tsx\n * <PublicRoute redirectTo=\"/painel\" redirectIfAuthenticated={true}>\n * <LoginPage />\n * </PublicRoute>\n * ```\n */\nexport const PublicRoute = ({\n children,\n redirectTo = '/painel',\n redirectIfAuthenticated = false,\n checkAuthBeforeRender = false,\n tokenValidationComponent,\n}: PublicRouteProps) => {\n const { isAuthenticated, isLoading } = useAuth();\n const { hasTokenInUrl } = useTokenInUrl();\n\n // Se tem tokens na URL, mostrar componente de validação (se fornecido)\n if (hasTokenInUrl && tokenValidationComponent) {\n return <>{tokenValidationComponent}</>;\n }\n\n // Se deve aguardar verificação de auth antes de renderizar\n if (checkAuthBeforeRender && isLoading) {\n return (\n <div className=\"flex items-center justify-center min-h-screen\">\n <div className=\"text-text-950 text-lg\">Carregando...</div>\n </div>\n );\n }\n\n // Redirecionar se já autenticado e configurado para isso\n if (isAuthenticated && redirectIfAuthenticated) {\n return <Navigate to={redirectTo} replace />;\n }\n\n return <>{children}</>;\n};\n\n/**\n * Higher-Order Component to protect components with authentication\n *\n * @template P - Component props type\n * @param {ComponentType<P>} Component - Component to wrap with authentication\n * @param {Omit<ProtectedRouteProps, 'children'>} [options] - Protection options\n * @returns {(props: P) => JSX.Element} Wrapped component\n *\n * @example\n * ```tsx\n * const ProtectedComponent = withAuth(MyComponent, {\n * redirectTo: \"/login\",\n * loadingComponent: <CustomSpinner />\n * });\n * ```\n */\nexport const withAuth = <P extends object>(\n Component: ComponentType<P>,\n options: Omit<ProtectedRouteProps, 'children'> = {}\n) => {\n return (props: P) => (\n <ProtectedRoute {...options}>\n <Component {...props} />\n </ProtectedRoute>\n );\n};\n\n/**\n * Hook for authentication guard with custom checks\n *\n * @param {object} [options] - Guard options\n * @param {boolean} [options.requireAuth=true] - Whether authentication is required\n * @param {(authState: AuthState) => boolean} [options.customCheck] - Custom check function\n * @returns {object} Guard result with canAccess, isLoading, and authState\n *\n * @example\n * ```tsx\n * const { canAccess, isLoading } = useAuthGuard({\n * requireAuth: true,\n * customCheck: (authState) => authState.user?.role === 'admin'\n * });\n * ```\n */\nexport const useAuthGuard = (\n options: {\n requireAuth?: boolean;\n customCheck?: (authState: AuthState) => boolean;\n } = {}\n) => {\n const authState = useAuth();\n const { requireAuth = true, customCheck } = options;\n\n const canAccess =\n !authState.isLoading &&\n (requireAuth\n ? authState.isAuthenticated && (!customCheck || customCheck(authState))\n : !authState.isAuthenticated || !customCheck || customCheck(authState));\n\n return {\n canAccess,\n isLoading: authState.isLoading,\n authState,\n };\n};\n\n/**\n * Hook to check authentication on specific routes\n * Useful for conditional checks within components\n *\n * @param {string} [fallbackPath='/'] - Path to redirect when not authenticated\n * @returns {object} Object with isAuthenticated, isLoading, and redirectToLogin function\n *\n * @example\n * ```tsx\n * const { isAuthenticated, redirectToLogin } = useRouteAuth();\n *\n * if (!isAuthenticated) {\n * return redirectToLogin();\n * }\n * ```\n */\nexport const useRouteAuth = (fallbackPath = '/') => {\n const { isAuthenticated, isLoading } = useAuth();\n const location = useLocation();\n\n const redirectToLogin = () => (\n <Navigate to={fallbackPath} state={{ from: location }} replace />\n );\n\n return {\n isAuthenticated,\n isLoading,\n redirectToLogin,\n };\n};\n\n/**\n * Get the root domain from the current window location\n * Handles localhost, IP addresses, and subdomain cases, including Brazilian .com.br domains\n *\n * @returns {string} The root domain URL\n *\n * @example\n * ```typescript\n * // Domain examples\n * aluno.analiticaensino.com.br -> analiticaensino.com.br\n * subdomain.example.com -> example.com\n *\n * // IP address examples\n * 127.0.0.1:3000 -> 127.0.0.1:3000\n * [::1]:8080 -> [::1]:8080\n *\n * // Localhost examples\n * localhost:3000 -> localhost:3000\n * ```\n */\nexport const getRootDomain = () => {\n const { hostname, protocol, port } = window.location;\n const portStr = port ? ':' + port : '';\n\n if (hostname === 'localhost') {\n return `${protocol}//${hostname}${portStr}`;\n }\n\n // IP literals: return as-is (no subdomain logic)\n const isIPv4 = /^\\d{1,3}(?:\\.\\d{1,3}){3}$/.test(hostname);\n const isIPv6 = hostname.includes(':'); // simple check is sufficient here\n if (isIPv4 || isIPv6) {\n return `${protocol}//${hostname}${portStr}`;\n }\n\n const parts = hostname.split('.');\n\n // Handle Brazilian .com.br domains and similar patterns\n if (\n parts.length >= 3 &&\n parts[parts.length - 2] === 'com' &&\n parts[parts.length - 1] === 'br'\n ) {\n if (parts.length === 3) {\n // Already at root level for .com.br (e.g., analiticaensino.com.br)\n return `${protocol}//${hostname}${portStr}`;\n }\n // For domains like aluno.analiticaensino.com.br, return analiticaensino.com.br\n const base = parts.slice(-3).join('.');\n return `${protocol}//${base}${portStr}`;\n }\n\n // Only treat as subdomain if there are 3+ parts (e.g., subdomain.example.com)\n if (parts.length > 2) {\n // Return the last 2 parts as the root domain (example.com)\n const base = parts.slice(-2).join('.');\n return `${protocol}//${base}${portStr}`;\n }\n\n // For 2-part domains (example.com) or single domains, return as-is\n return `${protocol}//${hostname}${portStr}`;\n};\n\nexport default {\n AuthProvider,\n ProtectedRoute,\n PublicRoute,\n withAuth,\n useAuth,\n useAuthGuard,\n useRouteAuth,\n};\n","import { useMemo } from 'react';\nimport { useLocation } from 'react-router-dom';\n\n/**\n * Hook to check if authentication tokens are present in the URL\n *\n * @returns {object} Object with hasTokenInUrl boolean indicating if tokens are present\n *\n * @example\n * ```typescript\n * const { hasTokenInUrl } = useTokenInUrl();\n *\n * if (hasTokenInUrl) {\n * // Show loading/validation component\n * }\n * ```\n */\nexport function useTokenInUrl() {\n const location = useLocation();\n\n const hasTokenInUrl = useMemo(() => {\n const searchParams = new URLSearchParams(location.search);\n const token = searchParams.get('token');\n const refreshToken = searchParams.get('refreshToken');\n const sessionId = searchParams.get('sessionId');\n\n return !!(token && refreshToken && sessionId);\n }, [location.search]);\n\n return { hasTokenInUrl };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAA,gBASO;AACP,IAAAC,2BAAsC;;;ACVtC,mBAAwB;AACxB,8BAA4B;AAgBrB,SAAS,gBAAgB;AAC9B,QAAM,eAAW,qCAAY;AAE7B,QAAM,oBAAgB,sBAAQ,MAAM;AAClC,UAAM,eAAe,IAAI,gBAAgB,SAAS,MAAM;AACxD,UAAM,QAAQ,aAAa,IAAI,OAAO;AACtC,UAAM,eAAe,aAAa,IAAI,cAAc;AACpD,UAAM,YAAY,aAAa,IAAI,WAAW;AAE9C,WAAO,CAAC,EAAE,SAAS,gBAAgB;AAAA,EACrC,GAAG,CAAC,SAAS,MAAM,CAAC;AAEpB,SAAO,EAAE,cAAc;AACzB;;;AD2NI;AAtJJ,IAAM,kBAAc,6BAA2C,MAAS;AA6DjE,IAAM,eAAe,CAAC;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA,mBAAmB,CAAC;AAAA,EACpB;AAAA,EACA;AAAA,EACA;AACF,MAAyB;AACvB,QAAM,CAAC,WAAW,YAAY,QAAI,wBA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QAAQ,KAAK,QAAQ,GAAG,OAAO;AAAA,EAC3C;AAGA,QAAM,SAAS,4BAA4B,KAAK,QAAQ;AACxD,QAAM,SAAS,SAAS,SAAS,GAAG;AACpC,MAAI,UAAU,QAAQ;AACpB,WAAO,GAAG,QAAQ,KAAK,QAAQ,GAAG,OAAO;AAAA,EAC3C;AAEA,QAAM,QAAQ,SAAS,MAAM,GAAG;AAGhC,MACE,MAAM,UAAU,KAChB,MAAM,MAAM,SAAS,CAAC,MAAM,SAC5B,MAAM,MAAM,SAAS,CAAC,MAAM,MAC5B;AACA,QAAI,MAAM,WAAW,GAAG;AAEtB,aAAO,GAAG,QAAQ,KAAK,QAAQ,GAAG,OAAO;AAAA,IAC3C;AAEA,UAAM,OAAO,MAAM,MAAM,EAAE,EAAE,KAAK,GAAG;AACrC,WAAO,GAAG,QAAQ,KAAK,IAAI,GAAG,OAAO;AAAA,EACvC;AAGA,MAAI,MAAM,SAAS,GAAG;AAEpB,UAAM,OAAO,MAAM,MAAM,EAAE,EAAE,KAAK,GAAG;AACrC,WAAO,GAAG,QAAQ,KAAK,IAAI,GAAG,OAAO;AAAA,EACvC;AAGA,SAAO,GAAG,QAAQ,KAAK,QAAQ,GAAG,OAAO;AAC3C;AAEA,IAAO,eAAQ;AAAA,EACb;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;","names":["import_react","import_react_router_dom"]}
|
|
@@ -5,9 +5,26 @@ import {
|
|
|
5
5
|
useEffect,
|
|
6
6
|
useState,
|
|
7
7
|
useCallback,
|
|
8
|
-
useMemo
|
|
8
|
+
useMemo as useMemo2
|
|
9
9
|
} from "react";
|
|
10
|
-
import { useLocation, Navigate } from "react-router-dom";
|
|
10
|
+
import { useLocation as useLocation2, Navigate } from "react-router-dom";
|
|
11
|
+
|
|
12
|
+
// src/components/Auth/useTokenInUrl.ts
|
|
13
|
+
import { useMemo } from "react";
|
|
14
|
+
import { useLocation } from "react-router-dom";
|
|
15
|
+
function useTokenInUrl() {
|
|
16
|
+
const location = useLocation();
|
|
17
|
+
const hasTokenInUrl = useMemo(() => {
|
|
18
|
+
const searchParams = new URLSearchParams(location.search);
|
|
19
|
+
const token = searchParams.get("token");
|
|
20
|
+
const refreshToken = searchParams.get("refreshToken");
|
|
21
|
+
const sessionId = searchParams.get("sessionId");
|
|
22
|
+
return !!(token && refreshToken && sessionId);
|
|
23
|
+
}, [location.search]);
|
|
24
|
+
return { hasTokenInUrl };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// src/components/Auth/Auth.tsx
|
|
11
28
|
import { Fragment, jsx } from "react/jsx-runtime";
|
|
12
29
|
var AuthContext = createContext(void 0);
|
|
13
30
|
var AuthProvider = ({
|
|
@@ -70,7 +87,7 @@ var AuthProvider = ({
|
|
|
70
87
|
useEffect(() => {
|
|
71
88
|
checkAuth();
|
|
72
89
|
}, [checkAuth]);
|
|
73
|
-
const contextValue =
|
|
90
|
+
const contextValue = useMemo2(
|
|
74
91
|
() => ({
|
|
75
92
|
...authState,
|
|
76
93
|
checkAuth,
|
|
@@ -118,9 +135,14 @@ var PublicRoute = ({
|
|
|
118
135
|
children,
|
|
119
136
|
redirectTo = "/painel",
|
|
120
137
|
redirectIfAuthenticated = false,
|
|
121
|
-
checkAuthBeforeRender = false
|
|
138
|
+
checkAuthBeforeRender = false,
|
|
139
|
+
tokenValidationComponent
|
|
122
140
|
}) => {
|
|
123
141
|
const { isAuthenticated, isLoading } = useAuth();
|
|
142
|
+
const { hasTokenInUrl } = useTokenInUrl();
|
|
143
|
+
if (hasTokenInUrl && tokenValidationComponent) {
|
|
144
|
+
return /* @__PURE__ */ jsx(Fragment, { children: tokenValidationComponent });
|
|
145
|
+
}
|
|
124
146
|
if (checkAuthBeforeRender && isLoading) {
|
|
125
147
|
return /* @__PURE__ */ jsx("div", { className: "flex items-center justify-center min-h-screen", children: /* @__PURE__ */ jsx("div", { className: "text-text-950 text-lg", children: "Carregando..." }) });
|
|
126
148
|
}
|
|
@@ -144,7 +166,7 @@ var useAuthGuard = (options = {}) => {
|
|
|
144
166
|
};
|
|
145
167
|
var useRouteAuth = (fallbackPath = "/") => {
|
|
146
168
|
const { isAuthenticated, isLoading } = useAuth();
|
|
147
|
-
const location =
|
|
169
|
+
const location = useLocation2();
|
|
148
170
|
const redirectToLogin = () => /* @__PURE__ */ jsx(Navigate, { to: fallbackPath, state: { from: location }, replace: true });
|
|
149
171
|
return {
|
|
150
172
|
isAuthenticated,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/components/Auth/Auth.tsx"],"sourcesContent":["import {\n createContext,\n useContext,\n useEffect,\n useState,\n ReactNode,\n ComponentType,\n useCallback,\n useMemo,\n} from 'react';\nimport { useLocation, Navigate } from 'react-router-dom';\n\n/**\n * Interface for basic authentication tokens\n *\n * @interface AuthTokens\n * @property {string} token - Main authentication token\n * @property {string} refreshToken - Token used to refresh the main token\n * @property {unknown} [key] - Additional properties that can be included\n */\nexport interface AuthTokens {\n token: string;\n refreshToken: string;\n [key: string]: unknown;\n}\n\n/**\n * Interface for basic user information\n *\n * @interface AuthUser\n * @property {string} id - Unique user identifier\n * @property {string} [name] - Optional user name\n * @property {string} [email] - Optional user email\n * @property {unknown} [key] - Additional user properties\n */\nexport interface AuthUser {\n id: string;\n name?: string;\n email?: string;\n [key: string]: unknown;\n}\n\n/**\n * Interface for basic session information\n *\n * @interface SessionInfo\n * @property {string} [institutionId] - Optional institution identifier\n * @property {string} [profileId] - Optional profile identifier\n * @property {string} [schoolId] - Optional school identifier\n * @property {string} [schoolYearId] - Optional school year identifier\n * @property {string} [classId] - Optional class identifier\n * @property {unknown} [key] - Additional session properties\n */\nexport interface SessionInfo {\n institutionId?: string;\n profileId?: string;\n schoolId?: string;\n schoolYearId?: string;\n classId?: string;\n [key: string]: unknown;\n}\n\n/**\n * Interface for authentication state\n *\n * @interface AuthState\n * @property {boolean} isAuthenticated - Whether the user is authenticated\n * @property {boolean} isLoading - Whether authentication is being checked\n * @property {AuthUser | null} [user] - Current user information\n * @property {SessionInfo | null} [sessionInfo] - Current session information\n * @property {AuthTokens | null} [tokens] - Current authentication tokens\n */\nexport interface AuthState {\n isAuthenticated: boolean;\n isLoading: boolean;\n user?: AuthUser | null;\n sessionInfo?: SessionInfo | null;\n tokens?: AuthTokens | null;\n}\n\n/**\n * Interface for authentication context functions and state\n *\n * @interface AuthContextType\n * @extends {AuthState}\n * @property {() => Promise<boolean>} checkAuth - Function to check authentication status\n * @property {() => void} signOut - Function to sign out the user\n */\nexport interface AuthContextType extends AuthState {\n checkAuth: () => Promise<boolean>;\n signOut: () => void;\n}\n\n/**\n * Authentication context for React components\n *\n * @private\n */\nconst AuthContext = createContext<AuthContextType | undefined>(undefined);\n\n/**\n * Props for the AuthProvider component\n *\n * @interface AuthProviderProps\n * @property {ReactNode} children - Child components\n * @property {() => Promise<boolean> | boolean} [checkAuthFn] - Function to check if user is authenticated\n * @property {() => void} [signOutFn] - Function to handle logout\n * @property {Partial<AuthState>} [initialAuthState] - Initial authentication state\n * @property {() => AuthUser | null | undefined} [getUserFn] - Function to get user data\n * @property {() => SessionInfo | null | undefined} [getSessionFn] - Function to get session info\n * @property {() => AuthTokens | null | undefined} [getTokensFn] - Function to get tokens\n */\nexport interface AuthProviderProps {\n children: ReactNode;\n /**\n * Função para verificar se o usuário está autenticado\n * Deve retornar uma Promise<boolean>\n */\n checkAuthFn?: () => Promise<boolean> | boolean;\n /**\n * Função para fazer logout\n */\n signOutFn?: () => void;\n /**\n * Estado de autenticação inicial\n */\n initialAuthState?: Partial<AuthState>;\n /**\n * Função para obter dados do usuário (opcional)\n */\n getUserFn?: () => AuthUser | null | undefined;\n /**\n * Função para obter informações da sessão (opcional)\n */\n getSessionFn?: () => SessionInfo | null | undefined;\n /**\n * Função para obter tokens (opcional)\n */\n getTokensFn?: () => AuthTokens | null | undefined;\n}\n\n/**\n * Authentication provider that manages global auth state\n * Compatible with any store (Zustand, Redux, Context, etc.)\n *\n * @param {AuthProviderProps} props - The provider props\n * @returns {JSX.Element} The provider component\n *\n * @example\n * ```tsx\n * <AuthProvider\n * checkAuthFn={checkAuthFunction}\n * signOutFn={signOutFunction}\n * getUserFn={getUserFunction}\n * >\n * <App />\n * </AuthProvider>\n * ```\n */\nexport const AuthProvider = ({\n children,\n checkAuthFn,\n signOutFn,\n initialAuthState = {},\n getUserFn,\n getSessionFn,\n getTokensFn,\n}: AuthProviderProps) => {\n const [authState, setAuthState] = useState<AuthState>({\n isAuthenticated: false,\n isLoading: true,\n ...initialAuthState,\n });\n\n /**\n * Check authentication status and update state accordingly\n *\n * @returns {Promise<boolean>} Promise that resolves to authentication status\n */\n const checkAuth = useCallback(async (): Promise<boolean> => {\n try {\n setAuthState((prev) => ({ ...prev, isLoading: true }));\n\n // Se não há função de verificação, assume como não autenticado\n if (!checkAuthFn) {\n setAuthState((prev) => ({\n ...prev,\n isAuthenticated: false,\n isLoading: false,\n }));\n return false;\n }\n\n const isAuth = await checkAuthFn();\n\n setAuthState((prev) => ({\n ...prev,\n isAuthenticated: isAuth,\n isLoading: false,\n user: getUserFn ? getUserFn() : prev.user,\n sessionInfo: getSessionFn ? getSessionFn() : prev.sessionInfo,\n tokens: getTokensFn ? getTokensFn() : prev.tokens,\n }));\n\n return isAuth;\n } catch (error) {\n console.error('Erro ao verificar autenticação:', error);\n setAuthState((prev) => ({\n ...prev,\n isAuthenticated: false,\n isLoading: false,\n }));\n return false;\n }\n }, [checkAuthFn, getUserFn, getSessionFn, getTokensFn]);\n\n /**\n * Sign out the current user and clear auth state\n *\n * @returns {void}\n */\n const signOut = useCallback(() => {\n if (signOutFn) {\n signOutFn();\n }\n setAuthState((prev) => ({\n ...prev,\n isAuthenticated: false,\n user: undefined,\n sessionInfo: undefined,\n tokens: undefined,\n }));\n }, [signOutFn]);\n\n useEffect(() => {\n checkAuth();\n }, [checkAuth]);\n\n const contextValue = useMemo(\n (): AuthContextType => ({\n ...authState,\n checkAuth,\n signOut,\n }),\n [authState, checkAuth, signOut]\n );\n\n return (\n <AuthContext.Provider value={contextValue}>{children}</AuthContext.Provider>\n );\n};\n\n/**\n * Hook to use the authentication context\n *\n * @throws {Error} When used outside of AuthProvider\n * @returns {AuthContextType} The authentication context\n *\n * @example\n * ```tsx\n * const { isAuthenticated, user, signOut } = useAuth();\n * ```\n */\nexport const useAuth = (): AuthContextType => {\n const context = useContext(AuthContext);\n if (context === undefined) {\n throw new Error('useAuth deve ser usado dentro de um AuthProvider');\n }\n return context;\n};\n\n/**\n * Props for the ProtectedRoute component\n *\n * @interface ProtectedRouteProps\n * @property {ReactNode} children - Components to render when authenticated\n * @property {string} [redirectTo] - Path to redirect when not authenticated (default: '/')\n * @property {ReactNode} [loadingComponent] - Custom loading component\n * @property {(authState: AuthState) => boolean} [additionalCheck] - Additional authentication check\n */\nexport interface ProtectedRouteProps {\n children: ReactNode;\n /**\n * Path para redirecionamento quando não autenticado\n */\n redirectTo?: string;\n /**\n * Componente de loading personalizado\n */\n loadingComponent?: ReactNode;\n /**\n * Função adicional de verificação (ex: verificar permissões específicas)\n */\n additionalCheck?: (authState: AuthState) => boolean;\n}\n\n/**\n * Componente para proteger rotas que requerem autenticação\n *\n * @example\n * ```tsx\n * <ProtectedRoute redirectTo=\"/login\">\n * <PainelPage />\n * </ProtectedRoute>\n * ```\n */\nexport const ProtectedRoute = ({\n children,\n redirectTo = '/',\n loadingComponent,\n additionalCheck,\n}: ProtectedRouteProps) => {\n const { isAuthenticated, isLoading, ...authState } = useAuth();\n\n // Componente de loading padrão\n const defaultLoadingComponent = (\n <div className=\"flex items-center justify-center min-h-screen\">\n <div className=\"text-text-950 text-lg\">Carregando...</div>\n </div>\n );\n\n // Mostrar loading enquanto verifica autenticação\n if (isLoading) {\n return <>{loadingComponent || defaultLoadingComponent}</>;\n }\n\n // Verificar autenticação básica\n if (!isAuthenticated) {\n if (typeof window !== 'undefined') {\n const rootDomain = getRootDomain();\n // Only redirect if the root domain is different from current location\n const currentLocation = `${window.location.protocol}//${window.location.hostname}${window.location.port ? ':' + window.location.port : ''}`;\n if (rootDomain !== currentLocation) {\n window.location.href = rootDomain;\n return null;\n }\n }\n return <Navigate to={redirectTo} replace />;\n }\n\n // Verificação adicional (ex: permissões)\n if (\n additionalCheck &&\n !additionalCheck({ isAuthenticated, isLoading, ...authState })\n ) {\n return <Navigate to={redirectTo} replace />;\n }\n\n return <>{children}</>;\n};\n\n/**\n * Props for the PublicRoute component\n *\n * @interface PublicRouteProps\n * @property {ReactNode} children - Components to render\n * @property {string} [redirectTo] - Path to redirect to (default: '/painel')\n * @property {boolean} [redirectIfAuthenticated] - Whether to redirect if authenticated\n * @property {boolean} [checkAuthBeforeRender] - Whether to check auth before rendering\n */\nexport interface PublicRouteProps {\n children: ReactNode;\n /**\n * Path para redirecionamento\n */\n redirectTo?: string;\n /**\n * Se deve redirecionar quando usuário estiver autenticado\n */\n redirectIfAuthenticated?: boolean;\n /**\n * Se deve verificar autenticação antes de renderizar\n */\n checkAuthBeforeRender?: boolean;\n}\n\n/**\n * Componente para rotas públicas (login, recuperação de senha, etc.)\n * Opcionalmente redireciona se o usuário já estiver autenticado\n *\n * @example\n * ```tsx\n * <PublicRoute redirectTo=\"/painel\" redirectIfAuthenticated={true}>\n * <LoginPage />\n * </PublicRoute>\n * ```\n */\nexport const PublicRoute = ({\n children,\n redirectTo = '/painel',\n redirectIfAuthenticated = false,\n checkAuthBeforeRender = false,\n}: PublicRouteProps) => {\n const { isAuthenticated, isLoading } = useAuth();\n\n // Se deve aguardar verificação de auth antes de renderizar\n if (checkAuthBeforeRender && isLoading) {\n return (\n <div className=\"flex items-center justify-center min-h-screen\">\n <div className=\"text-text-950 text-lg\">Carregando...</div>\n </div>\n );\n }\n\n // Redirecionar se já autenticado e configurado para isso\n if (isAuthenticated && redirectIfAuthenticated) {\n return <Navigate to={redirectTo} replace />;\n }\n\n return <>{children}</>;\n};\n\n/**\n * Higher-Order Component to protect components with authentication\n *\n * @template P - Component props type\n * @param {ComponentType<P>} Component - Component to wrap with authentication\n * @param {Omit<ProtectedRouteProps, 'children'>} [options] - Protection options\n * @returns {(props: P) => JSX.Element} Wrapped component\n *\n * @example\n * ```tsx\n * const ProtectedComponent = withAuth(MyComponent, {\n * redirectTo: \"/login\",\n * loadingComponent: <CustomSpinner />\n * });\n * ```\n */\nexport const withAuth = <P extends object>(\n Component: ComponentType<P>,\n options: Omit<ProtectedRouteProps, 'children'> = {}\n) => {\n return (props: P) => (\n <ProtectedRoute {...options}>\n <Component {...props} />\n </ProtectedRoute>\n );\n};\n\n/**\n * Hook for authentication guard with custom checks\n *\n * @param {object} [options] - Guard options\n * @param {boolean} [options.requireAuth=true] - Whether authentication is required\n * @param {(authState: AuthState) => boolean} [options.customCheck] - Custom check function\n * @returns {object} Guard result with canAccess, isLoading, and authState\n *\n * @example\n * ```tsx\n * const { canAccess, isLoading } = useAuthGuard({\n * requireAuth: true,\n * customCheck: (authState) => authState.user?.role === 'admin'\n * });\n * ```\n */\nexport const useAuthGuard = (\n options: {\n requireAuth?: boolean;\n customCheck?: (authState: AuthState) => boolean;\n } = {}\n) => {\n const authState = useAuth();\n const { requireAuth = true, customCheck } = options;\n\n const canAccess =\n !authState.isLoading &&\n (requireAuth\n ? authState.isAuthenticated && (!customCheck || customCheck(authState))\n : !authState.isAuthenticated || !customCheck || customCheck(authState));\n\n return {\n canAccess,\n isLoading: authState.isLoading,\n authState,\n };\n};\n\n/**\n * Hook to check authentication on specific routes\n * Useful for conditional checks within components\n *\n * @param {string} [fallbackPath='/'] - Path to redirect when not authenticated\n * @returns {object} Object with isAuthenticated, isLoading, and redirectToLogin function\n *\n * @example\n * ```tsx\n * const { isAuthenticated, redirectToLogin } = useRouteAuth();\n *\n * if (!isAuthenticated) {\n * return redirectToLogin();\n * }\n * ```\n */\nexport const useRouteAuth = (fallbackPath = '/') => {\n const { isAuthenticated, isLoading } = useAuth();\n const location = useLocation();\n\n const redirectToLogin = () => (\n <Navigate to={fallbackPath} state={{ from: location }} replace />\n );\n\n return {\n isAuthenticated,\n isLoading,\n redirectToLogin,\n };\n};\n\n/**\n * Get the root domain from the current window location\n * Handles localhost, IP addresses, and subdomain cases, including Brazilian .com.br domains\n *\n * @returns {string} The root domain URL\n *\n * @example\n * ```typescript\n * // Domain examples\n * aluno.analiticaensino.com.br -> analiticaensino.com.br\n * subdomain.example.com -> example.com\n *\n * // IP address examples\n * 127.0.0.1:3000 -> 127.0.0.1:3000\n * [::1]:8080 -> [::1]:8080\n *\n * // Localhost examples\n * localhost:3000 -> localhost:3000\n * ```\n */\nexport const getRootDomain = () => {\n const { hostname, protocol, port } = window.location;\n const portStr = port ? ':' + port : '';\n\n if (hostname === 'localhost') {\n return `${protocol}//${hostname}${portStr}`;\n }\n\n // IP literals: return as-is (no subdomain logic)\n const isIPv4 = /^\\d{1,3}(?:\\.\\d{1,3}){3}$/.test(hostname);\n const isIPv6 = hostname.includes(':'); // simple check is sufficient here\n if (isIPv4 || isIPv6) {\n return `${protocol}//${hostname}${portStr}`;\n }\n\n const parts = hostname.split('.');\n\n // Handle Brazilian .com.br domains and similar patterns\n if (\n parts.length >= 3 &&\n parts[parts.length - 2] === 'com' &&\n parts[parts.length - 1] === 'br'\n ) {\n if (parts.length === 3) {\n // Already at root level for .com.br (e.g., analiticaensino.com.br)\n return `${protocol}//${hostname}${portStr}`;\n }\n // For domains like aluno.analiticaensino.com.br, return analiticaensino.com.br\n const base = parts.slice(-3).join('.');\n return `${protocol}//${base}${portStr}`;\n }\n\n // Only treat as subdomain if there are 3+ parts (e.g., subdomain.example.com)\n if (parts.length > 2) {\n // Return the last 2 parts as the root domain (example.com)\n const base = parts.slice(-2).join('.');\n return `${protocol}//${base}${portStr}`;\n }\n\n // For 2-part domains (example.com) or single domains, return as-is\n return `${protocol}//${hostname}${portStr}`;\n};\n\nexport default {\n AuthProvider,\n ProtectedRoute,\n PublicRoute,\n withAuth,\n useAuth,\n useAuthGuard,\n useRouteAuth,\n};\n"],"mappings":";AAAA;A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ACL;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAsBO,IAAM,gBAAgB,MAAM;AACjC,QAAM,EAAE,UAAU,UAAU,KAAK,IAAI,OAAO;AAC5C,QAAM,UAAU,OAAO,MAAM,OAAO;AAEpC,MAAI,aAAa,aAAa;AAC5B,WAAO,GAAG,QAAQ,KAAK,QAAQ,GAAG,OAAO;AAAA,EAC3C;AAGA,QAAM,SAAS,4BAA4B,KAAK,QAAQ;AACxD,QAAM,SAAS,SAAS,SAAS,GAAG;AACpC,MAAI,UAAU,QAAQ;AACpB,WAAO,GAAG,QAAQ,KAAK,QAAQ,GAAG,OAAO;AAAA,EAC3C;AAEA,QAAM,QAAQ,SAAS,MAAM,GAAG;AAGhC,MACE,MAAM,UAAU,KAChB,MAAM,MAAM,SAAS,CAAC,MAAM,SAC5B,MAAM,MAAM,SAAS,CAAC,MAAM,MAC5B;AACA,QAAI,MAAM,WAAW,GAAG;AAEtB,aAAO,GAAG,QAAQ,KAAK,QAAQ,GAAG,OAAO;AAAA,IAC3C;AAEA,UAAM,OAAO,MAAM,MAAM,EAAE,EAAE,KAAK,GAAG;AACrC,WAAO,GAAG,QAAQ,KAAK,IAAI,GAAG,OAAO;AAAA,EACvC;AAGA,MAAI,MAAM,SAAS,GAAG;AAEpB,UAAM,OAAO,MAAM,MAAM,EAAE,EAAE,KAAK,GAAG;AACrC,WAAO,GAAG,QAAQ,KAAK,IAAI,GAAG,OAAO;AAAA,EACvC;AAGA,SAAO,GAAG,QAAQ,KAAK,QAAQ,GAAG,OAAO;AAC3C;AAEA,IAAO,eAAQ;AAAA,EACb;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../src/components/Auth/Auth.tsx","../../../src/components/Auth/useTokenInUrl.ts"],"sourcesContent":["import {\n createContext,\n useContext,\n useEffect,\n useState,\n ReactNode,\n ComponentType,\n useCallback,\n useMemo,\n} from 'react';\nimport { useLocation, Navigate } from 'react-router-dom';\nimport { useTokenInUrl } from './useTokenInUrl';\n\n/**\n * Interface for basic authentication tokens\n *\n * @interface AuthTokens\n * @property {string} token - Main authentication token\n * @property {string} refreshToken - Token used to refresh the main token\n * @property {unknown} [key] - Additional properties that can be included\n */\nexport interface AuthTokens {\n token: string;\n refreshToken: string;\n [key: string]: unknown;\n}\n\n/**\n * Interface for basic user information\n *\n * @interface AuthUser\n * @property {string} id - Unique user identifier\n * @property {string} [name] - Optional user name\n * @property {string} [email] - Optional user email\n * @property {unknown} [key] - Additional user properties\n */\nexport interface AuthUser {\n id: string;\n name?: string;\n email?: string;\n [key: string]: unknown;\n}\n\n/**\n * Interface for basic session information\n *\n * @interface SessionInfo\n * @property {string} [institutionId] - Optional institution identifier\n * @property {string} [profileId] - Optional profile identifier\n * @property {string} [schoolId] - Optional school identifier\n * @property {string} [schoolYearId] - Optional school year identifier\n * @property {string} [classId] - Optional class identifier\n * @property {unknown} [key] - Additional session properties\n */\nexport interface SessionInfo {\n institutionId?: string;\n profileId?: string;\n schoolId?: string;\n schoolYearId?: string;\n classId?: string;\n [key: string]: unknown;\n}\n\n/**\n * Interface for authentication state\n *\n * @interface AuthState\n * @property {boolean} isAuthenticated - Whether the user is authenticated\n * @property {boolean} isLoading - Whether authentication is being checked\n * @property {AuthUser | null} [user] - Current user information\n * @property {SessionInfo | null} [sessionInfo] - Current session information\n * @property {AuthTokens | null} [tokens] - Current authentication tokens\n */\nexport interface AuthState {\n isAuthenticated: boolean;\n isLoading: boolean;\n user?: AuthUser | null;\n sessionInfo?: SessionInfo | null;\n tokens?: AuthTokens | null;\n}\n\n/**\n * Interface for authentication context functions and state\n *\n * @interface AuthContextType\n * @extends {AuthState}\n * @property {() => Promise<boolean>} checkAuth - Function to check authentication status\n * @property {() => void} signOut - Function to sign out the user\n */\nexport interface AuthContextType extends AuthState {\n checkAuth: () => Promise<boolean>;\n signOut: () => void;\n}\n\n/**\n * Authentication context for React components\n *\n * @private\n */\nconst AuthContext = createContext<AuthContextType | undefined>(undefined);\n\n/**\n * Props for the AuthProvider component\n *\n * @interface AuthProviderProps\n * @property {ReactNode} children - Child components\n * @property {() => Promise<boolean> | boolean} [checkAuthFn] - Function to check if user is authenticated\n * @property {() => void} [signOutFn] - Function to handle logout\n * @property {Partial<AuthState>} [initialAuthState] - Initial authentication state\n * @property {() => AuthUser | null | undefined} [getUserFn] - Function to get user data\n * @property {() => SessionInfo | null | undefined} [getSessionFn] - Function to get session info\n * @property {() => AuthTokens | null | undefined} [getTokensFn] - Function to get tokens\n */\nexport interface AuthProviderProps {\n children: ReactNode;\n /**\n * Função para verificar se o usuário está autenticado\n * Deve retornar uma Promise<boolean>\n */\n checkAuthFn?: () => Promise<boolean> | boolean;\n /**\n * Função para fazer logout\n */\n signOutFn?: () => void;\n /**\n * Estado de autenticação inicial\n */\n initialAuthState?: Partial<AuthState>;\n /**\n * Função para obter dados do usuário (opcional)\n */\n getUserFn?: () => AuthUser | null | undefined;\n /**\n * Função para obter informações da sessão (opcional)\n */\n getSessionFn?: () => SessionInfo | null | undefined;\n /**\n * Função para obter tokens (opcional)\n */\n getTokensFn?: () => AuthTokens | null | undefined;\n}\n\n/**\n * Authentication provider that manages global auth state\n * Compatible with any store (Zustand, Redux, Context, etc.)\n *\n * @param {AuthProviderProps} props - The provider props\n * @returns {JSX.Element} The provider component\n *\n * @example\n * ```tsx\n * <AuthProvider\n * checkAuthFn={checkAuthFunction}\n * signOutFn={signOutFunction}\n * getUserFn={getUserFunction}\n * >\n * <App />\n * </AuthProvider>\n * ```\n */\nexport const AuthProvider = ({\n children,\n checkAuthFn,\n signOutFn,\n initialAuthState = {},\n getUserFn,\n getSessionFn,\n getTokensFn,\n}: AuthProviderProps) => {\n const [authState, setAuthState] = useState<AuthState>({\n isAuthenticated: false,\n isLoading: true,\n ...initialAuthState,\n });\n\n /**\n * Check authentication status and update state accordingly\n *\n * @returns {Promise<boolean>} Promise that resolves to authentication status\n */\n const checkAuth = useCallback(async (): Promise<boolean> => {\n try {\n setAuthState((prev) => ({ ...prev, isLoading: true }));\n\n // Se não há função de verificação, assume como não autenticado\n if (!checkAuthFn) {\n setAuthState((prev) => ({\n ...prev,\n isAuthenticated: false,\n isLoading: false,\n }));\n return false;\n }\n\n const isAuth = await checkAuthFn();\n\n setAuthState((prev) => ({\n ...prev,\n isAuthenticated: isAuth,\n isLoading: false,\n user: getUserFn ? getUserFn() : prev.user,\n sessionInfo: getSessionFn ? getSessionFn() : prev.sessionInfo,\n tokens: getTokensFn ? getTokensFn() : prev.tokens,\n }));\n\n return isAuth;\n } catch (error) {\n console.error('Erro ao verificar autenticação:', error);\n setAuthState((prev) => ({\n ...prev,\n isAuthenticated: false,\n isLoading: false,\n }));\n return false;\n }\n }, [checkAuthFn, getUserFn, getSessionFn, getTokensFn]);\n\n /**\n * Sign out the current user and clear auth state\n *\n * @returns {void}\n */\n const signOut = useCallback(() => {\n if (signOutFn) {\n signOutFn();\n }\n setAuthState((prev) => ({\n ...prev,\n isAuthenticated: false,\n user: undefined,\n sessionInfo: undefined,\n tokens: undefined,\n }));\n }, [signOutFn]);\n\n useEffect(() => {\n checkAuth();\n }, [checkAuth]);\n\n const contextValue = useMemo(\n (): AuthContextType => ({\n ...authState,\n checkAuth,\n signOut,\n }),\n [authState, checkAuth, signOut]\n );\n\n return (\n <AuthContext.Provider value={contextValue}>{children}</AuthContext.Provider>\n );\n};\n\n/**\n * Hook to use the authentication context\n *\n * @throws {Error} When used outside of AuthProvider\n * @returns {AuthContextType} The authentication context\n *\n * @example\n * ```tsx\n * const { isAuthenticated, user, signOut } = useAuth();\n * ```\n */\nexport const useAuth = (): AuthContextType => {\n const context = useContext(AuthContext);\n if (context === undefined) {\n throw new Error('useAuth deve ser usado dentro de um AuthProvider');\n }\n return context;\n};\n\n/**\n * Props for the ProtectedRoute component\n *\n * @interface ProtectedRouteProps\n * @property {ReactNode} children - Components to render when authenticated\n * @property {string} [redirectTo] - Path to redirect when not authenticated (default: '/')\n * @property {ReactNode} [loadingComponent] - Custom loading component\n * @property {(authState: AuthState) => boolean} [additionalCheck] - Additional authentication check\n */\nexport interface ProtectedRouteProps {\n children: ReactNode;\n /**\n * Path para redirecionamento quando não autenticado\n */\n redirectTo?: string;\n /**\n * Componente de loading personalizado\n */\n loadingComponent?: ReactNode;\n /**\n * Função adicional de verificação (ex: verificar permissões específicas)\n */\n additionalCheck?: (authState: AuthState) => boolean;\n}\n\n/**\n * Componente para proteger rotas que requerem autenticação\n *\n * @example\n * ```tsx\n * <ProtectedRoute redirectTo=\"/login\">\n * <PainelPage />\n * </ProtectedRoute>\n * ```\n */\nexport const ProtectedRoute = ({\n children,\n redirectTo = '/',\n loadingComponent,\n additionalCheck,\n}: ProtectedRouteProps) => {\n const { isAuthenticated, isLoading, ...authState } = useAuth();\n\n // Componente de loading padrão\n const defaultLoadingComponent = (\n <div className=\"flex items-center justify-center min-h-screen\">\n <div className=\"text-text-950 text-lg\">Carregando...</div>\n </div>\n );\n\n // Mostrar loading enquanto verifica autenticação\n if (isLoading) {\n return <>{loadingComponent || defaultLoadingComponent}</>;\n }\n\n // Verificar autenticação básica\n if (!isAuthenticated) {\n if (typeof window !== 'undefined') {\n const rootDomain = getRootDomain();\n // Only redirect if the root domain is different from current location\n const currentLocation = `${window.location.protocol}//${window.location.hostname}${window.location.port ? ':' + window.location.port : ''}`;\n if (rootDomain !== currentLocation) {\n window.location.href = rootDomain;\n return null;\n }\n }\n return <Navigate to={redirectTo} replace />;\n }\n\n // Verificação adicional (ex: permissões)\n if (\n additionalCheck &&\n !additionalCheck({ isAuthenticated, isLoading, ...authState })\n ) {\n return <Navigate to={redirectTo} replace />;\n }\n\n return <>{children}</>;\n};\n\n/**\n * Props for the PublicRoute component\n *\n * @interface PublicRouteProps\n * @property {ReactNode} children - Components to render\n * @property {string} [redirectTo] - Path to redirect to (default: '/painel')\n * @property {boolean} [redirectIfAuthenticated] - Whether to redirect if authenticated\n * @property {boolean} [checkAuthBeforeRender] - Whether to check auth before rendering\n * @property {ReactNode} [tokenValidationComponent] - Component to show while validating tokens from URL\n */\nexport interface PublicRouteProps {\n children: ReactNode;\n /**\n * Path para redirecionamento\n */\n redirectTo?: string;\n /**\n * Se deve redirecionar quando usuário estiver autenticado\n */\n redirectIfAuthenticated?: boolean;\n /**\n * Se deve verificar autenticação antes de renderizar\n */\n checkAuthBeforeRender?: boolean;\n /**\n * Componente a ser exibido enquanto valida tokens da URL\n */\n tokenValidationComponent?: ReactNode;\n}\n\n/**\n * Componente para rotas públicas (login, recuperação de senha, etc.)\n * Opcionalmente redireciona se o usuário já estiver autenticado\n *\n * @example\n * ```tsx\n * <PublicRoute redirectTo=\"/painel\" redirectIfAuthenticated={true}>\n * <LoginPage />\n * </PublicRoute>\n * ```\n */\nexport const PublicRoute = ({\n children,\n redirectTo = '/painel',\n redirectIfAuthenticated = false,\n checkAuthBeforeRender = false,\n tokenValidationComponent,\n}: PublicRouteProps) => {\n const { isAuthenticated, isLoading } = useAuth();\n const { hasTokenInUrl } = useTokenInUrl();\n\n // Se tem tokens na URL, mostrar componente de validação (se fornecido)\n if (hasTokenInUrl && tokenValidationComponent) {\n return <>{tokenValidationComponent}</>;\n }\n\n // Se deve aguardar verificação de auth antes de renderizar\n if (checkAuthBeforeRender && isLoading) {\n return (\n <div className=\"flex items-center justify-center min-h-screen\">\n <div className=\"text-text-950 text-lg\">Carregando...</div>\n </div>\n );\n }\n\n // Redirecionar se já autenticado e configurado para isso\n if (isAuthenticated && redirectIfAuthenticated) {\n return <Navigate to={redirectTo} replace />;\n }\n\n return <>{children}</>;\n};\n\n/**\n * Higher-Order Component to protect components with authentication\n *\n * @template P - Component props type\n * @param {ComponentType<P>} Component - Component to wrap with authentication\n * @param {Omit<ProtectedRouteProps, 'children'>} [options] - Protection options\n * @returns {(props: P) => JSX.Element} Wrapped component\n *\n * @example\n * ```tsx\n * const ProtectedComponent = withAuth(MyComponent, {\n * redirectTo: \"/login\",\n * loadingComponent: <CustomSpinner />\n * });\n * ```\n */\nexport const withAuth = <P extends object>(\n Component: ComponentType<P>,\n options: Omit<ProtectedRouteProps, 'children'> = {}\n) => {\n return (props: P) => (\n <ProtectedRoute {...options}>\n <Component {...props} />\n </ProtectedRoute>\n );\n};\n\n/**\n * Hook for authentication guard with custom checks\n *\n * @param {object} [options] - Guard options\n * @param {boolean} [options.requireAuth=true] - Whether authentication is required\n * @param {(authState: AuthState) => boolean} [options.customCheck] - Custom check function\n * @returns {object} Guard result with canAccess, isLoading, and authState\n *\n * @example\n * ```tsx\n * const { canAccess, isLoading } = useAuthGuard({\n * requireAuth: true,\n * customCheck: (authState) => authState.user?.role === 'admin'\n * });\n * ```\n */\nexport const useAuthGuard = (\n options: {\n requireAuth?: boolean;\n customCheck?: (authState: AuthState) => boolean;\n } = {}\n) => {\n const authState = useAuth();\n const { requireAuth = true, customCheck } = options;\n\n const canAccess =\n !authState.isLoading &&\n (requireAuth\n ? authState.isAuthenticated && (!customCheck || customCheck(authState))\n : !authState.isAuthenticated || !customCheck || customCheck(authState));\n\n return {\n canAccess,\n isLoading: authState.isLoading,\n authState,\n };\n};\n\n/**\n * Hook to check authentication on specific routes\n * Useful for conditional checks within components\n *\n * @param {string} [fallbackPath='/'] - Path to redirect when not authenticated\n * @returns {object} Object with isAuthenticated, isLoading, and redirectToLogin function\n *\n * @example\n * ```tsx\n * const { isAuthenticated, redirectToLogin } = useRouteAuth();\n *\n * if (!isAuthenticated) {\n * return redirectToLogin();\n * }\n * ```\n */\nexport const useRouteAuth = (fallbackPath = '/') => {\n const { isAuthenticated, isLoading } = useAuth();\n const location = useLocation();\n\n const redirectToLogin = () => (\n <Navigate to={fallbackPath} state={{ from: location }} replace />\n );\n\n return {\n isAuthenticated,\n isLoading,\n redirectToLogin,\n };\n};\n\n/**\n * Get the root domain from the current window location\n * Handles localhost, IP addresses, and subdomain cases, including Brazilian .com.br domains\n *\n * @returns {string} The root domain URL\n *\n * @example\n * ```typescript\n * // Domain examples\n * aluno.analiticaensino.com.br -> analiticaensino.com.br\n * subdomain.example.com -> example.com\n *\n * // IP address examples\n * 127.0.0.1:3000 -> 127.0.0.1:3000\n * [::1]:8080 -> [::1]:8080\n *\n * // Localhost examples\n * localhost:3000 -> localhost:3000\n * ```\n */\nexport const getRootDomain = () => {\n const { hostname, protocol, port } = window.location;\n const portStr = port ? ':' + port : '';\n\n if (hostname === 'localhost') {\n return `${protocol}//${hostname}${portStr}`;\n }\n\n // IP literals: return as-is (no subdomain logic)\n const isIPv4 = /^\\d{1,3}(?:\\.\\d{1,3}){3}$/.test(hostname);\n const isIPv6 = hostname.includes(':'); // simple check is sufficient here\n if (isIPv4 || isIPv6) {\n return `${protocol}//${hostname}${portStr}`;\n }\n\n const parts = hostname.split('.');\n\n // Handle Brazilian .com.br domains and similar patterns\n if (\n parts.length >= 3 &&\n parts[parts.length - 2] === 'com' &&\n parts[parts.length - 1] === 'br'\n ) {\n if (parts.length === 3) {\n // Already at root level for .com.br (e.g., analiticaensino.com.br)\n return `${protocol}//${hostname}${portStr}`;\n }\n // For domains like aluno.analiticaensino.com.br, return analiticaensino.com.br\n const base = parts.slice(-3).join('.');\n return `${protocol}//${base}${portStr}`;\n }\n\n // Only treat as subdomain if there are 3+ parts (e.g., subdomain.example.com)\n if (parts.length > 2) {\n // Return the last 2 parts as the root domain (example.com)\n const base = parts.slice(-2).join('.');\n return `${protocol}//${base}${portStr}`;\n }\n\n // For 2-part domains (example.com) or single domains, return as-is\n return `${protocol}//${hostname}${portStr}`;\n};\n\nexport default {\n AuthProvider,\n ProtectedRoute,\n PublicRoute,\n withAuth,\n useAuth,\n useAuthGuard,\n useRouteAuth,\n};\n","import { useMemo } from 'react';\nimport { useLocation } from 'react-router-dom';\n\n/**\n * Hook to check if authentication tokens are present in the URL\n *\n * @returns {object} Object with hasTokenInUrl boolean indicating if tokens are present\n *\n * @example\n * ```typescript\n * const { hasTokenInUrl } = useTokenInUrl();\n *\n * if (hasTokenInUrl) {\n * // Show loading/validation component\n * }\n * ```\n */\nexport function useTokenInUrl() {\n const location = useLocation();\n\n const hasTokenInUrl = useMemo(() => {\n const searchParams = new URLSearchParams(location.search);\n const token = searchParams.get('token');\n const refreshToken = searchParams.get('refreshToken');\n const sessionId = searchParams.get('sessionId');\n\n return !!(token && refreshToken && sessionId);\n }, [location.search]);\n\n return { hasTokenInUrl };\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAGA;AAAA,EACA,WAAAA;AAAA,OACK;AACP,SAAS,eAAAC,cAAa,gBAAgB;;;ACVtC,SAAS,eAAe;AACxB,SAAS,mBAAmB;AAgBrB,SAAS,gBAAgB;AAC9B,QAAM,WAAW,YAAY;AAE7B,QAAM,gBAAgB,QAAQ,MAAM;AAClC,UAAM,eAAe,IAAI,gBAAgB,SAAS,MAAM;AACxD,UAAM,QAAQ,aAAa,IAAI,OAAO;AACtC,UAAM,eAAe,aAAa,IAAI,cAAc;AACpD,UAAM,YAAY,aAAa,IAAI,WAAW;AAE9C,WAAO,CAAC,EAAE,SAAS,gBAAgB;AAAA,EACrC,GAAG,CAAC,SAAS,MAAM,CAAC;AAEpB,SAAO,EAAE,cAAc;AACzB;;;AD2NI,SA2EO,UA3EP;AAtJJ,IAAM,cAAc,cAA2C,MAAS;AA6DjE,IAAM,eAAe,CAAC;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA,mBAAmB,CAAC;AAAA,EACpB;AAAA,EACA;AAAA,EACA;AACF,MAAyB;AACvB,QAAM,CAAC,WAAW,YAAY,IAAI,SAAoB;AAAA,IACpD,iBAAiB;AAAA,IACjB,WAAW;AAAA,IACX,GAAG;AAAA,EACL,CAAC;AAOD,QAAM,YAAY,YAAY,YAA8B;AAC1D,QAAI;AACF,mBAAa,CAAC,UAAU,EAAE,GAAG,MAAM,WAAW,KAAK,EAAE;AAGrD,UAAI,CAAC,aAAa;AAChB,qBAAa,CAAC,UAAU;AAAA,UACtB,GAAG;AA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M,UAAU,KAChB,MAAM,MAAM,SAAS,CAAC,MAAM,SAC5B,MAAM,MAAM,SAAS,CAAC,MAAM,MAC5B;AACA,QAAI,MAAM,WAAW,GAAG;AAEtB,aAAO,GAAG,QAAQ,KAAK,QAAQ,GAAG,OAAO;AAAA,IAC3C;AAEA,UAAM,OAAO,MAAM,MAAM,EAAE,EAAE,KAAK,GAAG;AACrC,WAAO,GAAG,QAAQ,KAAK,IAAI,GAAG,OAAO;AAAA,EACvC;AAGA,MAAI,MAAM,SAAS,GAAG;AAEpB,UAAM,OAAO,MAAM,MAAM,EAAE,EAAE,KAAK,GAAG;AACrC,WAAO,GAAG,QAAQ,KAAK,IAAI,GAAG,OAAO;AAAA,EACvC;AAGA,SAAO,GAAG,QAAQ,KAAK,QAAQ,GAAG,OAAO;AAC3C;AAEA,IAAO,eAAQ;AAAA,EACb;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;","names":["useMemo","useLocation","useMemo","useLocation"]}
|
|
@@ -189,6 +189,7 @@ export declare const ProtectedRoute: ({ children, redirectTo, loadingComponent,
|
|
|
189
189
|
* @property {string} [redirectTo] - Path to redirect to (default: '/painel')
|
|
190
190
|
* @property {boolean} [redirectIfAuthenticated] - Whether to redirect if authenticated
|
|
191
191
|
* @property {boolean} [checkAuthBeforeRender] - Whether to check auth before rendering
|
|
192
|
+
* @property {ReactNode} [tokenValidationComponent] - Component to show while validating tokens from URL
|
|
192
193
|
*/
|
|
193
194
|
export interface PublicRouteProps {
|
|
194
195
|
children: ReactNode;
|
|
@@ -204,6 +205,10 @@ export interface PublicRouteProps {
|
|
|
204
205
|
* Se deve verificar autenticação antes de renderizar
|
|
205
206
|
*/
|
|
206
207
|
checkAuthBeforeRender?: boolean;
|
|
208
|
+
/**
|
|
209
|
+
* Componente a ser exibido enquanto valida tokens da URL
|
|
210
|
+
*/
|
|
211
|
+
tokenValidationComponent?: ReactNode;
|
|
207
212
|
}
|
|
208
213
|
/**
|
|
209
214
|
* Componente para rotas públicas (login, recuperação de senha, etc.)
|
|
@@ -216,7 +221,7 @@ export interface PublicRouteProps {
|
|
|
216
221
|
* </PublicRoute>
|
|
217
222
|
* ```
|
|
218
223
|
*/
|
|
219
|
-
export declare const PublicRoute: ({ children, redirectTo, redirectIfAuthenticated, checkAuthBeforeRender, }: PublicRouteProps) => import("react/jsx-runtime").JSX.Element;
|
|
224
|
+
export declare const PublicRoute: ({ children, redirectTo, redirectIfAuthenticated, checkAuthBeforeRender, tokenValidationComponent, }: PublicRouteProps) => import("react/jsx-runtime").JSX.Element;
|
|
220
225
|
/**
|
|
221
226
|
* Higher-Order Component to protect components with authentication
|
|
222
227
|
*
|
|
@@ -303,7 +308,7 @@ export declare const getRootDomain: () => string;
|
|
|
303
308
|
declare const _default: {
|
|
304
309
|
AuthProvider: ({ children, checkAuthFn, signOutFn, initialAuthState, getUserFn, getSessionFn, getTokensFn, }: AuthProviderProps) => import("react/jsx-runtime").JSX.Element;
|
|
305
310
|
ProtectedRoute: ({ children, redirectTo, loadingComponent, additionalCheck, }: ProtectedRouteProps) => import("react/jsx-runtime").JSX.Element | null;
|
|
306
|
-
PublicRoute: ({ children, redirectTo, redirectIfAuthenticated, checkAuthBeforeRender, }: PublicRouteProps) => import("react/jsx-runtime").JSX.Element;
|
|
311
|
+
PublicRoute: ({ children, redirectTo, redirectIfAuthenticated, checkAuthBeforeRender, tokenValidationComponent, }: PublicRouteProps) => import("react/jsx-runtime").JSX.Element;
|
|
307
312
|
withAuth: <P extends object>(Component: ComponentType<P>, options?: Omit<ProtectedRouteProps, "children">) => (props: P) => import("react/jsx-runtime").JSX.Element;
|
|
308
313
|
useAuth: () => AuthContextType;
|
|
309
314
|
useAuthGuard: (options?: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Auth.d.ts","sourceRoot":"","sources":["../../../src/components/Auth/Auth.tsx"],"names":[],"mappings":"AAAA,OAAO,EAKL,SAAS,EACT,aAAa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O,CAAC;IAChC;;OAEG;IACH,wBAAwB,CAAC,EAAE,SAAS,CAAC;CACtC;AAED;;;;;;;;;;GAUG;AACH,eAAO,MAAM,WAAW,GAAI,qGAMzB,gBAAgB,4CAwBlB,CAAC;AAEF;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,QAAQ,GAAI,CAAC,SAAS,MAAM,EACvC,WAAW,aAAa,CAAC,CAAC,CAAC,EAC3B,UAAS,IAAI,CAAC,mBAAmB,EAAE,UAAU,CAAM,MAE3C,OAAO,CAAC,4CAKjB,CAAC;AAEF;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,YAAY,GACvB,UAAS;IACP,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,WAAW,CAAC,EAAE,CAAC,SAAS,EAAE,SAAS,KAAK,OAAO,CAAC;CAC5C;;;;CAgBP,CAAC;AAEF;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,YAAY,GAAI,qBAAkB;;;;CAa9C,CAAC;AAEF;;;;;;;;;;;;;;;;;;;GAmBG;AACH,eAAO,MAAM,aAAa,cAyCzB,CAAC;;kHA9ZC,iBAAiB;mFAgJjB,mBAAmB;uHAuFnB,gBAAgB;eA0CM,CAAC,SAAS,MAAM,aAC5B,aAAa,CAAC,CAAC,CAAC,YAClB,IAAI,CAAC,mBAAmB,EAAE,UAAU,CAAC,MAEtC,OAAO,CAAC;mBArLS,eAAe;6BA6M/B;QACP,WAAW,CAAC,EAAE,OAAO,CAAC;QACtB,WAAW,CAAC,EAAE,CAAC,SAAS,EAAE,SAAS,KAAK,OAAO,CAAC;KACjD;;;;;;;;;;;AAgHH,wBAQE"}
|
|
@@ -31,10 +31,27 @@ __export(Auth_exports, {
|
|
|
31
31
|
withAuth: () => withAuth
|
|
32
32
|
});
|
|
33
33
|
module.exports = __toCommonJS(Auth_exports);
|
|
34
|
+
var import_react2 = require("react");
|
|
35
|
+
var import_react_router_dom2 = require("react-router-dom");
|
|
36
|
+
|
|
37
|
+
// src/components/Auth/useTokenInUrl.ts
|
|
34
38
|
var import_react = require("react");
|
|
35
39
|
var import_react_router_dom = require("react-router-dom");
|
|
40
|
+
function useTokenInUrl() {
|
|
41
|
+
const location = (0, import_react_router_dom.useLocation)();
|
|
42
|
+
const hasTokenInUrl = (0, import_react.useMemo)(() => {
|
|
43
|
+
const searchParams = new URLSearchParams(location.search);
|
|
44
|
+
const token = searchParams.get("token");
|
|
45
|
+
const refreshToken = searchParams.get("refreshToken");
|
|
46
|
+
const sessionId = searchParams.get("sessionId");
|
|
47
|
+
return !!(token && refreshToken && sessionId);
|
|
48
|
+
}, [location.search]);
|
|
49
|
+
return { hasTokenInUrl };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// src/components/Auth/Auth.tsx
|
|
36
53
|
var import_jsx_runtime = require("react/jsx-runtime");
|
|
37
|
-
var AuthContext = (0,
|
|
54
|
+
var AuthContext = (0, import_react2.createContext)(void 0);
|
|
38
55
|
var AuthProvider = ({
|
|
39
56
|
children,
|
|
40
57
|
checkAuthFn,
|
|
@@ -44,12 +61,12 @@ var AuthProvider = ({
|
|
|
44
61
|
getSessionFn,
|
|
45
62
|
getTokensFn
|
|
46
63
|
}) => {
|
|
47
|
-
const [authState, setAuthState] = (0,
|
|
64
|
+
const [authState, setAuthState] = (0, import_react2.useState)({
|
|
48
65
|
isAuthenticated: false,
|
|
49
66
|
isLoading: true,
|
|
50
67
|
...initialAuthState
|
|
51
68
|
});
|
|
52
|
-
const checkAuth = (0,
|
|
69
|
+
const checkAuth = (0, import_react2.useCallback)(async () => {
|
|
53
70
|
try {
|
|
54
71
|
setAuthState((prev) => ({ ...prev, isLoading: true }));
|
|
55
72
|
if (!checkAuthFn) {
|
|
@@ -80,7 +97,7 @@ var AuthProvider = ({
|
|
|
80
97
|
return false;
|
|
81
98
|
}
|
|
82
99
|
}, [checkAuthFn, getUserFn, getSessionFn, getTokensFn]);
|
|
83
|
-
const signOut = (0,
|
|
100
|
+
const signOut = (0, import_react2.useCallback)(() => {
|
|
84
101
|
if (signOutFn) {
|
|
85
102
|
signOutFn();
|
|
86
103
|
}
|
|
@@ -92,10 +109,10 @@ var AuthProvider = ({
|
|
|
92
109
|
tokens: void 0
|
|
93
110
|
}));
|
|
94
111
|
}, [signOutFn]);
|
|
95
|
-
(0,
|
|
112
|
+
(0, import_react2.useEffect)(() => {
|
|
96
113
|
checkAuth();
|
|
97
114
|
}, [checkAuth]);
|
|
98
|
-
const contextValue = (0,
|
|
115
|
+
const contextValue = (0, import_react2.useMemo)(
|
|
99
116
|
() => ({
|
|
100
117
|
...authState,
|
|
101
118
|
checkAuth,
|
|
@@ -106,7 +123,7 @@ var AuthProvider = ({
|
|
|
106
123
|
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AuthContext.Provider, { value: contextValue, children });
|
|
107
124
|
};
|
|
108
125
|
var useAuth = () => {
|
|
109
|
-
const context = (0,
|
|
126
|
+
const context = (0, import_react2.useContext)(AuthContext);
|
|
110
127
|
if (context === void 0) {
|
|
111
128
|
throw new Error("useAuth deve ser usado dentro de um AuthProvider");
|
|
112
129
|
}
|
|
@@ -132,10 +149,10 @@ var ProtectedRoute = ({
|
|
|
132
149
|
return null;
|
|
133
150
|
}
|
|
134
151
|
}
|
|
135
|
-
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
|
|
152
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_router_dom2.Navigate, { to: redirectTo, replace: true });
|
|
136
153
|
}
|
|
137
154
|
if (additionalCheck && !additionalCheck({ isAuthenticated, isLoading, ...authState })) {
|
|
138
|
-
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
|
|
155
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_router_dom2.Navigate, { to: redirectTo, replace: true });
|
|
139
156
|
}
|
|
140
157
|
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, { children });
|
|
141
158
|
};
|
|
@@ -143,14 +160,19 @@ var PublicRoute = ({
|
|
|
143
160
|
children,
|
|
144
161
|
redirectTo = "/painel",
|
|
145
162
|
redirectIfAuthenticated = false,
|
|
146
|
-
checkAuthBeforeRender = false
|
|
163
|
+
checkAuthBeforeRender = false,
|
|
164
|
+
tokenValidationComponent
|
|
147
165
|
}) => {
|
|
148
166
|
const { isAuthenticated, isLoading } = useAuth();
|
|
167
|
+
const { hasTokenInUrl } = useTokenInUrl();
|
|
168
|
+
if (hasTokenInUrl && tokenValidationComponent) {
|
|
169
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, { children: tokenValidationComponent });
|
|
170
|
+
}
|
|
149
171
|
if (checkAuthBeforeRender && isLoading) {
|
|
150
172
|
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "flex items-center justify-center min-h-screen", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "text-text-950 text-lg", children: "Carregando..." }) });
|
|
151
173
|
}
|
|
152
174
|
if (isAuthenticated && redirectIfAuthenticated) {
|
|
153
|
-
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
|
|
175
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_router_dom2.Navigate, { to: redirectTo, replace: true });
|
|
154
176
|
}
|
|
155
177
|
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, { children });
|
|
156
178
|
};
|
|
@@ -169,8 +191,8 @@ var useAuthGuard = (options = {}) => {
|
|
|
169
191
|
};
|
|
170
192
|
var useRouteAuth = (fallbackPath = "/") => {
|
|
171
193
|
const { isAuthenticated, isLoading } = useAuth();
|
|
172
|
-
const location = (0,
|
|
173
|
-
const redirectToLogin = () => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
|
|
194
|
+
const location = (0, import_react_router_dom2.useLocation)();
|
|
195
|
+
const redirectToLogin = () => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_router_dom2.Navigate, { to: fallbackPath, state: { from: location }, replace: true });
|
|
174
196
|
return {
|
|
175
197
|
isAuthenticated,
|
|
176
198
|
isLoading,
|