Files
task-stream/libs/api/identity/presenters/src/lib/auth/auth.guard.ts
Josep Piguillem e656222b54 feat: public projects, project deletion and sagas
Public projects:
- Project.isPublic (create/update, owners and admins). Anyone can read a
  public project without a token: project, board, tickets, comments,
  history, releases, activity, tracking and statistics, over GraphQL and
  REST. Writes stay for members (401 anonymous, 403 outsiders).
- @OptionalAuth() / @ApiOptionalPireonAuth(): anonymous callers allowed,
  invalid tokens still rejected. ReadAccess lets anonymous viewers read
  public projects only; linked tickets are filtered by visibility.
- publicProjects (GraphQL) and GET /api/explore/projects (REST).
- Web: «Explorar» page, project pages open without a session (read-only
  notice, sign-in hints), public badge, visibility switch in settings,
  no realtime subscriptions without a session.

Project deletion:
- Owner only, confirming the key (deleteProject / DELETE
  /api/projects/{project}?confirm=KEY). The key is freed; the read model
  drops the project and members are notified (web goes home).

Sagas (run by the EventsBridge after projections, durable and ordered):
- ProjectDeletionSaga: project deleted → delete its tickets and releases;
  ticket deleted → purge its comments and drop links from other tickets.
- ReleaseArchivedSaga: unfinished tickets leave an archived release.
- UserDeactivatedSaga: the Pireon webhook records UserDeactivatedEvent in
  the event store (EventRecorder); the tracker unassigns that user's open
  tickets as the system actor.
- Internal idempotent commands; domain refusals are logged and skipped,
  concurrency conflicts retried. Affected streams come from the event store
  (TrackerStreamsRepository).

Tests: domain lifecycle specs, saga specs run like the bridge, facade
tests, e2e for public access, cascade deletion, archived releases and
deactivation webhook. Docs, READMEs, schema.gql/openapi.json and Word/PDF
updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 07:04:20 +02:00

70 lines
2.0 KiB
TypeScript

import {
CanActivate,
ExecutionContext,
ForbiddenException,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import {
IdentityService,
InvalidAccessTokenError,
} from '@task-stream/api/identity/application';
import { extractBearerToken, getAuthRequest } from './auth-request';
import {
IS_OPTIONAL_AUTH,
IS_PUBLIC,
REQUIRED_APP_ROLES,
} from './auth.decorators';
/**
* Global guard: every HTTP/GraphQL operation needs a valid Pireon token unless
* @Public(); with @OptionalAuth() the token may be missing (but not invalid).
*/
@Injectable()
export class AuthGuard implements CanActivate {
constructor(
private readonly reflector: Reflector,
private readonly identity: IdentityService,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const targets = [context.getHandler(), context.getClass()];
if (this.reflector.getAllAndOverride<boolean>(IS_PUBLIC, targets))
return true;
const req = getAuthRequest(context);
// WebSocket subscriptions are authenticated once in connection_init.
if (!req.user) {
const token = extractBearerToken(req.headers['authorization']);
if (!token) {
if (
this.reflector.getAllAndOverride<boolean>(IS_OPTIONAL_AUTH, targets)
)
return true;
throw new UnauthorizedException('Missing bearer token');
}
try {
req.user = await this.identity.resolveSession(token);
req.accessToken = token;
} catch (error) {
if (error instanceof InvalidAccessTokenError)
throw new UnauthorizedException(error.message);
throw error;
}
}
const roles = this.reflector.getAllAndOverride<string[]>(
REQUIRED_APP_ROLES,
targets,
);
const user = req.user;
if (roles?.length && user && !roles.some((role) => user.hasAppRole(role))) {
throw new ForbiddenException(
`Requires one of the app roles: ${roles.join(', ')}`,
);
}
return true;
}
}