All files / src/routes profile.ts

54.83% Statements 68/124
87.5% Branches 7/8
100% Functions 2/2
54.83% Lines 68/124

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 1501x           1x 1x 1x 1x 1x 1x 1x 1x 1x     1x     1x 26x   26x 3x 3x   26x 3x 1x 1x 1x 1x 1x 1x 26x     26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x                     26x   26x 1x 1x 1x 1x 1x 1x 1x 1x 26x     26x                 26x     26x 1x                                                                                     26x     26x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 26x 26x  
import { AppError } from "@ontrack/backend-common";
import type { FastifyPluginAsync } from "fastify";
import type { AppConfig } from "../config.js";
import { requireUser, requireVerifiedUser, type IdTokenVerifier } from "../lib/firebase-auth.js";
import { proxyJsonRequest, proxyUpstreamGetRaw, throwIfUpstreamFailed } from "../lib/http-client.js";
 
const updateProfileBodySchema = {
  type: "object",
  additionalProperties: false,
  properties: {
    nickname: { type: ["string", "null"], maxLength: 60 },
    city: { type: ["string", "null"], maxLength: 120 },
    bio: { type: ["string", "null"], maxLength: 1000 },
  },
} as const;
 
/** Профиль текущего пользователя (город/био/аватар). uid берётся из ID-токена, не от клиента. */
export const profileRoutes: FastifyPluginAsync<{
  config: AppConfig;
  verifyIdToken: IdTokenVerifier;
}> = async (app, opts) => {
  const { config, verifyIdToken } = opts;
 
  function userHeaders(uid: string): Record<string, string> {
    return { "x-service-token": config.serviceToken, "x-user-uid": uid };
  }
 
  app.get("/profile", async (request) => {
    const user = await requireVerifiedUser(request, verifyIdToken);
    return proxyJsonRequest<unknown>({
      method: "GET",
      url: `${config.catalogServiceUrl}/profile`,
      headers: userHeaders(user.uid),
      timeoutMs: config.upstreamTimeoutMs,
    });
  });
 
  /** Свободен ли никнейм. */
  app.get(
    "/profile/nickname-available",
    {
      schema: {
        querystring: {
          type: "object",
          required: ["nickname"],
          additionalProperties: false,
          properties: { nickname: { type: "string" } },
        },
      },
    },
    async (request) => {
      const user = await requireVerifiedUser(request, verifyIdToken);
      const nickname = (request.query as { nickname: string }).nickname;
      const params = new URLSearchParams({ nickname });
      return proxyJsonRequest<unknown>({
        method: "GET",
        url: `${config.catalogServiceUrl}/profile/nickname-available?${params.toString()}`,
        headers: userHeaders(user.uid),
        timeoutMs: config.upstreamTimeoutMs,
      });
    },
  );
 
  app.put("/profile", { schema: { body: updateProfileBodySchema } }, async (request) => {
    const user = await requireVerifiedUser(request, verifyIdToken);
    return proxyJsonRequest<unknown>({
      method: "PUT",
      url: `${config.catalogServiceUrl}/profile`,
      headers: userHeaders(user.uid),
      body: request.body,
      timeoutMs: config.upstreamTimeoutMs,
    });
  });
 
  /** Синк сессии: метаданные входа Firebase → профиль (для админ-таблицы). */
  app.post("/profile/session", async (request) => {
    const user = await requireUser(request, verifyIdToken);
    return proxyJsonRequest<unknown>({
      method: "POST",
      url: `${config.catalogServiceUrl}/profile/session`,
      headers: userHeaders(user.uid),
      body: request.body ?? {},
      timeoutMs: config.upstreamTimeoutMs,
    });
  });
 
  /** Загрузка аватара (multipart, поле `file`) — проксируется в каталог с X-User-Uid. */
  app.post("/profile/avatar", async (request, reply) => {
    const user = await requireVerifiedUser(request, verifyIdToken);
 
    const outgoing = new FormData();
    const parts = request.parts();
    for await (const part of parts) {
      if (part.type === "file") {
        const buf = await part.toBuffer();
        const blob = new Blob([new Uint8Array(buf)], part.mimetype ? { type: part.mimetype } : {});
        outgoing.append(part.fieldname, blob, part.filename ?? "avatar");
      } else {
        outgoing.append(part.fieldname, String(part.value ?? ""));
      }
    }
 
    const controller = new AbortController();
    const timeout = setTimeout(() => controller.abort(), config.upstreamTimeoutMs);
    try {
      const response = await fetch(`${config.catalogServiceUrl}/profile/avatar`, {
        method: "POST",
        headers: userHeaders(user.uid),
        body: outgoing,
        signal: controller.signal,
      });
 
      const body = Buffer.from(await response.arrayBuffer());
      throwIfUpstreamFailed(response.status, body);
 
      const ct = response.headers.get("content-type");
      if (ct) {
        reply.header("Content-Type", ct);
      }
      return reply.code(response.status).send(body);
    } catch (error) {
      if (error instanceof AppError) {
        throw error;
      }
      if (error instanceof Error && error.name === "AbortError") {
        throw new AppError(504, "UPSTREAM_TIMEOUT", "Upstream request timed out");
      }
      throw new AppError(502, "UPSTREAM_UNAVAILABLE", "Upstream service unavailable");
    } finally {
      clearTimeout(timeout);
    }
  });
 
  /** Отдача аватара текущего пользователя (байты картинки из R2 через каталог). */
  app.get("/profile/avatar", async (request, reply) => {
    const user = await requireVerifiedUser(request, verifyIdToken);
    const result = await proxyUpstreamGetRaw({
      url: `${config.catalogServiceUrl}/profile/avatar`,
      headers: userHeaders(user.uid),
      timeoutMs: config.upstreamTimeoutMs,
    });
 
    if (result.contentType) {
      reply.header("Content-Type", result.contentType);
    }
    reply.header("Cache-Control", "private, max-age=300");
    return reply.code(result.status).send(result.body);
  });
};