# Secuencia de autenticacion

```mermaid
sequenceDiagram
  actor Usuario
  participant Login as LoginPageComponent
  participant AuthFE as AuthService Angular
  participant Interceptor as authInterceptor
  participant AuthRoute as POST /api/auth/login
  participant AuthBE as auth.service.js
  participant DB as PostgreSQL
  participant Router as Angular Router

  Usuario->>Login: Ingresa usuario y contrasena
  Login->>AuthFE: login(identifier, password)
  AuthFE->>AuthRoute: POST /api/auth/login
  AuthRoute->>AuthBE: login(pool, credenciales, metadata)
  AuthBE->>DB: SELECT usuario por lower(username)
  DB-->>AuthBE: app_users
  AuthBE->>AuthBE: verifyPassword con crypto.scryptSync
  AuthBE->>AuthBE: genera token aleatorio base64url
  AuthBE->>AuthBE: hashToken SHA-256 con AUTH_TOKEN_SECRET
  AuthBE->>DB: INSERT app_sessions(token_hash, user_id, expires_at, user_agent, ip_address)
  DB-->>AuthBE: OK
  AuthBE-->>AuthRoute: user, accessToken, expiresAt
  AuthRoute-->>AuthFE: { ok: true, data }
  AuthFE->>AuthFE: setSession signals y localStorage
  AuthFE-->>Login: AuthSession
  Login->>Router: navigateByUrl(redirect o /dashboard)

  Usuario->>Router: Abre ruta protegida
  Router->>AuthFE: authGuard revisa isAuthenticated()
  AuthFE-->>Router: true si hay token y usuario

  Usuario->>AuthFE: Peticion protegida posterior
  AuthFE->>Interceptor: HttpClient request
  Interceptor->>AuthFE: getAccessToken()
  Interceptor->>AuthRoute: Authorization Bearer accessToken
  AuthRoute->>AuthBE: requireAuth -> authenticateToken()
  AuthBE->>DB: SELECT app_sessions JOIN app_users por token_hash vigente
  DB-->>AuthBE: usuario activo
  AuthBE->>DB: UPDATE app_sessions SET last_used_at = NOW()
  AuthBE-->>AuthRoute: req.user
```

## Archivos analizados

- `semillero/src/app/features/auth/login-page.component.ts`
- `semillero/src/app/core/services/auth.service.ts`
- `semillero/src/app/core/guards/auth.guard.ts`
- `semillero/src/app/core/interceptors/auth.interceptor.ts`
- `backend/src/routes/auth.routes.js`
- `backend/src/middlewares/auth.middleware.js`
- `backend/src/auth/auth.service.js`
- `backend/src/config/env.js`
- `backend/src/db/pool.js`
