@riligar/auth-react 1.17.0 → 1.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js CHANGED
@@ -60,6 +60,8 @@ async function api(route, opts = {}) {
60
60
  }
61
61
  const res = await fetch(url, {
62
62
  headers,
63
+ credentials: 'include',
64
+ // Required for sending session cookies
63
65
  ...opts
64
66
  });
65
67
 
@@ -390,46 +392,33 @@ const useAuthStore = create((set, get) => ({
390
392
  try {
391
393
  // Buscar application info primeiro (não bloqueia o init)
392
394
  fetchApplicationInfo();
395
+ let user = null;
393
396
 
394
- // Verifica se um token válido
395
- if (isAuthenticated()) {
396
- // Tenta extrair usuário do token (JWT)
397
- let user = getCurrentUser();
398
-
399
- // Se o token for opaco (não-JWT), getCurrentUser retorna null.
400
- // Precisamos buscar a sessão no servidor.
401
- if (!user) {
402
- try {
403
- const sessionData = await getSession();
404
- if (sessionData?.user) {
405
- user = sessionData.user;
406
- }
407
- if (sessionData?.session) {
408
- set({
409
- currentSession: sessionData.session
410
- });
411
- }
412
- } catch (sessionError) {
413
- console.warn('[AuthStore] Failed to fetch session:', sessionError);
414
- }
397
+ // PRIMEIRO: Tenta buscar sessão do servidor (funciona com cookies)
398
+ // Isso é essencial para Better Auth que usa session cookies
399
+ try {
400
+ const sessionData = await getSession();
401
+ if (sessionData?.user) {
402
+ user = sessionData.user;
415
403
  }
416
- if (user) {
417
- set({
418
- user,
419
- loading: false
420
- });
421
- } else {
404
+ if (sessionData?.session) {
422
405
  set({
423
- user: null,
424
- loading: false
406
+ currentSession: sessionData.session
425
407
  });
426
408
  }
427
- } else {
428
- set({
429
- user: null,
430
- loading: false
431
- });
409
+ } catch (sessionError) {
410
+ // Se falhar (401), continua para verificar localStorage token
411
+ console.log('[AuthStore] Server session not found, checking local token');
432
412
  }
413
+
414
+ // SEGUNDO: Se não encontrou sessão via cookies, verifica localStorage token (JWT)
415
+ if (!user && isAuthenticated()) {
416
+ user = getCurrentUser();
417
+ }
418
+ set({
419
+ user,
420
+ loading: false
421
+ });
433
422
  } catch (error) {
434
423
  console.error('Erro na inicialização:', error);
435
424
  set({
@@ -707,19 +696,41 @@ const useAuthStore = create((set, get) => ({
707
696
  throw err;
708
697
  }
709
698
  },
710
- revokeSession: async token => {
699
+ revokeSession: async sessionId => {
711
700
  const {
712
701
  setLoading,
713
- listSessions
702
+ currentSession,
703
+ sessions,
704
+ signOut
714
705
  } = get();
715
706
  setLoading('revokeSession', true);
716
707
  set({
717
708
  error: null
718
709
  });
719
710
  try {
720
- await revokeSession(token);
721
- // Refresh sessions list after revocation
722
- await listSessions();
711
+ console.log('[AuthStore] Revoking session:', {
712
+ targetId: sessionId,
713
+ currentId: currentSession?.id,
714
+ totalSessions: sessions.length
715
+ });
716
+
717
+ // Detect if current session OR last remaining session
718
+ const isCurrent = sessionId === currentSession?.id;
719
+ const isLast = sessions.length === 1 && sessions[0].id === sessionId;
720
+
721
+ // Se for a sessão atual ou a última, faz logout normal
722
+ if (isCurrent || isLast) {
723
+ console.log('[AuthStore] Revoking current/last session -> Executing signOut');
724
+ await signOut();
725
+ // signOut já limpa loading states e erros no finally, mas
726
+ // como estamos dentro do fluxo deste método, garantimos:
727
+ setLoading('revokeSession', false);
728
+ return;
729
+ }
730
+ await revokeSession(sessionId);
731
+
732
+ // NÃO atualiza a lista automaticamente - se for a sessão atual,
733
+ // listSessions() vai falhar com 401. O componente decide se quer atualizar.
723
734
  setLoading('revokeSession', false);
724
735
  } catch (err) {
725
736
  set({
@@ -941,6 +952,8 @@ function AuthProvider({
941
952
  });
942
953
  // Dispara evento de logout para sincronizar entre abas
943
954
  localStorage.setItem('auth:logout', Date.now());
955
+ // Recarrega para redirecionar - deixa o Protect/rotas decidirem para onde ir
956
+ window.location.reload();
944
957
  };
945
958
  window.addEventListener('storage', handleStorageChange);
946
959
  window.addEventListener('auth:session-revoked', handleSessionRevoked);