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