All files / src/routes admin.ts

50% Statements 127/254
100% Branches 1/1
25% Functions 1/4
50% Lines 127/254

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 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 3081x                               1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x     1x 39x 39x     39x               39x       39x                   39x 39x 39x 39x                                                                                                                                             39x     39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x                                             39x     39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x                 39x       39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x                                 39x     39x 39x 39x 39x                       39x 39x  
import { AppError } from "@ontrack/backend-common";
import type { FastifyPluginAsync, FastifyRequest } from "fastify";
import type { AppConfig } from "../config.js";
import { assertAdmin } from "../lib/admin-role.js";
import {
  catalogStatsProperties,
  catalogStatsRequired,
  computeCatalogStats,
} from "../lib/catalog-stats.js";
import { deleteAuthUser, listAuthUsers, setEmailVerified } from "../lib/firebase-admin.js";
import { assertServiceToken } from "../lib/service-token.js";
import { readUserUid } from "../lib/user-uid.js";
import { prisma } from "../lib/prisma.js";
import type { ObjectStore } from "../storage/object-store.js";
import { purgeUserData } from "./account.js";
 
const ADMIN_ROLES = ["user", "admin"] as const;
 
const adminUserSchema = {
  type: "object",
  required: [
    "uid",
    "role",
    "isSuperAdmin",
    "emailVerified",
    "tracksCount",
    "likesGiven",
    "favoritesGiven",
  ],
  additionalProperties: false,
  properties: {
    uid: { type: "string" },
    nickname: { type: "string", nullable: true },
    email: { type: "string", nullable: true },
    role: { type: "string" },
    isSuperAdmin: { type: "boolean" },
    emailVerified: { type: "boolean" },
    authProvider: { type: "string", nullable: true },
    registeredAt: { type: "string", nullable: true },
    lastSignInAt: { type: "string", nullable: true },
    tracksCount: { type: "integer" },
    likesGiven: { type: "integer" },
    favoritesGiven: { type: "integer" },
  },
} as const;
 
const usersResponseSchema = {
  type: "object",
  required: ["users"],
  additionalProperties: false,
  properties: { users: { type: "array", items: adminUserSchema } },
} as const;
 
const roleParamSchema = {
  type: "object",
  required: ["uid"],
  additionalProperties: false,
  properties: { uid: { type: "string", minLength: 1 } },
} as const;
 
const roleBodySchema = {
  type: "object",
  required: ["role"],
  additionalProperties: false,
  properties: { role: { type: "string", enum: ADMIN_ROLES } },
} as const;
 
const statsResponseSchema = {
  type: "object",
  required: ["usersCount", "newUsers7d", ...catalogStatsRequired],
  additionalProperties: false,
  properties: {
    usersCount: { type: "integer" },
    newUsers7d: { type: "integer" },
    ...catalogStatsProperties,
  },
} as const;
 
export const adminRoutes: FastifyPluginAsync<{
  config: AppConfig;
  objectStore: ObjectStore | null;
}> = async (app, opts) => {
  const { config, objectStore } = opts;
  const superEmails = new Set(config.superAdminEmails);
 
  /** X-Service-Token + текущий пользователь должен иметь role=admin. Возвращает его uid. */
  async function authorizeAdmin(request: FastifyRequest): Promise<string> {
    const token = request.headers["x-service-token"];
    assertServiceToken(Array.isArray(token) ? token[0] : token, config.serviceToken);
    const uid = readUserUid(request);
    await assertAdmin(uid);
    return uid;
  }
 
  const isSuperEmail = (email: string | null | undefined): boolean =>
    !!email && superEmails.has(email.toLowerCase());
 
  /** Защищённый супер-админ (по email профиля) — его нельзя удалить/разжаловать. */
  async function isSuperAdminUid(uid: string): Promise<boolean> {
    if (superEmails.size === 0) return false;
    const p = await prisma.userProfile.findUnique({
      where: { firebaseUid: uid },
      select: { email: true },
    });
    return isSuperEmail(p?.email);
  }
 
  /** Список пользователей + агрегаты (треки/лайки/избранное). */
  app.get(
    "/admin/users",
    { schema: { response: { 200: usersResponseSchema } } },
    async (request, reply) => {
      await authorizeAdmin(request);
 
      const [authUsers, profiles, tracksByOwner, likesByUser, favsByUser] = await Promise.all([
        listAuthUsers(config.firebaseServiceAccountPath),
        prisma.userProfile.findMany({
          orderBy: [{ lastSignInAt: { sort: "desc", nulls: "last" } }, { createdAt: "desc" }],
          select: {
            firebaseUid: true,
            nickname: true,
            email: true,
            role: true,
            authProvider: true,
            registeredAt: true,
            lastSignInAt: true,
          },
        }),
        prisma.gpxTrack.groupBy({
          by: ["ownerUid"],
          where: { deletedAt: null, ownerUid: { not: null } },
          _count: { _all: true },
        }),
        prisma.trackLike.groupBy({ by: ["firebaseUid"], _count: { _all: true } }),
        prisma.trackFavorite.groupBy({ by: ["firebaseUid"], _count: { _all: true } }),
      ]);
 
      const tracksMap = new Map(tracksByOwner.map((r) => [r.ownerUid, r._count._all]));
      const likesMap = new Map(likesByUser.map((r) => [r.firebaseUid, r._count._all]));
      const favsMap = new Map(favsByUser.map((r) => [r.firebaseUid, r._count._all]));
      const profileMap = new Map(profiles.map((p) => [p.firebaseUid, p]));
 
      const stats = (uid: string) => ({
        tracksCount: tracksMap.get(uid) ?? 0,
        likesGiven: likesMap.get(uid) ?? 0,
        favoritesGiven: favsMap.get(uid) ?? 0,
      });
 
      // Полный список — из Firebase (если Admin SDK настроен), иначе из БД.
      const users = authUsers
        ? authUsers
            .map((au) => {
              const p = profileMap.get(au.uid);
              return {
                uid: au.uid,
                nickname: p?.nickname ?? null,
                email: au.email ?? p?.email ?? null,
                role: p?.role ?? "user",
                isSuperAdmin: isSuperEmail(au.email ?? p?.email),
                emailVerified: au.emailVerified,
                authProvider: au.authProvider,
                registeredAt: au.registeredAt,
                lastSignInAt: au.lastSignInAt,
                ...stats(au.uid),
              };
            })
            .sort((a, b) => (b.lastSignInAt ?? "").localeCompare(a.lastSignInAt ?? ""))
        : profiles.map((r) => ({
            uid: r.firebaseUid,
            nickname: r.nickname,
            email: r.email,
            role: r.role,
            isSuperAdmin: isSuperEmail(r.email),
            emailVerified: false,
            authProvider: r.authProvider,
            registeredAt: r.registeredAt ? r.registeredAt.toISOString() : null,
            lastSignInAt: r.lastSignInAt ? r.lastSignInAt.toISOString() : null,
            ...stats(r.firebaseUid),
          }));
 
      return reply.send({ users });
    },
  );
 
  /** Сменить роль пользователя (нельзя менять свою — защита от самоблокировки). */
  app.put(
    "/admin/users/:uid/role",
    {
      schema: {
        params: roleParamSchema,
        body: roleBodySchema,
        response: {
          200: {
            type: "object",
            required: ["uid", "role"],
            additionalProperties: false,
            properties: { uid: { type: "string" }, role: { type: "string" } },
          },
        },
      },
    },
    async (request, reply) => {
      const callerUid = await authorizeAdmin(request);
      const { uid } = request.params as { uid: string };
      const { role } = request.body as { role: (typeof ADMIN_ROLES)[number] };
 
      if (uid === callerUid) {
        throw new AppError(400, "CANNOT_CHANGE_OWN_ROLE", "Нельзя менять свою роль");
      }
      if (await isSuperAdminUid(uid)) {
        throw new AppError(403, "PROTECTED_SUPER_ADMIN", "Нельзя менять роль супер-админа");
      }
 
      const target = await prisma.userProfile.findUnique({
        where: { firebaseUid: uid },
        select: { firebaseUid: true },
      });
      if (!target) {
        throw new AppError(404, "USER_NOT_FOUND", "Пользователь не найден");
      }
 
      await prisma.userProfile.update({ where: { firebaseUid: uid }, data: { role } });
      return reply.send({ uid, role });
    },
  );
 
  /** Подтвердить email пользователя вручную (админом) — emailVerified=true в Firebase Auth. */
  app.post(
    "/admin/users/:uid/verify-email",
    {
      schema: {
        params: roleParamSchema,
        response: {
          200: {
            type: "object",
            required: ["ok"],
            additionalProperties: false,
            properties: { ok: { type: "boolean" } },
          },
        },
      },
    },
    async (request, reply) => {
      await authorizeAdmin(request);
      const { uid } = request.params as { uid: string };
      const ok = await setEmailVerified(config.firebaseServiceAccountPath, uid);
      if (!ok) {
        throw new AppError(503, "AUTH_UNAVAILABLE", "Firebase Admin SDK не настроен");
      }
      return reply.send({ ok: true });
    },
  );
 
  /** Удалить пользователя: его данные (профиль/велики/лайки/избранное/аватар) + аккаунт Firebase.
      Загруженные им треки остаются в каталоге (owner → NULL). Свой аккаунт удалить нельзя. */
  app.delete(
    "/admin/users/:uid",
    {
      schema: {
        params: roleParamSchema,
        response: {
          200: {
            type: "object",
            required: ["ok"],
            additionalProperties: false,
            properties: { ok: { type: "boolean" } },
          },
        },
      },
    },
    async (request, reply) => {
      const callerUid = await authorizeAdmin(request);
      const { uid } = request.params as { uid: string };
 
      if (uid === callerUid) {
        throw new AppError(400, "CANNOT_DELETE_SELF", "Нельзя удалить свой аккаунт");
      }
      if (await isSuperAdminUid(uid)) {
        throw new AppError(403, "PROTECTED_SUPER_ADMIN", "Нельзя удалить супер-админа");
      }
 
      await purgeUserData(uid, objectStore);
      await prisma.gpxTrack.updateMany({ where: { ownerUid: uid }, data: { ownerUid: null } });
      await deleteAuthUser(config.firebaseServiceAccountPath, uid);
 
      return reply.send({ ok: true });
    },
  );
 
  /** Сводная статистика для дашборда. */
  app.get(
    "/admin/stats",
    { schema: { response: { 200: statsResponseSchema } } },
    async (request, reply) => {
      await authorizeAdmin(request);
      const weekAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
 
      const [base, usersCount, newUsers7d] = await Promise.all([
        computeCatalogStats(),
        prisma.userProfile.count(),
        prisma.userProfile.count({ where: { registeredAt: { gte: weekAgo } } }),
      ]);
 
      return reply.send({ usersCount, newUsers7d, ...base });
    },
  );
};