@innertia-solutions/innertia-nuxt 0.1.68 → 0.1.70

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.
@@ -1,4 +1,5 @@
1
1
  // useRequestInterceptors auto-imported from nuxt-core
2
+ import { deleteCookie } from 'h3'
2
3
  // useAuthStore auto-imported from this package
3
4
 
4
5
  export function useApi() {
@@ -9,6 +10,10 @@ export function useApi() {
9
10
  ? (config.apiInternalUrl || config.public.apiBaseUrl || '/api')
10
11
  : (config.public.apiBaseUrl || '/api')
11
12
  const loginPath = config.public.loginPath || '/login'
13
+ // Capturados en setup (contexto Nuxt síncrono): tras un await en makeRequest
14
+ // el contexto puede no estar disponible.
15
+ const requestEvent = import.meta.server ? useRequestEvent() : null
16
+ const router = import.meta.client ? useRouter() : null
12
17
 
13
18
  const { run, add } = useRequestInterceptors()
14
19
 
@@ -66,7 +71,19 @@ export function useApi() {
66
71
  if (response.status === 401) {
67
72
  const authStore = useAuthStore()
68
73
  authStore.logout()
69
- await navigateTo(loginPath)
74
+ // La sesión sellada quedó inválida (token revocado, usuario borrado, BD
75
+ // reseteada): hay que BORRARLA. Si no, cada request vuelve "autenticado",
76
+ // guest manda a home, auth/me da 401 y se redirige a login → loop infinito
77
+ // (ERR_TOO_MANY_REDIRECTS).
78
+ if (requestEvent) {
79
+ requestEvent.context.authToken = undefined
80
+ deleteCookie(requestEvent, 'innertia_session', { path: '/' })
81
+ } else if (import.meta.client) {
82
+ try { await $fetch('/_auth/logout', { method: 'POST' }) } catch { /* best-effort */ }
83
+ }
84
+ const current = requestEvent ? requestEvent.path?.split('?')[0] : router?.currentRoute.value.path
85
+ // Ya en una página de login (la del producto o /platform/login): no redirigir.
86
+ if (current !== loginPath && !current?.endsWith('/login')) await navigateTo(loginPath)
70
87
  return null
71
88
  }
72
89
 
@@ -0,0 +1,13 @@
1
+ // Cuenta de plataforma con clave temporal (force_password_change): mientras no
2
+ // defina una nueva, cualquier ruta de /platform la lleva a /platform/change-password.
3
+ // Genérico para todos los productos (identidad de plataforma separada). El backend
4
+ // (Authenticate de innertia-laravel) bloquea igual la API con 403.
5
+ export default defineNuxtRouteMiddleware((to) => {
6
+ if (!to.path.startsWith('/platform')) return
7
+ if (to.path === '/platform/login' || to.path === '/platform/change-password') return
8
+
9
+ const user = useAuthStore().user as any
10
+ if (user?.is_platform_admin && user?.force_password_change) {
11
+ return navigateTo('/platform/change-password', { replace: true })
12
+ }
13
+ })
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@innertia-solutions/innertia-nuxt",
3
- "version": "0.1.68",
3
+ "version": "0.1.70",
4
4
  "description": "Innertia Solutions — Nuxt layer unificada: core, auth, multitenancy, theme y app contexts",
5
5
  "keywords": [
6
6
  "nuxt",
@@ -0,0 +1,83 @@
1
+ <script setup>
2
+ // Cambio de contraseña obligatorio de la cuenta de plataforma (genérico, vía layer).
3
+ // Se llega aquí cuando la cuenta entró con una clave temporal: la por defecto
4
+ // (platform@innertia.cl) o una generada con `php artisan platform:password`.
5
+ // Mientras esté pendiente, el backend responde 403 a todo lo demás y el middleware
6
+ // 05.platform-password redirige aquí.
7
+ definePageMeta({ layout: 'auth' })
8
+
9
+ const api = useApi()
10
+ const authStore = useAuthStore()
11
+ const { logout } = useAuth()
12
+
13
+ const password = ref('')
14
+ const confirmation = ref('')
15
+ const errors = reactive({ password: null, confirmation: null })
16
+ const processing = ref(false)
17
+
18
+ async function handleSubmit() {
19
+ errors.password = null
20
+ errors.confirmation = null
21
+ if (password.value.length < 10) { errors.password = 'Mínimo 10 caracteres, con letras y números.'; return }
22
+ if (password.value !== confirmation.value) { errors.confirmation = 'Las contraseñas no coinciden.'; return }
23
+
24
+ processing.value = true
25
+ try {
26
+ const res = await api.post('platform/auth/password', {
27
+ password: password.value,
28
+ password_confirmation: confirmation.value,
29
+ })
30
+ authStore.saveUser({ ...(authStore.user ?? {}), ...(res?.user ?? {}), force_password_change: false })
31
+ await navigateTo('/platform', { replace: true })
32
+ } catch (e) {
33
+ const body = e?.data ?? {}
34
+ errors.password = body.errors?.password?.[0] ?? body.message ?? 'No se pudo guardar la contraseña.'
35
+ } finally {
36
+ processing.value = false
37
+ }
38
+ }
39
+ </script>
40
+
41
+ <template>
42
+ <div class="space-y-6">
43
+ <div>
44
+ <h1 class="text-2xl font-bold text-foreground">Define tu contraseña</h1>
45
+ <p class="mt-1.5 text-sm text-muted-foreground">
46
+ Entraste con una clave temporal<span v-if="authStore.user?.email"> ({{ authStore.user.email }})</span>.
47
+ Elige una contraseña nueva para continuar a la consola.
48
+ </p>
49
+ </div>
50
+
51
+ <form class="space-y-4" novalidate @submit.prevent="handleSubmit">
52
+ <Forms.Input
53
+ v-model="password"
54
+ type="password"
55
+ label="Contraseña nueva"
56
+ autocomplete="new-password"
57
+ hint="Mínimo 10 caracteres, con letras y números."
58
+ :disabled="processing"
59
+ :error="errors.password"
60
+ />
61
+ <Forms.Input
62
+ v-model="confirmation"
63
+ type="password"
64
+ label="Repite la contraseña"
65
+ autocomplete="new-password"
66
+ :disabled="processing"
67
+ :error="errors.confirmation"
68
+ />
69
+
70
+ <button
71
+ type="submit"
72
+ :disabled="processing"
73
+ class="mt-1 inline-flex w-full items-center justify-center gap-2 rounded-control bg-primary px-4 py-2.5 text-sm font-semibold text-primary-foreground shadow-sm hover:bg-primary-hover disabled:cursor-not-allowed disabled:opacity-60 transition-colors"
74
+ >
75
+ {{ processing ? 'Guardando…' : 'Guardar y continuar' }}
76
+ </button>
77
+ </form>
78
+
79
+ <button type="button" class="w-full text-center text-sm text-muted-foreground hover:text-foreground" @click="logout()">
80
+ Salir
81
+ </button>
82
+ </div>
83
+ </template>
@@ -1,7 +1,7 @@
1
1
  import { defineEventHandler, readBody, createError, getRequestHeader } from 'h3'
2
2
  import { writeSession } from '../../utils/session'
3
3
  import { forwardClientHeaders } from '../../utils/bff'
4
- import { normalizeLoginResponse } from '../../utils/login'
4
+ import { normalizeLoginResponse, loginErrorMessage } from '../../utils/login'
5
5
 
6
6
  // Llama a Laravel /auth/login server-to-server; en éxito sella el JWT en la
7
7
  // sesión y devuelve el body SIN token. Propaga el status de Laravel (403 = el
@@ -18,7 +18,7 @@ export default defineEventHandler(async (event) => {
18
18
  })
19
19
  } catch (err: any) {
20
20
  const status = err?.response?.status ?? err?.statusCode ?? 500
21
- throw createError({ statusCode: status, data: err?.data ?? null, statusMessage: 'login_failed' })
21
+ throw createError({ statusCode: status, data: err?.data ?? null, statusMessage: 'login_failed', message: loginErrorMessage(status, err?.data) })
22
22
  }
23
23
  const { token, body } = normalizeLoginResponse(data)
24
24
  await writeSession(event, { token, currentContext: context })
@@ -1,7 +1,7 @@
1
1
  import { defineEventHandler, readBody, createError, getRequestHeader } from 'h3'
2
2
  import { writeSession } from '../../../utils/session'
3
3
  import { forwardClientHeaders } from '../../../utils/bff'
4
- import { normalizeLoginResponse } from '../../../utils/login'
4
+ import { normalizeLoginResponse, loginErrorMessage } from '../../../utils/login'
5
5
 
6
6
  // Login de plataforma (identidad separada, sin contexto de tenant). Llama a
7
7
  // Laravel /platform/auth/login server-to-server; en éxito sella el JWT en la
@@ -20,7 +20,7 @@ export default defineEventHandler(async (event) => {
20
20
  })
21
21
  } catch (err: any) {
22
22
  const status = err?.response?.status ?? err?.statusCode ?? 500
23
- throw createError({ statusCode: status, data: err?.data ?? null, statusMessage: 'login_failed' })
23
+ throw createError({ statusCode: status, data: err?.data ?? null, statusMessage: 'login_failed', message: loginErrorMessage(status, err?.data) })
24
24
  }
25
25
  const { token, body } = normalizeLoginResponse(data)
26
26
  await writeSession(event, { token })
@@ -1,5 +1,5 @@
1
1
  import { defineEventHandler, proxyRequest, getRequestURL } from 'h3'
2
- import { readSession } from '../../utils/session'
2
+ import { readSession, clearSession } from '../../utils/session'
3
3
  import { resolveApiTarget, buildAuthHeaders } from '../../utils/bff'
4
4
 
5
5
  // BFF: reenvía /api/** a Laravel inyectando el Bearer desde la sesión sellada.
@@ -11,5 +11,12 @@ export default defineEventHandler(async (event) => {
11
11
  const path = (event.context.params?.path ?? '') as string
12
12
  const search = getRequestURL(event).search
13
13
  const target = resolveApiTarget(config.apiInternalUrl, path, search)
14
- return proxyRequest(event, target, { headers: buildAuthHeaders(token) })
14
+ return proxyRequest(event, target, {
15
+ headers: buildAuthHeaders(token),
16
+ // Token rechazado por Laravel → la sesión sellada no sirve: borrarla para que
17
+ // /_auth/session deje de reportar authenticated (evita loops de redirección).
18
+ onResponse: (ev, response) => {
19
+ if (token && response.status === 401) clearSession(ev)
20
+ },
21
+ })
15
22
  })
@@ -1,5 +1,5 @@
1
1
  import { describe, it, expect } from 'vitest'
2
- import { normalizeLoginResponse } from '../login'
2
+ import { normalizeLoginResponse, loginErrorMessage } from '../login'
3
3
 
4
4
  describe('normalizeLoginResponse', () => {
5
5
  it('separa el token del resto', () => {
@@ -14,3 +14,17 @@ describe('normalizeLoginResponse', () => {
14
14
  expect(normalizeLoginResponse({ access_token: 'jwt2' }).token).toBe('jwt2')
15
15
  })
16
16
  })
17
+
18
+ describe('loginErrorMessage', () => {
19
+ it('422 → credenciales incorrectas en español (no el genérico de Laravel)', () => {
20
+ expect(loginErrorMessage(422, { message: 'Invalid credentials.' })).toBe('Correo o contraseña incorrectos.')
21
+ })
22
+ it('429 → throttle', () => {
23
+ expect(loginErrorMessage(429, null)).toContain('Demasiados intentos')
24
+ })
25
+ it('otros → mensaje del backend o fallback', () => {
26
+ expect(loginErrorMessage(403, { message: 'Esta cuenta no tiene acceso al panel de plataforma.' }))
27
+ .toBe('Esta cuenta no tiene acceso al panel de plataforma.')
28
+ expect(loginErrorMessage(500, null)).toBe('No se pudo iniciar sesión. Inténtalo de nuevo.')
29
+ })
30
+ })
@@ -19,3 +19,14 @@ export function normalizeLoginResponse(data: LaravelLoginResponse) {
19
19
  },
20
20
  }
21
21
  }
22
+
23
+ /**
24
+ * Mensaje legible para un login fallido. Va en `message` del error H3 (lo que el
25
+ * cliente lee como e.data.message), en vez del statusMessage técnico 'login_failed'.
26
+ * 422 = credenciales inválidas (Laravel responde un genérico en inglés).
27
+ */
28
+ export function loginErrorMessage(status: number, data: any): string {
29
+ if (status === 422) return 'Correo o contraseña incorrectos.'
30
+ if (status === 429) return 'Demasiados intentos. Espera un minuto e inténtalo de nuevo.'
31
+ return (typeof data?.message === 'string' && data.message) || 'No se pudo iniciar sesión. Inténtalo de nuevo.'
32
+ }