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 (
getBearerTokenfirst 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; throwsUnauthorizedError.authorize(roles)→ checks role membership; throwsUnauthorizedError/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¶
- Never log passwords, OTPs, tokens, or auth headers.
- Keep
*_SECRETvalues out of git; rotate if leaked. - Validate every protected route; never trust client identifiers alone for access control (see authorization.md).
- WebSocket handshake authenticates with the same access-token JWT (see api/websocket/authentication.md).