analytica-frontend-lib 1.0.85 → 1.0.87

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.
Files changed (291) hide show
  1. package/dist/Accordation/index.js +0 -1
  2. package/dist/Accordation/index.mjs +0 -1
  3. package/dist/Alert/index.js +0 -1
  4. package/dist/Alert/index.mjs +0 -1
  5. package/dist/AlertDialog/index.js +0 -1
  6. package/dist/AlertDialog/index.mjs +0 -1
  7. package/dist/Alternative/index.js +0 -1
  8. package/dist/Alternative/index.mjs +0 -1
  9. package/dist/Auth/AuthProvider/index.js +0 -1
  10. package/dist/Auth/AuthProvider/index.mjs +0 -1
  11. package/dist/Auth/ProtectedRoute/index.js +0 -1
  12. package/dist/Auth/ProtectedRoute/index.mjs +0 -1
  13. package/dist/Auth/PublicRoute/index.js +0 -1
  14. package/dist/Auth/PublicRoute/index.mjs +0 -1
  15. package/dist/Auth/getRootDomain/index.js +0 -1
  16. package/dist/Auth/getRootDomain/index.mjs +0 -1
  17. package/dist/Auth/index.js +0 -1
  18. package/dist/Auth/index.mjs +0 -1
  19. package/dist/Auth/useApiConfig/index.js +0 -1
  20. package/dist/Auth/useApiConfig/index.mjs +0 -1
  21. package/dist/Auth/useAuth/index.js +0 -1
  22. package/dist/Auth/useAuth/index.mjs +0 -1
  23. package/dist/Auth/useAuthGuard/index.js +0 -1
  24. package/dist/Auth/useAuthGuard/index.mjs +0 -1
  25. package/dist/Auth/useRouteAuth/index.js +0 -1
  26. package/dist/Auth/useRouteAuth/index.mjs +0 -1
  27. package/dist/Auth/useUrlAuthentication/index.js +0 -1
  28. package/dist/Auth/useUrlAuthentication/index.mjs +0 -1
  29. package/dist/Auth/withAuth/index.js +0 -1
  30. package/dist/Auth/withAuth/index.mjs +0 -1
  31. package/dist/Auth/zustandAuthAdapter/index.js +0 -1
  32. package/dist/Auth/zustandAuthAdapter/index.mjs +0 -1
  33. package/dist/Badge/index.js +0 -1
  34. package/dist/Badge/index.mjs +0 -1
  35. package/dist/Button/index.js +0 -1
  36. package/dist/Button/index.mjs +0 -1
  37. package/dist/Calendar/index.js +0 -1
  38. package/dist/Calendar/index.mjs +0 -1
  39. package/dist/Card/index.js +0 -1
  40. package/dist/Card/index.mjs +0 -1
  41. package/dist/CheckBox/index.js +0 -1
  42. package/dist/CheckBox/index.mjs +0 -1
  43. package/dist/Chips/index.js +0 -1
  44. package/dist/Chips/index.mjs +0 -1
  45. package/dist/Divider/index.js +0 -1
  46. package/dist/Divider/index.mjs +0 -1
  47. package/dist/DropdownMenu/index.js +0 -1
  48. package/dist/DropdownMenu/index.mjs +0 -1
  49. package/dist/IconButton/index.js +0 -1
  50. package/dist/IconButton/index.mjs +0 -1
  51. package/dist/IconRoundedButton/index.js +0 -1
  52. package/dist/IconRoundedButton/index.mjs +0 -1
  53. package/dist/Input/index.js +0 -1
  54. package/dist/Input/index.mjs +0 -1
  55. package/dist/Menu/index.js +0 -1
  56. package/dist/Menu/index.mjs +0 -1
  57. package/dist/Modal/index.js +0 -1
  58. package/dist/Modal/index.mjs +0 -1
  59. package/dist/MultipleChoice/index.js +660 -0
  60. package/dist/MultipleChoice/index.mjs +647 -0
  61. package/dist/NavButton/index.js +0 -1
  62. package/dist/NavButton/index.mjs +0 -1
  63. package/dist/NotFound/index.js +0 -1
  64. package/dist/NotFound/index.mjs +0 -1
  65. package/dist/ProgressBar/index.js +0 -1
  66. package/dist/ProgressBar/index.mjs +0 -1
  67. package/dist/ProgressCircle/index.js +0 -1
  68. package/dist/ProgressCircle/index.mjs +0 -1
  69. package/dist/Quiz/index.js +957 -298
  70. package/dist/Quiz/index.mjs +974 -297
  71. package/dist/Quiz/useQuizStore/index.js +79 -35
  72. package/dist/Quiz/useQuizStore/index.mjs +79 -35
  73. package/dist/Radio/index.js +0 -1
  74. package/dist/Radio/index.mjs +0 -1
  75. package/dist/Select/index.js +2 -3
  76. package/dist/Select/index.mjs +2 -3
  77. package/dist/SelectionButton/index.js +0 -1
  78. package/dist/SelectionButton/index.mjs +0 -1
  79. package/dist/Skeleton/index.js +0 -1
  80. package/dist/Skeleton/index.mjs +0 -1
  81. package/dist/Stepper/index.js +0 -1
  82. package/dist/Stepper/index.mjs +0 -1
  83. package/dist/Table/index.js +0 -1
  84. package/dist/Table/index.mjs +0 -1
  85. package/dist/Text/index.js +0 -1
  86. package/dist/Text/index.mjs +0 -1
  87. package/dist/TextArea/index.js +0 -1
  88. package/dist/TextArea/index.mjs +0 -1
  89. package/dist/Toast/ToastStore/index.js +0 -1
  90. package/dist/Toast/ToastStore/index.mjs +0 -1
  91. package/dist/Toast/Toaster/index.js +0 -1
  92. package/dist/Toast/Toaster/index.mjs +0 -1
  93. package/dist/Toast/index.js +0 -1
  94. package/dist/Toast/index.mjs +0 -1
  95. package/dist/index.css +46 -1
  96. package/dist/index.js +1399 -937
  97. package/dist/index.mjs +1340 -868
  98. package/dist/styles.css +46 -1
  99. package/package.json +4 -2
  100. package/dist/Accordation/index.d.mts +0 -12
  101. package/dist/Accordation/index.d.ts +0 -12
  102. package/dist/Accordation/index.js.map +0 -1
  103. package/dist/Accordation/index.mjs.map +0 -1
  104. package/dist/Alert/index.d.mts +0 -13
  105. package/dist/Alert/index.d.ts +0 -13
  106. package/dist/Alert/index.js.map +0 -1
  107. package/dist/Alert/index.mjs.map +0 -1
  108. package/dist/AlertDialog/index.d.mts +0 -36
  109. package/dist/AlertDialog/index.d.ts +0 -36
  110. package/dist/AlertDialog/index.js.map +0 -1
  111. package/dist/AlertDialog/index.mjs.map +0 -1
  112. package/dist/Alternative/index.d.mts +0 -81
  113. package/dist/Alternative/index.d.ts +0 -81
  114. package/dist/Alternative/index.js.map +0 -1
  115. package/dist/Alternative/index.mjs.map +0 -1
  116. package/dist/Auth/AuthProvider/index.d.mts +0 -3
  117. package/dist/Auth/AuthProvider/index.d.ts +0 -3
  118. package/dist/Auth/AuthProvider/index.js.map +0 -1
  119. package/dist/Auth/AuthProvider/index.mjs.map +0 -1
  120. package/dist/Auth/ProtectedRoute/index.d.mts +0 -3
  121. package/dist/Auth/ProtectedRoute/index.d.ts +0 -3
  122. package/dist/Auth/ProtectedRoute/index.js.map +0 -1
  123. package/dist/Auth/ProtectedRoute/index.mjs.map +0 -1
  124. package/dist/Auth/PublicRoute/index.d.mts +0 -3
  125. package/dist/Auth/PublicRoute/index.d.ts +0 -3
  126. package/dist/Auth/PublicRoute/index.js.map +0 -1
  127. package/dist/Auth/PublicRoute/index.mjs.map +0 -1
  128. package/dist/Auth/getRootDomain/index.d.mts +0 -3
  129. package/dist/Auth/getRootDomain/index.d.ts +0 -3
  130. package/dist/Auth/getRootDomain/index.js.map +0 -1
  131. package/dist/Auth/getRootDomain/index.mjs.map +0 -1
  132. package/dist/Auth/index.d.mts +0 -312
  133. package/dist/Auth/index.d.ts +0 -312
  134. package/dist/Auth/index.js.map +0 -1
  135. package/dist/Auth/index.mjs.map +0 -1
  136. package/dist/Auth/useApiConfig/index.d.mts +0 -43
  137. package/dist/Auth/useApiConfig/index.d.ts +0 -43
  138. package/dist/Auth/useApiConfig/index.js.map +0 -1
  139. package/dist/Auth/useApiConfig/index.mjs.map +0 -1
  140. package/dist/Auth/useAuth/index.d.mts +0 -3
  141. package/dist/Auth/useAuth/index.d.ts +0 -3
  142. package/dist/Auth/useAuth/index.js.map +0 -1
  143. package/dist/Auth/useAuth/index.mjs.map +0 -1
  144. package/dist/Auth/useAuthGuard/index.d.mts +0 -3
  145. package/dist/Auth/useAuthGuard/index.d.ts +0 -3
  146. package/dist/Auth/useAuthGuard/index.js.map +0 -1
  147. package/dist/Auth/useAuthGuard/index.mjs.map +0 -1
  148. package/dist/Auth/useRouteAuth/index.d.mts +0 -3
  149. package/dist/Auth/useRouteAuth/index.d.ts +0 -3
  150. package/dist/Auth/useRouteAuth/index.js.map +0 -1
  151. package/dist/Auth/useRouteAuth/index.mjs.map +0 -1
  152. package/dist/Auth/useUrlAuthentication/index.d.mts +0 -58
  153. package/dist/Auth/useUrlAuthentication/index.d.ts +0 -58
  154. package/dist/Auth/useUrlAuthentication/index.js.map +0 -1
  155. package/dist/Auth/useUrlAuthentication/index.mjs.map +0 -1
  156. package/dist/Auth/withAuth/index.d.mts +0 -3
  157. package/dist/Auth/withAuth/index.d.ts +0 -3
  158. package/dist/Auth/withAuth/index.js.map +0 -1
  159. package/dist/Auth/withAuth/index.mjs.map +0 -1
  160. package/dist/Auth/zustandAuthAdapter/index.d.mts +0 -75
  161. package/dist/Auth/zustandAuthAdapter/index.d.ts +0 -75
  162. package/dist/Auth/zustandAuthAdapter/index.js.map +0 -1
  163. package/dist/Auth/zustandAuthAdapter/index.mjs.map +0 -1
  164. package/dist/Badge/index.d.mts +0 -46
  165. package/dist/Badge/index.d.ts +0 -46
  166. package/dist/Badge/index.js.map +0 -1
  167. package/dist/Badge/index.mjs.map +0 -1
  168. package/dist/Button/index.d.mts +0 -45
  169. package/dist/Button/index.d.ts +0 -45
  170. package/dist/Button/index.js.map +0 -1
  171. package/dist/Button/index.mjs.map +0 -1
  172. package/dist/Calendar/index.d.mts +0 -60
  173. package/dist/Calendar/index.d.ts +0 -60
  174. package/dist/Calendar/index.js.map +0 -1
  175. package/dist/Calendar/index.mjs.map +0 -1
  176. package/dist/Card/index.d.mts +0 -150
  177. package/dist/Card/index.d.ts +0 -150
  178. package/dist/Card/index.js.map +0 -1
  179. package/dist/Card/index.mjs.map +0 -1
  180. package/dist/CheckBox/index.d.mts +0 -74
  181. package/dist/CheckBox/index.d.ts +0 -74
  182. package/dist/CheckBox/index.js.map +0 -1
  183. package/dist/CheckBox/index.mjs.map +0 -1
  184. package/dist/Chips/index.d.mts +0 -41
  185. package/dist/Chips/index.d.ts +0 -41
  186. package/dist/Chips/index.js.map +0 -1
  187. package/dist/Chips/index.mjs.map +0 -1
  188. package/dist/Divider/index.d.mts +0 -32
  189. package/dist/Divider/index.d.ts +0 -32
  190. package/dist/Divider/index.js.map +0 -1
  191. package/dist/Divider/index.mjs.map +0 -1
  192. package/dist/DropdownMenu/index.d.mts +0 -68
  193. package/dist/DropdownMenu/index.d.ts +0 -68
  194. package/dist/DropdownMenu/index.js.map +0 -1
  195. package/dist/DropdownMenu/index.mjs.map +0 -1
  196. package/dist/IconButton/index.d.mts +0 -76
  197. package/dist/IconButton/index.d.ts +0 -76
  198. package/dist/IconButton/index.js.map +0 -1
  199. package/dist/IconButton/index.mjs.map +0 -1
  200. package/dist/IconRoundedButton/index.d.mts +0 -34
  201. package/dist/IconRoundedButton/index.d.ts +0 -34
  202. package/dist/IconRoundedButton/index.js.map +0 -1
  203. package/dist/IconRoundedButton/index.mjs.map +0 -1
  204. package/dist/Input/index.d.mts +0 -27
  205. package/dist/Input/index.d.ts +0 -27
  206. package/dist/Input/index.js.map +0 -1
  207. package/dist/Input/index.mjs.map +0 -1
  208. package/dist/Menu/index.d.mts +0 -48
  209. package/dist/Menu/index.d.ts +0 -48
  210. package/dist/Menu/index.js.map +0 -1
  211. package/dist/Menu/index.mjs.map +0 -1
  212. package/dist/Modal/index.d.mts +0 -66
  213. package/dist/Modal/index.d.ts +0 -66
  214. package/dist/Modal/index.js.map +0 -1
  215. package/dist/Modal/index.mjs.map +0 -1
  216. package/dist/NavButton/index.d.mts +0 -57
  217. package/dist/NavButton/index.d.ts +0 -57
  218. package/dist/NavButton/index.js.map +0 -1
  219. package/dist/NavButton/index.mjs.map +0 -1
  220. package/dist/NotFound/index.d.mts +0 -58
  221. package/dist/NotFound/index.d.ts +0 -58
  222. package/dist/NotFound/index.js.map +0 -1
  223. package/dist/NotFound/index.mjs.map +0 -1
  224. package/dist/ProgressBar/index.d.mts +0 -95
  225. package/dist/ProgressBar/index.d.ts +0 -95
  226. package/dist/ProgressBar/index.js.map +0 -1
  227. package/dist/ProgressBar/index.mjs.map +0 -1
  228. package/dist/ProgressCircle/index.d.mts +0 -60
  229. package/dist/ProgressCircle/index.d.ts +0 -60
  230. package/dist/ProgressCircle/index.js.map +0 -1
  231. package/dist/ProgressCircle/index.mjs.map +0 -1
  232. package/dist/Quiz/index.d.mts +0 -52
  233. package/dist/Quiz/index.d.ts +0 -52
  234. package/dist/Quiz/index.js.map +0 -1
  235. package/dist/Quiz/index.mjs.map +0 -1
  236. package/dist/Quiz/useQuizStore/index.d.mts +0 -140
  237. package/dist/Quiz/useQuizStore/index.d.ts +0 -140
  238. package/dist/Quiz/useQuizStore/index.js.map +0 -1
  239. package/dist/Quiz/useQuizStore/index.mjs.map +0 -1
  240. package/dist/Radio/index.d.mts +0 -203
  241. package/dist/Radio/index.d.ts +0 -203
  242. package/dist/Radio/index.js.map +0 -1
  243. package/dist/Radio/index.mjs.map +0 -1
  244. package/dist/Select/index.d.mts +0 -58
  245. package/dist/Select/index.d.ts +0 -58
  246. package/dist/Select/index.js.map +0 -1
  247. package/dist/Select/index.mjs.map +0 -1
  248. package/dist/SelectionButton/index.d.mts +0 -57
  249. package/dist/SelectionButton/index.d.ts +0 -57
  250. package/dist/SelectionButton/index.js.map +0 -1
  251. package/dist/SelectionButton/index.mjs.map +0 -1
  252. package/dist/Skeleton/index.d.mts +0 -40
  253. package/dist/Skeleton/index.d.ts +0 -40
  254. package/dist/Skeleton/index.js.map +0 -1
  255. package/dist/Skeleton/index.mjs.map +0 -1
  256. package/dist/Stepper/index.d.mts +0 -169
  257. package/dist/Stepper/index.d.ts +0 -169
  258. package/dist/Stepper/index.js.map +0 -1
  259. package/dist/Stepper/index.mjs.map +0 -1
  260. package/dist/Table/index.d.mts +0 -17
  261. package/dist/Table/index.d.ts +0 -17
  262. package/dist/Table/index.js.map +0 -1
  263. package/dist/Table/index.mjs.map +0 -1
  264. package/dist/Text/index.d.mts +0 -58
  265. package/dist/Text/index.d.ts +0 -58
  266. package/dist/Text/index.js.map +0 -1
  267. package/dist/Text/index.mjs.map +0 -1
  268. package/dist/TextArea/index.d.mts +0 -70
  269. package/dist/TextArea/index.d.ts +0 -70
  270. package/dist/TextArea/index.js.map +0 -1
  271. package/dist/TextArea/index.mjs.map +0 -1
  272. package/dist/Toast/ToastStore/index.d.mts +0 -19
  273. package/dist/Toast/ToastStore/index.d.ts +0 -19
  274. package/dist/Toast/ToastStore/index.js.map +0 -1
  275. package/dist/Toast/ToastStore/index.mjs.map +0 -1
  276. package/dist/Toast/Toaster/index.d.mts +0 -16
  277. package/dist/Toast/Toaster/index.d.ts +0 -16
  278. package/dist/Toast/Toaster/index.js.map +0 -1
  279. package/dist/Toast/Toaster/index.mjs.map +0 -1
  280. package/dist/Toast/index.d.mts +0 -17
  281. package/dist/Toast/index.d.ts +0 -17
  282. package/dist/Toast/index.js.map +0 -1
  283. package/dist/Toast/index.mjs.map +0 -1
  284. package/dist/index.css.map +0 -1
  285. package/dist/index.d.mts +0 -41
  286. package/dist/index.d.ts +0 -41
  287. package/dist/index.js.map +0 -1
  288. package/dist/index.mjs.map +0 -1
  289. package/dist/styles.css.map +0 -1
  290. package/dist/styles.d.mts +0 -2
  291. package/dist/styles.d.ts +0 -2
@@ -1 +0,0 @@
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 and subdomain cases\n *\n * @returns {string} The root domain URL\n */\nexport const getRootDomain = () => {\n const { hostname, protocol, port } = window.location;\n const portStr = port ? ':' + port : '';\n if (hostname === 'localhost') {\n return `${protocol}//${hostname}${portStr}`;\n }\n const parts = hostname.split('.');\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 // 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,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O;AAAA,EACvC;AAEA,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 +0,0 @@
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 and subdomain cases\n *\n * @returns {string} The root domain URL\n */\nexport const getRootDomain = () => {\n const { hostname, protocol, port } = window.location;\n const portStr = port ? ':' + port : '';\n if (hostname === 'localhost') {\n return `${protocol}//${hostname}${portStr}`;\n }\n const parts = hostname.split('.');\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 // 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,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAGA;AAAA,EACA;AAAA,OACK;AACP,SAAS,aAAa,gBAAgB;AA8OlC,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;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,QAC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YACJ,CAAC,UAAU,cACV,cACG,UAAU,oBAAoB,CAAC,eAAe,YAAY,SAAS,KACnE,CAAC,UAAU,mBAAmB,CAAC,eAAe,YAAY,SAAS;AAEzE,SAAO;AAAA,IACL;AAAA,IACA,WAAW,UAAU;AAAA,IACrB;AAAA,EACF;AACF;AAkBO,IAAM,eAAe,CAAC,eAAe,QAAQ;AAClD,QAAM,EAAE,iBAAiB,UAAU,IAAI,QAAQ;AAC/C,QAAM,WAAW,YAAY;AAE7B,QAAM,kBAAkB,MACtB,oBAAC,YAAS,IAAI,cAAc,OAAO,EAAE,MAAM,SAAS,GAAG,SAAO,MAAC;AAGjE,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAQO,IAAM,gBAAgB,MAAM;AACjC,QAAM,EAAE,UAAU,UAAU,KAAK,IAAI,OAAO;AAC5C,QAAM,UAAU,OAAO,MAAM,OAAO;AACpC,MAAI,aAAa,aAAa;AAC5B,WAAO,GAAG,QAAQ,KAAK,QAAQ,GAAG,OAAO;AAAA,EAC3C;AACA,QAAM,QAAQ,SAAS,MAAM,GAAG;AAEhC,MAAI,MAAM,SAAS,GAAG;AAEpB,UAAM,OAAO,MAAM,MAAM,EAAE,EAAE,KAAK,GAAG;AACrC,WAAO,GAAG,QAAQ,KAAK,IAAI,GAAG,OAAO;AAAA,EACvC;AAEA,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,3 +0,0 @@
1
- import 'react/jsx-runtime';
2
- import 'react';
3
- export { AuthContextType, AuthProvider, AuthProviderProps, AuthState, AuthTokens, AuthUser, ProtectedRoute, ProtectedRouteProps, PublicRoute, PublicRouteProps, SessionInfo, default, getRootDomain, useAuth, useAuthGuard, useRouteAuth, withAuth } from '../index.mjs';
@@ -1,3 +0,0 @@
1
- import 'react/jsx-runtime';
2
- import 'react';
3
- export { AuthContextType, AuthProvider, AuthProviderProps, AuthState, AuthTokens, AuthUser, ProtectedRoute, ProtectedRouteProps, PublicRoute, PublicRouteProps, SessionInfo, default, getRootDomain, useAuth, useAuthGuard, useRouteAuth, withAuth } from '../index.js';
@@ -1 +0,0 @@
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 and subdomain cases\n *\n * @returns {string} The root domain URL\n */\nexport const getRootDomain = () => {\n const { hostname, protocol, port } = window.location;\n const portStr = port ? ':' + port : '';\n if (hostname === 'localhost') {\n return `${protocol}//${hostname}${portStr}`;\n }\n const parts = hostname.split('.');\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 // 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,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Ac,MAAM,YAAY,IAAI;AAE5C,QAAM,YACJ,CAAC,UAAU,cACV,cACG,UAAU,oBAAoB,CAAC,eAAe,YAAY,SAAS,KACnE,CAAC,UAAU,mBAAmB,CAAC,eAAe,YAAY,SAAS;AAEzE,SAAO;AAAA,IACL;AAAA,IACA,WAAW,UAAU;AAAA,IACrB;AAAA,EACF;AACF;AAkBO,IAAM,eAAe,CAAC,eAAe,QAAQ;AAClD,QAAM,EAAE,iBAAiB,UAAU,IAAI,QAAQ;AAC/C,QAAM,eAAW,qCAAY;AAE7B,QAAM,kBAAkB,MACtB,4CAAC,oCAAS,IAAI,cAAc,OAAO,EAAE,MAAM,SAAS,GAAG,SAAO,MAAC;AAGjE,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAQO,IAAM,gBAAgB,MAAM;AACjC,QAAM,EAAE,UAAU,UAAU,KAAK,IAAI,OAAO;AAC5C,QAAM,UAAU,OAAO,MAAM,OAAO;AACpC,MAAI,aAAa,aAAa;AAC5B,WAAO,GAAG,QAAQ,KAAK,QAAQ,GAAG,OAAO;AAAA,EAC3C;AACA,QAAM,QAAQ,SAAS,MAAM,GAAG;AAEhC,MAAI,MAAM,SAAS,GAAG;AAEpB,UAAM,OAAO,MAAM,MAAM,EAAE,EAAE,KAAK,GAAG;AACrC,WAAO,GAAG,QAAQ,KAAK,IAAI,GAAG,OAAO;AAAA,EACvC;AAEA,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 +0,0 @@
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 and subdomain cases\n *\n * @returns {string} The root domain URL\n */\nexport const getRootDomain = () => {\n const { hostname, protocol, port } = window.location;\n const portStr = port ? ':' + port : '';\n if (hostname === 'localhost') {\n return `${protocol}//${hostname}${portStr}`;\n }\n const parts = hostname.split('.');\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 // 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 useAu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AAM,SAAS,GAAG,SAAO,MAAC;AAGjE,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAQO,IAAM,gBAAgB,MAAM;AACjC,QAAM,EAAE,UAAU,UAAU,KAAK,IAAI,OAAO;AAC5C,QAAM,UAAU,OAAO,MAAM,OAAO;AACpC,MAAI,aAAa,aAAa;AAC5B,WAAO,GAAG,QAAQ,KAAK,QAAQ,GAAG,OAAO;AAAA,EAC3C;AACA,QAAM,QAAQ,SAAS,MAAM,GAAG;AAEhC,MAAI,MAAM,SAAS,GAAG;AAEpB,UAAM,OAAO,MAAM,MAAM,EAAE,EAAE,KAAK,GAAG;AACrC,WAAO,GAAG,QAAQ,KAAK,IAAI,GAAG,OAAO;AAAA,EACvC;AAEA,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,58 +0,0 @@
1
- /**
2
- * Options interface for the useUrlAuthentication hook
3
- *
4
- * @template Tokens - Type for authentication tokens
5
- * @template Session - Type for session information
6
- * @template Profile - Type for profile information
7
- *
8
- * @interface UseUrlAuthOptions
9
- * @property {(tokens: Tokens) => void} setTokens - Function to set authentication tokens
10
- * @property {(session: Session) => void} setSessionInfo - Function to set session information
11
- * @property {(profile: Profile) => void} [setSelectedProfile] - Optional function to set selected profile
12
- * @property {object} api - API instance with get method
13
- * @property {(endpoint: string, config: unknown) => Promise<unknown>} api.get - API get method
14
- * @property {string} endpoint - API endpoint to fetch session data
15
- * @property {(searchParams: URLSearchParams) => object} [extractParams] - Custom parameter extraction function
16
- * @property {() => void} [clearParamsFromURL] - Function to clear URL parameters after processing
17
- */
18
- interface UseUrlAuthOptions<Tokens = unknown, Session = unknown, Profile = unknown> {
19
- setTokens: (tokens: Tokens) => void;
20
- setSessionInfo: (session: Session) => void;
21
- setSelectedProfile?: (profile: Profile) => void;
22
- api: {
23
- get: (endpoint: string, config: unknown) => Promise<unknown>;
24
- };
25
- endpoint: string;
26
- extractParams?: (searchParams: URLSearchParams) => {
27
- sessionId: string;
28
- token: string;
29
- refreshToken: string;
30
- };
31
- clearParamsFromURL?: () => void;
32
- }
33
- /**
34
- * Hook for handling URL-based authentication
35
- * Extracts authentication parameters from URL and processes them
36
- *
37
- * @template Tokens - Type for authentication tokens
38
- * @template Session - Type for session information
39
- * @template Profile - Type for profile information
40
- *
41
- * @param {UseUrlAuthOptions<Tokens, Session, Profile>} options - Configuration options
42
- * @returns {void}
43
- *
44
- * @example
45
- * ```typescript
46
- * useUrlAuthentication({
47
- * setTokens: (tokens) => authStore.setTokens(tokens),
48
- * setSessionInfo: (session) => authStore.setSessionInfo(session),
49
- * setSelectedProfile: (profile) => authStore.setProfile(profile),
50
- * api: apiInstance,
51
- * endpoint: '/auth/session',
52
- * clearParamsFromURL: () => navigate('/', { replace: true })
53
- * });
54
- * ```
55
- */
56
- declare function useUrlAuthentication<Tokens = unknown, Session = unknown, Profile = unknown>(options: UseUrlAuthOptions<Tokens, Session, Profile>): void;
57
-
58
- export { type UseUrlAuthOptions, useUrlAuthentication };
@@ -1,58 +0,0 @@
1
- /**
2
- * Options interface for the useUrlAuthentication hook
3
- *
4
- * @template Tokens - Type for authentication tokens
5
- * @template Session - Type for session information
6
- * @template Profile - Type for profile information
7
- *
8
- * @interface UseUrlAuthOptions
9
- * @property {(tokens: Tokens) => void} setTokens - Function to set authentication tokens
10
- * @property {(session: Session) => void} setSessionInfo - Function to set session information
11
- * @property {(profile: Profile) => void} [setSelectedProfile] - Optional function to set selected profile
12
- * @property {object} api - API instance with get method
13
- * @property {(endpoint: string, config: unknown) => Promise<unknown>} api.get - API get method
14
- * @property {string} endpoint - API endpoint to fetch session data
15
- * @property {(searchParams: URLSearchParams) => object} [extractParams] - Custom parameter extraction function
16
- * @property {() => void} [clearParamsFromURL] - Function to clear URL parameters after processing
17
- */
18
- interface UseUrlAuthOptions<Tokens = unknown, Session = unknown, Profile = unknown> {
19
- setTokens: (tokens: Tokens) => void;
20
- setSessionInfo: (session: Session) => void;
21
- setSelectedProfile?: (profile: Profile) => void;
22
- api: {
23
- get: (endpoint: string, config: unknown) => Promise<unknown>;
24
- };
25
- endpoint: string;
26
- extractParams?: (searchParams: URLSearchParams) => {
27
- sessionId: string;
28
- token: string;
29
- refreshToken: string;
30
- };
31
- clearParamsFromURL?: () => void;
32
- }
33
- /**
34
- * Hook for handling URL-based authentication
35
- * Extracts authentication parameters from URL and processes them
36
- *
37
- * @template Tokens - Type for authentication tokens
38
- * @template Session - Type for session information
39
- * @template Profile - Type for profile information
40
- *
41
- * @param {UseUrlAuthOptions<Tokens, Session, Profile>} options - Configuration options
42
- * @returns {void}
43
- *
44
- * @example
45
- * ```typescript
46
- * useUrlAuthentication({
47
- * setTokens: (tokens) => authStore.setTokens(tokens),
48
- * setSessionInfo: (session) => authStore.setSessionInfo(session),
49
- * setSelectedProfile: (profile) => authStore.setProfile(profile),
50
- * api: apiInstance,
51
- * endpoint: '/auth/session',
52
- * clearParamsFromURL: () => navigate('/', { replace: true })
53
- * });
54
- * ```
55
- */
56
- declare function useUrlAuthentication<Tokens = unknown, Session = unknown, Profile = unknown>(options: UseUrlAuthOptions<Tokens, Session, Profile>): void;
57
-
58
- export { type UseUrlAuthOptions, useUrlAuthentication };
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../src/components/Auth/useUrlAuthentication.ts"],"sourcesContent":["import { useEffect } from 'react';\nimport { useLocation } from 'react-router-dom';\n\n/**\n * Options interface for the useUrlAuthentication hook\n *\n * @template Tokens - Type for authentication tokens\n * @template Session - Type for session information\n * @template Profile - Type for profile information\n *\n * @interface UseUrlAuthOptions\n * @property {(tokens: Tokens) => void} setTokens - Function to set authentication tokens\n * @property {(session: Session) => void} setSessionInfo - Function to set session information\n * @property {(profile: Profile) => void} [setSelectedProfile] - Optional function to set selected profile\n * @property {object} api - API instance with get method\n * @property {(endpoint: string, config: unknown) => Promise<unknown>} api.get - API get method\n * @property {string} endpoint - API endpoint to fetch session data\n * @property {(searchParams: URLSearchParams) => object} [extractParams] - Custom parameter extraction function\n * @property {() => void} [clearParamsFromURL] - Function to clear URL parameters after processing\n */\nexport interface UseUrlAuthOptions<\n Tokens = unknown,\n Session = unknown,\n Profile = unknown,\n> {\n setTokens: (tokens: Tokens) => void;\n setSessionInfo: (session: Session) => void;\n setSelectedProfile?: (profile: Profile) => void;\n api: { get: (endpoint: string, config: unknown) => Promise<unknown> };\n endpoint: string;\n extractParams?: (searchParams: URLSearchParams) => {\n sessionId: string;\n token: string;\n refreshToken: string;\n };\n clearParamsFromURL?: () => void;\n}\n\n/**\n * Helper function to extract authentication parameters from URL\n *\n * @param {object} location - Location object with search property\n * @param {string} location.search - URL search string\n * @param {function} [extractParams] - Custom parameter extraction function\n * @returns {object} Object with sessionId, token, and refreshToken\n *\n * @private\n */\nconst getAuthParams = (\n location: { search: string },\n extractParams?: (searchParams: URLSearchParams) => {\n sessionId: string;\n token: string;\n refreshToken: string;\n }\n) => {\n const searchParams = new URLSearchParams(location.search);\n return extractParams\n ? extractParams(searchParams)\n : {\n sessionId: searchParams.get('sessionId'),\n token: searchParams.get('token'),\n refreshToken: searchParams.get('refreshToken'),\n };\n};\n\n/**\n * Helper function to validate authentication parameters\n *\n * @param {object} authParams - Authentication parameters object\n * @param {string | null} authParams.sessionId - Session ID from URL\n * @param {string | null} authParams.token - Authentication token from URL\n * @param {string | null} authParams.refreshToken - Refresh token from URL\n * @returns {boolean} True if all required parameters are present\n *\n * @private\n */\nconst hasValidAuthParams = (authParams: {\n sessionId: string | null;\n token: string | null;\n refreshToken: string | null;\n}) => {\n return !!(\n authParams?.sessionId &&\n authParams?.token &&\n authParams?.refreshToken\n );\n};\n\n/**\n * Helper function to check if response has valid profile data\n *\n * @param {unknown} data - Response data to validate\n * @returns {data is Record<string, unknown>} Type guard for valid profile data\n *\n * @private\n */\nconst hasValidProfileData = (\n data: unknown\n): data is Record<string, unknown> => {\n return data !== null && typeof data === 'object' && data !== undefined;\n};\n\n/**\n * Helper function to handle profile selection from response data\n *\n * @template Profile - Profile type\n * @param {unknown} responseData - Response data from API\n * @param {(profile: Profile) => void} [setSelectedProfile] - Optional function to set selected profile\n * @returns {void}\n *\n * @private\n */\nconst handleProfileSelection = <Profile>(\n responseData: unknown,\n setSelectedProfile?: (profile: Profile) => void\n) => {\n if (!setSelectedProfile) return;\n if (!hasValidProfileData(responseData)) return;\n\n const profileId = responseData.profileId;\n const isValidProfileId = profileId !== null && profileId !== undefined;\n\n if (isValidProfileId) {\n setSelectedProfile({\n id: profileId,\n } as Profile);\n }\n};\n\n/**\n * Hook for handling URL-based authentication\n * Extracts authentication parameters from URL and processes them\n *\n * @template Tokens - Type for authentication tokens\n * @template Session - Type for session information\n * @template Profile - Type for profile information\n *\n * @param {UseUrlAuthOptions<Tokens, Session, Profile>} options - Configuration options\n * @returns {void}\n *\n * @example\n * ```typescript\n * useUrlAuthentication({\n * setTokens: (tokens) => authStore.setTokens(tokens),\n * setSessionInfo: (session) => authStore.setSessionInfo(session),\n * setSelectedProfile: (profile) => authStore.setProfile(profile),\n * api: apiInstance,\n * endpoint: '/auth/session',\n * clearParamsFromURL: () => navigate('/', { replace: true })\n * });\n * ```\n */\nexport function useUrlAuthentication<\n Tokens = unknown,\n Session = unknown,\n Profile = unknown,\n>(options: UseUrlAuthOptions<Tokens, Session, Profile>) {\n const location = useLocation();\n\n useEffect(() => {\n /**\n * Main authentication handler that processes URL parameters\n *\n * @returns {Promise<void>}\n * @private\n */\n const handleAuthentication = async () => {\n const authParams = getAuthParams(location, options.extractParams);\n\n if (!hasValidAuthParams(authParams)) {\n return;\n }\n\n try {\n options.setTokens({\n token: authParams.token,\n refreshToken: authParams.refreshToken,\n } as Tokens);\n\n const response = (await options.api.get(options.endpoint, {\n headers: {\n Authorization: `Bearer ${authParams.token}`,\n },\n })) as { data: { data: unknown; [key: string]: unknown } };\n\n options.setSessionInfo(response.data.data as Session);\n handleProfileSelection(response.data.data, options.setSelectedProfile);\n options.clearParamsFromURL?.();\n } catch (error) {\n console.error('Erro ao obter informações da sessão:', error);\n }\n };\n\n handleAuthentication();\n }, [\n location.search,\n options.setSessionInfo,\n options.setSelectedProfile,\n options.setTokens,\n options.api,\n options.endpoint,\n options.extractParams,\n options.clearParamsFromURL,\n ]);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAA0B;AAC1B,8BAA4B;AA+C5B,IAAM,gBAAgB,CACpB,UACA,kBAKG;AACH,QAAM,eAAe,IAAI,gBAAgB,SAAS,MAAM;AACxD,SAAO,gBACH,cAAc,YAAY,IAC1B;AAAA,IACE,WAAW,aAAa,IAAI,WAAW;AAAA,IACvC,OAAO,aAAa,IAAI,OAAO;AAAA,IAC/B,cAAc,aAAa,IAAI,cAAc;AAAA,EAC/C;AACN;AAaA,IAAM,qBAAqB,CAAC,eAItB;AACJ,SAAO,CAAC,EACN,YAAY,aACZ,YAAY,SACZ,YAAY;AAEhB;AAUA,IAAM,sBAAsB,CAC1B,SACoC;AACpC,SAAO,SAAS,QAAQ,OAAO,SAAS,YAAY,SAAS;AAC/D;AAYA,IAAM,yBAAyB,CAC7B,cACA,uBACG;AACH,MAAI,CAAC,mBAAoB;AACzB,MAAI,CAAC,oBAAoB,YAAY,EAAG;AAExC,QAAM,YAAY,aAAa;AAC/B,QAAM,mBAAmB,cAAc,QAAQ,cAAc;AAE7D,MAAI,kBAAkB;AACpB,uBAAmB;AAAA,MACjB,IAAI;AAAA,IACN,CAAY;AAAA,EACd;AACF;AAyBO,SAAS,qBAId,SAAsD;AACtD,QAAM,eAAW,qCAAY;AAE7B,8BAAU,MAAM;AAOd,UAAM,uBAAuB,YAAY;AACvC,YAAM,aAAa,cAAc,UAAU,QAAQ,aAAa;AAEhE,UAAI,CAAC,mBAAmB,UAAU,GAAG;AACnC;AAAA,MACF;AAEA,UAAI;AACF,gBAAQ,UAAU;AAAA,UAChB,OAAO,WAAW;AAAA,UAClB,cAAc,WAAW;AAAA,QAC3B,CAAW;AAEX,cAAM,WAAY,MAAM,QAAQ,IAAI,IAAI,QAAQ,UAAU;AAAA,UACxD,SAAS;AAAA,YACP,eAAe,UAAU,WAAW,KAAK;AAAA,UAC3C;AAAA,QACF,CAAC;AAED,gBAAQ,eAAe,SAAS,KAAK,IAAe;AACpD,+BAAuB,SAAS,KAAK,MAAM,QAAQ,kBAAkB;AACrE,gBAAQ,qBAAqB;AAAA,MAC/B,SAAS,OAAO;AACd,gBAAQ,MAAM,iDAAwC,KAAK;AAAA,MAC7D;AAAA,IACF;AAEA,yBAAqB;AAAA,EACvB,GAAG;AAAA,IACD,SAAS;AAAA,IACT,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,QAAQ;AAAA,EACV,CAAC;AACH;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../src/components/Auth/useUrlAuthentication.ts"],"sourcesContent":["import { useEffect } from 'react';\nimport { useLocation } from 'react-router-dom';\n\n/**\n * Options interface for the useUrlAuthentication hook\n *\n * @template Tokens - Type for authentication tokens\n * @template Session - Type for session information\n * @template Profile - Type for profile information\n *\n * @interface UseUrlAuthOptions\n * @property {(tokens: Tokens) => void} setTokens - Function to set authentication tokens\n * @property {(session: Session) => void} setSessionInfo - Function to set session information\n * @property {(profile: Profile) => void} [setSelectedProfile] - Optional function to set selected profile\n * @property {object} api - API instance with get method\n * @property {(endpoint: string, config: unknown) => Promise<unknown>} api.get - API get method\n * @property {string} endpoint - API endpoint to fetch session data\n * @property {(searchParams: URLSearchParams) => object} [extractParams] - Custom parameter extraction function\n * @property {() => void} [clearParamsFromURL] - Function to clear URL parameters after processing\n */\nexport interface UseUrlAuthOptions<\n Tokens = unknown,\n Session = unknown,\n Profile = unknown,\n> {\n setTokens: (tokens: Tokens) => void;\n setSessionInfo: (session: Session) => void;\n setSelectedProfile?: (profile: Profile) => void;\n api: { get: (endpoint: string, config: unknown) => Promise<unknown> };\n endpoint: string;\n extractParams?: (searchParams: URLSearchParams) => {\n sessionId: string;\n token: string;\n refreshToken: string;\n };\n clearParamsFromURL?: () => void;\n}\n\n/**\n * Helper function to extract authentication parameters from URL\n *\n * @param {object} location - Location object with search property\n * @param {string} location.search - URL search string\n * @param {function} [extractParams] - Custom parameter extraction function\n * @returns {object} Object with sessionId, token, and refreshToken\n *\n * @private\n */\nconst getAuthParams = (\n location: { search: string },\n extractParams?: (searchParams: URLSearchParams) => {\n sessionId: string;\n token: string;\n refreshToken: string;\n }\n) => {\n const searchParams = new URLSearchParams(location.search);\n return extractParams\n ? extractParams(searchParams)\n : {\n sessionId: searchParams.get('sessionId'),\n token: searchParams.get('token'),\n refreshToken: searchParams.get('refreshToken'),\n };\n};\n\n/**\n * Helper function to validate authentication parameters\n *\n * @param {object} authParams - Authentication parameters object\n * @param {string | null} authParams.sessionId - Session ID from URL\n * @param {string | null} authParams.token - Authentication token from URL\n * @param {string | null} authParams.refreshToken - Refresh token from URL\n * @returns {boolean} True if all required parameters are present\n *\n * @private\n */\nconst hasValidAuthParams = (authParams: {\n sessionId: string | null;\n token: string | null;\n refreshToken: string | null;\n}) => {\n return !!(\n authParams?.sessionId &&\n authParams?.token &&\n authParams?.refreshToken\n );\n};\n\n/**\n * Helper function to check if response has valid profile data\n *\n * @param {unknown} data - Response data to validate\n * @returns {data is Record<string, unknown>} Type guard for valid profile data\n *\n * @private\n */\nconst hasValidProfileData = (\n data: unknown\n): data is Record<string, unknown> => {\n return data !== null && typeof data === 'object' && data !== undefined;\n};\n\n/**\n * Helper function to handle profile selection from response data\n *\n * @template Profile - Profile type\n * @param {unknown} responseData - Response data from API\n * @param {(profile: Profile) => void} [setSelectedProfile] - Optional function to set selected profile\n * @returns {void}\n *\n * @private\n */\nconst handleProfileSelection = <Profile>(\n responseData: unknown,\n setSelectedProfile?: (profile: Profile) => void\n) => {\n if (!setSelectedProfile) return;\n if (!hasValidProfileData(responseData)) return;\n\n const profileId = responseData.profileId;\n const isValidProfileId = profileId !== null && profileId !== undefined;\n\n if (isValidProfileId) {\n setSelectedProfile({\n id: profileId,\n } as Profile);\n }\n};\n\n/**\n * Hook for handling URL-based authentication\n * Extracts authentication parameters from URL and processes them\n *\n * @template Tokens - Type for authentication tokens\n * @template Session - Type for session information\n * @template Profile - Type for profile information\n *\n * @param {UseUrlAuthOptions<Tokens, Session, Profile>} options - Configuration options\n * @returns {void}\n *\n * @example\n * ```typescript\n * useUrlAuthentication({\n * setTokens: (tokens) => authStore.setTokens(tokens),\n * setSessionInfo: (session) => authStore.setSessionInfo(session),\n * setSelectedProfile: (profile) => authStore.setProfile(profile),\n * api: apiInstance,\n * endpoint: '/auth/session',\n * clearParamsFromURL: () => navigate('/', { replace: true })\n * });\n * ```\n */\nexport function useUrlAuthentication<\n Tokens = unknown,\n Session = unknown,\n Profile = unknown,\n>(options: UseUrlAuthOptions<Tokens, Session, Profile>) {\n const location = useLocation();\n\n useEffect(() => {\n /**\n * Main authentication handler that processes URL parameters\n *\n * @returns {Promise<void>}\n * @private\n */\n const handleAuthentication = async () => {\n const authParams = getAuthParams(location, options.extractParams);\n\n if (!hasValidAuthParams(authParams)) {\n return;\n }\n\n try {\n options.setTokens({\n token: authParams.token,\n refreshToken: authParams.refreshToken,\n } as Tokens);\n\n const response = (await options.api.get(options.endpoint, {\n headers: {\n Authorization: `Bearer ${authParams.token}`,\n },\n })) as { data: { data: unknown; [key: string]: unknown } };\n\n options.setSessionInfo(response.data.data as Session);\n handleProfileSelection(response.data.data, options.setSelectedProfile);\n options.clearParamsFromURL?.();\n } catch (error) {\n console.error('Erro ao obter informações da sessão:', error);\n }\n };\n\n handleAuthentication();\n }, [\n location.search,\n options.setSessionInfo,\n options.setSelectedProfile,\n options.setTokens,\n options.api,\n options.endpoint,\n options.extractParams,\n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e;AACpD,+BAAuB,SAAS,KAAK,MAAM,QAAQ,kBAAkB;AACrE,gBAAQ,qBAAqB;AAAA,MAC/B,SAAS,OAAO;AACd,gBAAQ,MAAM,iDAAwC,KAAK;AAAA,MAC7D;AAAA,IACF;AAEA,yBAAqB;AAAA,EACvB,GAAG;AAAA,IACD,SAAS;AAAA,IACT,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,QAAQ;AAAA,EACV,CAAC;AACH;","names":[]}
@@ -1,3 +0,0 @@
1
- import 'react/jsx-runtime';
2
- import 'react';
3
- export { AuthContextType, AuthProvider, AuthProviderProps, AuthState, AuthTokens, AuthUser, ProtectedRoute, ProtectedRouteProps, PublicRoute, PublicRouteProps, SessionInfo, default, getRootDomain, useAuth, useAuthGuard, useRouteAuth, withAuth } from '../index.mjs';
@@ -1,3 +0,0 @@
1
- import 'react/jsx-runtime';
2
- import 'react';
3
- export { AuthContextType, AuthProvider, AuthProviderProps, AuthState, AuthTokens, AuthUser, ProtectedRoute, ProtectedRouteProps, PublicRoute, PublicRouteProps, SessionInfo, default, getRootDomain, useAuth, useAuthGuard, useRouteAuth, withAuth } from '../index.js';
@@ -1 +0,0 @@
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 and subdomain cases\n *\n * @returns {string} The root domain URL\n */\nexport const getRootDomain = () => {\n const { hostname, protocol, port } = window.location;\n const portStr = port ? ':' + port : '';\n if (hostname === 'localhost') {\n return `${protocol}//${hostname}${portStr}`;\n }\n const parts = hostname.split('.');\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 // 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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AG,QAAQ,KAAK,QAAQ,GAAG,OAAO;AAAA,EAC3C;AACA,QAAM,QAAQ,SAAS,MAAM,GAAG;AAEhC,MAAI,MAAM,SAAS,GAAG;AAEpB,UAAM,OAAO,MAAM,MAAM,EAAE,EAAE,KAAK,GAAG;AACrC,WAAO,GAAG,QAAQ,KAAK,IAAI,GAAG,OAAO;AAAA,EACvC;AAEA,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 +0,0 @@
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 and subdomain cases\n *\n * @returns {string} The root domain URL\n */\nexport const getRootDomain = () => {\n const { hostname, protocol, port } = window.location;\n const portStr = port ? ':' + port : '';\n if (hostname === 'localhost') {\n return `${protocol}//${hostname}${portStr}`;\n }\n const parts = hostname.split('.');\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 // 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,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAGA;AAAA,EACA;AAAA,OACK;AACP,SAAS,aAAa,gBAAgB;AA8OlC,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;AAAA,UACH,iBAAiB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1,75 +0,0 @@
1
- /**
2
- * Generic adapter for integrating AuthProvider with Zustand stores
3
- * Users should import this file and pass their store instance
4
- *
5
- * @template S - Zustand store type that contains auth-related state
6
- * @param {object} useAuthStore - Zustand store hook with getState method
7
- * @param {() => S} useAuthStore.getState - Function to get current store state
8
- * @returns {object} Adapter object with auth functions
9
- *
10
- * @example
11
- * ```typescript
12
- * // Define your Zustand store type
13
- * interface AuthStore {
14
- * sessionInfo?: SessionInfo;
15
- * tokens?: AuthTokens;
16
- * user?: AuthUser;
17
- * signOut: () => void;
18
- * }
19
- *
20
- * // Create the adapter
21
- * const authAdapter = createZustandAuthAdapter(useAuthStore);
22
- *
23
- * // Use with AuthProvider
24
- * <AuthProvider
25
- * checkAuthFn={authAdapter.checkAuth}
26
- * signOutFn={authAdapter.signOut}
27
- * getUserFn={authAdapter.getUser}
28
- * getSessionFn={authAdapter.getSessionInfo}
29
- * getTokensFn={authAdapter.getTokens}
30
- * >
31
- * <App />
32
- * </AuthProvider>
33
- * ```
34
- */
35
- declare function createZustandAuthAdapter<S extends {
36
- sessionInfo?: unknown;
37
- tokens?: unknown;
38
- user?: unknown;
39
- signOut?: () => void;
40
- }>(useAuthStore: {
41
- getState: () => S;
42
- }): {
43
- /**
44
- * Check if the user is authenticated based on sessionInfo and tokens
45
- *
46
- * @returns {Promise<boolean>} Promise that resolves to authentication status
47
- */
48
- checkAuth: () => Promise<boolean>;
49
- /**
50
- * Get the current user from the store
51
- *
52
- * @returns {unknown} Current user data from the store
53
- */
54
- getUser: () => unknown;
55
- /**
56
- * Get the current session information from the store
57
- *
58
- * @returns {unknown} Current session info from the store
59
- */
60
- getSessionInfo: () => unknown;
61
- /**
62
- * Get the current authentication tokens from the store
63
- *
64
- * @returns {unknown} Current tokens from the store
65
- */
66
- getTokens: () => unknown;
67
- /**
68
- * Sign out the user by calling the store's signOut function if available
69
- *
70
- * @returns {void}
71
- */
72
- signOut: () => void;
73
- };
74
-
75
- export { createZustandAuthAdapter };