@autenticar-me/vue 0.15.0 → 0.17.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/README.md CHANGED
@@ -38,6 +38,100 @@ app.mount('#app')
38
38
  - **`useAuth()`** - Gerenciamento de autenticação
39
39
  - **`useTheme()`** - Controle de tema (light/dark)
40
40
 
41
+ ## Verificação Periódica de Autenticação
42
+
43
+ O pacote inclui um sistema automático de verificação de autenticação que monitora o estado de login do usuário a cada 3 segundos. Se a sessão expirar ou o usuário for deslogado no servidor, o logout é executado automaticamente e um evento é emitido.
44
+
45
+ ### Como Funciona
46
+
47
+ - Após o login, a verificação inicia automaticamente
48
+ - A cada 3 segundos, faz uma requisição à rota de perfil do usuário
49
+ - Se a requisição falhar (token inválido, sessão expirada, etc.):
50
+ - Executa logout automático
51
+ - Limpa os dados do usuário
52
+ - Remove tokens dos cookies
53
+ - Emite evento de logout
54
+
55
+ ### Capturando o Evento de Logout
56
+
57
+ Use o método `onLogout()` do composable `useAtm()` para registrar callbacks que serão executados quando o logout ocorrer (manual ou automático):
58
+
59
+ ```vue
60
+ <template>
61
+ <div>
62
+ <h1>Minha Aplicação</h1>
63
+ <UserProfile />
64
+ </div>
65
+ </template>
66
+
67
+ <script setup>
68
+ import { onMounted, onUnmounted } from 'vue'
69
+ import { useAtm } from '@autenticar-me/vue'
70
+ import { useRouter } from 'vue-router'
71
+
72
+ const { onLogout } = useAtm()
73
+ const router = useRouter()
74
+
75
+ onMounted(() => {
76
+ const unsubscribe = onLogout(() => {
77
+ console.log('Usuário foi deslogado')
78
+ router.push('/login')
79
+ })
80
+
81
+ onUnmounted(() => {
82
+ unsubscribe()
83
+ })
84
+ })
85
+ </script>
86
+ ```
87
+
88
+ ### Exemplo com Notificação ao Usuário
89
+
90
+ ```vue
91
+ <script setup>
92
+ import { onMounted, onUnmounted } from 'vue'
93
+ import { useAtm } from '@autenticar-me/vue'
94
+ import { useRouter } from 'vue-router'
95
+
96
+ const { onLogout } = useAtm()
97
+ const router = useRouter()
98
+
99
+ onMounted(() => {
100
+ const unsubscribe = onLogout(() => {
101
+ alert('Sua sessão expirou. Por favor, faça login novamente.')
102
+ router.push('/login')
103
+ })
104
+
105
+ onUnmounted(() => {
106
+ unsubscribe()
107
+ })
108
+ })
109
+ </script>
110
+ ```
111
+
112
+ ### Controle Manual do Polling
113
+
114
+ Caso precise controlar manualmente quando o polling inicia ou para:
115
+
116
+ ```vue
117
+ <script setup>
118
+ import { onMounted, onUnmounted } from 'vue'
119
+ import { useAuth } from '@autenticar-me/vue'
120
+
121
+ const { startAuthPolling, stopAuthPolling } = useAuth()
122
+
123
+ onMounted(() => {
124
+ startAuthPolling()
125
+ })
126
+
127
+ onUnmounted(() => {
128
+ stopAuthPolling()
129
+ })
130
+ </script>
131
+ ```
132
+
133
+ **Nota:** Na maioria dos casos, não é necessário controlar manualmente o polling, pois ele inicia automaticamente após o login e para automaticamente no logout.
134
+
41
135
  ## Componentes
42
136
 
43
137
  ### Formulários de Autenticação
@@ -1 +1 @@
1
- {"version":3,"file":"useAuth.d.ts","sourceRoot":"","sources":["../../src/composables/useAuth.ts"],"names":[],"mappings":"AAMA,wBAAgB,OAAO;;uCAG6B,MAAM,KAAG,OAAO,CAAC,IAAI,CAAC;;;kBAK7C,OAAO,CAAC,IAAI,CAAC;4BAkBT,IAAI;2BAkBL,IAAI;EAgBnC"}
1
+ {"version":3,"file":"useAuth.d.ts","sourceRoot":"","sources":["../../src/composables/useAuth.ts"],"names":[],"mappings":"AAKA,wBAAgB,OAAO;;uCAG6B,MAAM,KAAG,OAAO,CAAC,IAAI,CAAC;;;kBAM7C,OAAO,CAAC,IAAI,CAAC;4BAkBT,IAAI;2BAIL,IAAI;EAanC"}
package/dist/index.cjs CHANGED
@@ -66,11 +66,39 @@ function useAtm() {
66
66
  return ctx;
67
67
  }
68
68
  let authPollingInterval = null;
69
+ const startAuthPolling = (client, user, emitLogout) => {
70
+ if (authPollingInterval !== null) {
71
+ return;
72
+ }
73
+ authPollingInterval = window.setInterval(async () => {
74
+ const hasToken = document.cookie.includes("atm_access_token") || document.cookie.includes("atm_refresh_token");
75
+ if (!hasToken || user.value === null || user.value === void 0) {
76
+ stopAuthPolling();
77
+ emitLogout();
78
+ return;
79
+ }
80
+ try {
81
+ await fetchUser(client, user);
82
+ } catch (error) {
83
+ stopAuthPolling();
84
+ user.value = null;
85
+ writeAccessTokenInCookie(null);
86
+ emitLogout();
87
+ }
88
+ }, 3e3);
89
+ };
90
+ const stopAuthPolling = () => {
91
+ if (authPollingInterval !== null) {
92
+ clearInterval(authPollingInterval);
93
+ authPollingInterval = null;
94
+ }
95
+ };
69
96
  function useAuth() {
70
- const { client, user, isSignedIn, emitLogout } = useAtm();
97
+ const { client, user, emitLogout } = useAtm();
71
98
  const signInByAccessToken = async (accessToken) => {
72
99
  writeAccessTokenInCookie(accessToken);
73
100
  await fetchUser(client, user);
101
+ startAuthPolling(client, user, emitLogout);
74
102
  };
75
103
  const logout = async () => {
76
104
  stopAuthPolling();
@@ -83,26 +111,11 @@ function useAuth() {
83
111
  writeAccessTokenInCookie(null);
84
112
  emitLogout();
85
113
  };
86
- const startAuthPolling = () => {
87
- if (authPollingInterval !== null) {
88
- return;
89
- }
90
- authPollingInterval = window.setInterval(async () => {
91
- if (!isSignedIn.value) {
92
- return;
93
- }
94
- try {
95
- await fetchUser(client, user);
96
- } catch (error) {
97
- await logout();
98
- }
99
- }, 3e3);
114
+ const startAuthPolling$1 = () => {
115
+ startAuthPolling(client, user, emitLogout);
100
116
  };
101
- const stopAuthPolling = () => {
102
- if (authPollingInterval !== null) {
103
- clearInterval(authPollingInterval);
104
- authPollingInterval = null;
105
- }
117
+ const stopAuthPolling$1 = () => {
118
+ stopAuthPolling();
106
119
  };
107
120
  return {
108
121
  user,
@@ -110,8 +123,8 @@ function useAuth() {
110
123
  getAccessToken,
111
124
  fetchUser,
112
125
  logout,
113
- startAuthPolling,
114
- stopAuthPolling
126
+ startAuthPolling: startAuthPolling$1,
127
+ stopAuthPolling: stopAuthPolling$1
115
128
  };
116
129
  }
117
130
  const _hoisted_1$8 = { class: "atm-overlay" };
@@ -2508,7 +2521,12 @@ const atmPlugin = {
2508
2521
  Promise.all([
2509
2522
  fetchUser(client, user),
2510
2523
  fetchConfigurations(client, configurations)
2511
- ]).then(() => isLoaded.value = true);
2524
+ ]).then(() => {
2525
+ isLoaded.value = true;
2526
+ if (user.value !== null && user.value !== void 0) {
2527
+ startAuthPolling(client, user, emitLogout);
2528
+ }
2529
+ });
2512
2530
  app.provide("atm", {
2513
2531
  client,
2514
2532
  user,