Skip to content

Authentication

Authentication in dichit-backend is JWT-based. The Fastify auth plugin (src/infrastructure/plugins/06-auth.ts) exposes authenticate and authorize decorators, and token signing lives in src/infrastructure/auth/services/jwt.service.ts.

Access & refresh model

Token Claims / role Purpose
access (JWT) user id, role authorizes REST + WebSocket requests
refresh (JWT) rotation obtains a new access token

Config (ACCESS_TOKEN_SECRET, ACCESS_TOKEN_EXPIRES_IN, REFRESH_TOKEN_SECRET, REFRESH_TOKEN_EXPIRES_IN) — see environment-variables.

Flow

sequenceDiagram
    participant C as Client
    participant A as API
    participant DB as PostgreSQL

    C->>A: POST /auth (OTP / OAuth / password)
    A->>DB: verify identity
    A-->>C: accessToken + refreshToken
    C->>A: API call with Authorization: Bearer <access>
    A->>A: authenticate() → verify JWT
    A-->>C: 200 response
    C->>A: POST /auth/refresh (refreshToken)
    A-->>C: new accessToken

Access-token placement

The auth plugin resolves the token from:

  • Authorization: Bearer <token> header, or
  • a query parameter (getBearerToken first tries the header, then the query).

A missing/malformed header is rejected for protected routes.

Protecting a route

// authenticate() then optionally authorize(roles)
app.get(
  '/v2/me',
  {
    preValidation: [
      app.authenticate,
      app.authorize(['SUBSCRIBER', 'COMPANY', 'SUPERADMIN'])
    ]
  },
  handler
);
  • authenticate → verifies the JWT, attaches the user to the request; throws UnauthorizedError.
  • authorize(roles) → checks role membership; throws UnauthorizedError / ForbiddenError (see authorization.md).

Refresh & cookies

  • @fastify/cookie (07-cookie.ts) stores the refresh token; rotation and invalidation are handled in the auth use cases.
  • Logout invalidates the session/refresh token (see src/interfaces/http/routes/v2/auth/logout).

Security rules

  1. Never log passwords, OTPs, tokens, or auth headers.
  2. Keep *_SECRET values out of git; rotate if leaked.
  3. Validate every protected route; never trust client identifiers alone for access control (see authorization.md).
  4. WebSocket handshake authenticates with the same access-token JWT (see api/websocket/authentication.md).