Domain

AuthEntity

Entità di dominio per l'autenticazione — credenziali, richieste registrazione/reset, risposte token e custom response. Include type guards runtime.

Cos'è

AuthEntity raccoglie tutti i tipi DTO scambiati tra client e server PostgREST nel flusso di autenticazione: credenziali in input, dati di registrazione, risposte token e generic CustomResponse per operazioni server-side che restituiscono solo conferma.

Tutti i tipi sono importabili come pure type:

import type {
  UserCredentials,
  RegisterUser,
  ResetPassword,
  ForgotPassword,
  AuthResponse,
  AuthRefresh,
  CustomResponse,
} from '@pzeta/postgrest'

import { isAuthResponse, isCustomResponse } from '@pzeta/postgrest'

Tipi

UserCredentials

Credenziali login (input di client.login()).

interface UserCredentials {
  email: string
  password: string
}
CampoTipoRequiredDescrizione
emailstringEmail utente
passwordstringPassword in plaintext (TLS only)

RegisterUser

Dati per registrazione nuovo utente (input di client.register()). Tutti i campi sono opzionali: la libreria non impone uno schema rigido — è il server PostgREST a validare.

interface RegisterUser {
  name?: string
  email?: string
  password?: string
  phone?: string
  role?: string
}
CampoTipoRequiredDescrizione
namestringNome completo
emailstringEmail (tipicamente obbligatoria server-side)
passwordstringPassword in plaintext
phonestringTelefono
rolestringRuolo richiesto (server può ignorare/sovrascrivere)

ForgotPassword

Richiesta inizio flusso recupero password.

interface ForgotPassword {
  email: string
}

ResetPassword

Completamento reset password con token ricevuto via email.

interface ResetPassword {
  token: string
  newPassword: string
}
CampoTipoRequiredDescrizione
tokenstringToken ricevuto via email
newPasswordstringNuova password in plaintext

AuthResponse

Risposta server al login/refresh con coppia di token JWT.

interface AuthResponse {
  token: string
  refreshToken: string
}
CampoTipoRequiredDescrizione
tokenstringAccess token JWT (header Authorization: Bearer <token>)
refreshTokenstringRefresh token (usato da client.refreshToken() per rinnovare l'access token)

AuthRefresh

Body inviato dal client per rinnovare l'access token.

interface AuthRefresh {
  refreshToken: string | null
}

CustomResponse

Risposta server generica per operazioni che restituiscono solo esito (registrazione, attivazione, reset password).

interface CustomResponse {
  success: boolean
  message: string
  data?: Record<string, unknown>
  error?: string
}
CampoTipoRequiredDescrizione
successbooleantrue se l'operazione è riuscita
messagestringMessaggio user-facing
dataRecord<string, unknown>Payload opzionale (es. info utente attivato)
errorstringCodice/dettaglio errore se success === false

Type Guards

isAuthResponse(obj)

function isAuthResponse(obj: unknown): obj is AuthResponse

Verifica runtime che un oggetto sia un AuthResponse valido (presenza e tipo di token e refreshToken come stringhe).

import { isAuthResponse } from '@pzeta/postgrest'

const response = await fetchAuth()

if (isAuthResponse(response)) {
  // response è tipizzato come AuthResponse
  console.log('Token:', response.token)
} else {
  console.error('Risposta auth non valida')
}

isCustomResponse(obj)

function isCustomResponse(obj: unknown): obj is CustomResponse

Verifica runtime: success boolean, message string, data undefined o object, error undefined o string.

import { isCustomResponse } from '@pzeta/postgrest'

const result = await client.register({ email, password })

if (isCustomResponse(result) && result.success) {
  showToast(result.message)
} else if (isCustomResponse(result)) {
  showError(result.error ?? result.message)
}

Esempio — Flusso auth completo con AuthService

import {
  PostgRESTClient,
  isAuthResponse,
  isCustomResponse,
  type UserCredentials,
  type RegisterUser,
} from '@pzeta/postgrest'

const client = new PostgRESTClient({ apiUrl: 'https://api.example.com' })
await client.init()

// 1. Registrazione
const regResult = await client.register({
  email: 'nuovo@example.com',
  password: 'Password123!',
  name: 'Mario Rossi',
} satisfies RegisterUser)

if (isCustomResponse(regResult) && regResult.success) {
  console.log(regResult.message) // "Controlla la tua email..."
}

// 2. Attivazione account (dal link email)
const token = new URLSearchParams(location.search).get('token')
if (token) {
  await client.activateAccount(token)
}

// 3. Login
const auth = await client.login({
  email: 'nuovo@example.com',
  password: 'Password123!',
} satisfies UserCredentials)

if (auth && isAuthResponse(auth)) {
  console.log('Logged in, token:', auth.token)
}

// 4. Logout
await client.logout()

Tipi correlati

  • IAuthService — servizio che orchestra il flusso usando questi tipi
  • IAuthStrategy — strategia di persistenza/applicazione dei token
  • PostgRESTClient — facade con metodi che accettano/ritornano questi tipi