done
This commit is contained in:
72
apps/backend/Dockerfile
Normal file
72
apps/backend/Dockerfile
Normal file
@@ -0,0 +1,72 @@
|
||||
# Multi-stage production Dockerfile for Backend (NestJS + Prisma + FFmpeg)
|
||||
# Supports Linux VPS, AWS EC2, GCP Compute, DigitalOcean, and Windows Docker Desktop
|
||||
|
||||
FROM node:22-bookworm-slim AS builder
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Install build essentials for native addons (e.g. argon2)
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
python3 \
|
||||
make \
|
||||
g++ \
|
||||
openssl \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Copy root package files
|
||||
COPY package*.json ./
|
||||
COPY packages/shared/package*.json ./packages/shared/
|
||||
COPY apps/backend/package*.json ./apps/backend/
|
||||
|
||||
# Install dependencies across workspaces
|
||||
RUN npm ci
|
||||
|
||||
# Copy shared package source and backend source
|
||||
COPY packages/shared ./packages/shared
|
||||
COPY apps/backend ./apps/backend
|
||||
|
||||
# Generate Prisma client and compile backend TypeScript
|
||||
WORKDIR /app/apps/backend
|
||||
RUN npx prisma generate
|
||||
RUN npm run build
|
||||
|
||||
# ==============================================================
|
||||
# Production Runtime Stage
|
||||
# ==============================================================
|
||||
FROM node:22-bookworm-slim AS runner
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Install runtime dependencies: FFmpeg and OpenSSL (for Prisma)
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
ffmpeg \
|
||||
openssl \
|
||||
curl \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
ENV NODE_ENV=production
|
||||
ENV PORT=4000
|
||||
ENV LOCAL_STORAGE_PATH=/app/storage
|
||||
|
||||
# Create storage directory with proper permissions
|
||||
RUN mkdir -p /app/storage && chmod 755 /app/storage
|
||||
|
||||
# Copy installed node_modules and built assets from builder
|
||||
COPY --from=builder /app/node_modules ./node_modules
|
||||
COPY --from=builder /app/packages/shared ./packages/shared
|
||||
COPY --from=builder /app/apps/backend/node_modules ./apps/backend/node_modules
|
||||
COPY --from=builder /app/apps/backend/dist ./apps/backend/dist
|
||||
COPY --from=builder /app/apps/backend/prisma ./apps/backend/prisma
|
||||
COPY --from=builder /app/apps/backend/package.json ./apps/backend/package.json
|
||||
|
||||
WORKDIR /app/apps/backend
|
||||
|
||||
# Expose backend REST API port
|
||||
EXPOSE 4000
|
||||
|
||||
# Health check
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
|
||||
CMD curl -f http://localhost:4000/api/docs || exit 1
|
||||
|
||||
# Start production server
|
||||
CMD ["node", "dist/main.js"]
|
||||
5
apps/backend/nest-cli.json
Normal file
5
apps/backend/nest-cli.json
Normal file
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/nest-cli",
|
||||
"collection": "@nestjs/schematics",
|
||||
"sourceRoot": "src"
|
||||
}
|
||||
77
apps/backend/package.json
Normal file
77
apps/backend/package.json
Normal file
@@ -0,0 +1,77 @@
|
||||
{
|
||||
"name": "@fileshare/backend",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"prebuild": "node ../../scripts/prisma-generate.js",
|
||||
"build": "nest build",
|
||||
"format": "prettier --write \"src/**/*.ts\"",
|
||||
"start": "nest start",
|
||||
"start:dev": "nest start --watch",
|
||||
"start:debug": "nest start --debug --watch",
|
||||
"start:prod": "node dist/main.js",
|
||||
"prisma:generate": "node ../../scripts/prisma-generate.js",
|
||||
"prisma:migrate": "prisma migrate dev",
|
||||
"prisma:migrate:deploy": "prisma migrate deploy",
|
||||
"prisma:seed": "ts-node prisma/seed.ts",
|
||||
"test": "jest --passWithNoTests",
|
||||
"test:watch": "jest --watch",
|
||||
"test:cov": "jest --coverage",
|
||||
"test:e2e": "jest --config ./test/jest-e2e.json"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fileshare/shared": "*",
|
||||
"@aws-sdk/client-s3": "^3.750.0",
|
||||
"@nestjs/common": "^11.0.11",
|
||||
"@nestjs/config": "^4.0.1",
|
||||
"@nestjs/core": "^11.0.11",
|
||||
"@nestjs/jwt": "^11.0.0",
|
||||
"@nestjs/passport": "^11.0.5",
|
||||
"@nestjs/platform-express": "^11.0.11",
|
||||
"@nestjs/swagger": "^11.0.6",
|
||||
"@prisma/client": "^6.4.1",
|
||||
"argon2": "^0.41.1",
|
||||
"bullmq": "^5.41.7",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.14.1",
|
||||
"compression": "^1.8.0",
|
||||
"cookie-parser": "^1.4.7",
|
||||
"dotenv": "^16.4.7",
|
||||
"fluent-ffmpeg": "^2.1.3",
|
||||
"helmet": "^8.0.0",
|
||||
"ioredis": "^5.5.0",
|
||||
"mime-types": "^2.1.35",
|
||||
"multer": "^1.4.5-lts.1",
|
||||
"passport": "^0.7.0",
|
||||
"passport-jwt": "^4.0.1",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"rxjs": "^7.8.2",
|
||||
"swagger-ui-express": "^5.0.1",
|
||||
"uuid": "^11.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@nestjs/cli": "^11.0.5",
|
||||
"@nestjs/schematics": "^11.0.2",
|
||||
"@nestjs/testing": "^11.0.11",
|
||||
"@types/compression": "^1.7.5",
|
||||
"@types/cookie-parser": "^1.4.8",
|
||||
"@types/express": "^5.0.0",
|
||||
"@types/fluent-ffmpeg": "^2.1.27",
|
||||
"@types/jest": "^29.5.14",
|
||||
"@types/mime-types": "^2.1.4",
|
||||
"@types/multer": "^1.4.12",
|
||||
"@types/node": "^22.13.9",
|
||||
"@types/passport-jwt": "^4.0.1",
|
||||
"@types/supertest": "^6.0.2",
|
||||
"@types/uuid": "^10.0.0",
|
||||
"jest": "^29.7.0",
|
||||
"prisma": "^6.4.1",
|
||||
"source-map-support": "^0.5.21",
|
||||
"supertest": "^7.0.0",
|
||||
"ts-jest": "^29.2.6",
|
||||
"ts-loader": "^9.5.2",
|
||||
"ts-node": "^10.9.2",
|
||||
"tsconfig-paths": "^4.2.0",
|
||||
"typescript": "^5.7.3"
|
||||
}
|
||||
}
|
||||
20
apps/backend/prisma/add-allowed-companies.js
Normal file
20
apps/backend/prisma/add-allowed-companies.js
Normal file
@@ -0,0 +1,20 @@
|
||||
require('dotenv').config({ path: __dirname + '/../.env' });
|
||||
const { PrismaClient } = require('@prisma/client');
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
async function main() {
|
||||
try {
|
||||
await prisma.$executeRawUnsafe('ALTER TABLE `User` ADD COLUMN `allowedCompanies` TEXT NULL AFTER `companyName`;');
|
||||
console.log('✓ Successfully added allowedCompanies column to User table');
|
||||
} catch (err) {
|
||||
if (err.message && err.message.includes('Duplicate column name')) {
|
||||
console.log('✓ Column allowedCompanies already exists');
|
||||
} else {
|
||||
console.error('Error adding column:', err.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
main()
|
||||
.catch(console.error)
|
||||
.finally(() => prisma.$disconnect());
|
||||
30
apps/backend/prisma/add-column.js
Normal file
30
apps/backend/prisma/add-column.js
Normal file
@@ -0,0 +1,30 @@
|
||||
const { PrismaClient } = require('@prisma/client');
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
async function main() {
|
||||
try {
|
||||
await prisma.$executeRawUnsafe('ALTER TABLE `User` ADD COLUMN `viewablePassword` VARCHAR(191) NULL AFTER `passwordHash`;');
|
||||
console.log('✓ Successfully added viewablePassword column to User table');
|
||||
} catch (err) {
|
||||
if (err.message.includes('Duplicate column name')) {
|
||||
console.log('✓ Column viewablePassword already exists');
|
||||
} else {
|
||||
console.error('Error adding column:', err.message);
|
||||
}
|
||||
}
|
||||
|
||||
// Update existing seeded users with their plain passwords
|
||||
await prisma.$executeRawUnsafe("UPDATE `User` SET `viewablePassword` = 'Ecohub@520' WHERE `username` = 'ecohub';");
|
||||
await prisma.$executeRawUnsafe("UPDATE `User` SET `viewablePassword` = '123' WHERE `username` = 'ecohubstaff';");
|
||||
await prisma.$executeRawUnsafe("UPDATE `User` SET `viewablePassword` = '123' WHERE `username` = 'ecouser';");
|
||||
await prisma.$executeRawUnsafe("UPDATE `User` SET `viewablePassword` = 'SuperAdmin@Secure2026!' WHERE `username` = 'superadmin';");
|
||||
await prisma.$executeRawUnsafe("UPDATE `User` SET `viewablePassword` = 'Admin@Secure2026!' WHERE `username` = 'admin';");
|
||||
await prisma.$executeRawUnsafe("UPDATE `User` SET `viewablePassword` = 'UserA@Secure2026!' WHERE `username` = 'usera';");
|
||||
await prisma.$executeRawUnsafe("UPDATE `User` SET `viewablePassword` = 'UserB@Secure2026!' WHERE `username` = 'userb';");
|
||||
|
||||
console.log('✓ Updated existing user viewable passwords');
|
||||
}
|
||||
|
||||
main()
|
||||
.catch(console.error)
|
||||
.finally(() => prisma.$disconnect());
|
||||
14
apps/backend/prisma/check-cols.js
Normal file
14
apps/backend/prisma/check-cols.js
Normal file
@@ -0,0 +1,14 @@
|
||||
require('dotenv').config({ path: __dirname + '/../.env' });
|
||||
const { PrismaClient } = require('@prisma/client');
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
async function main() {
|
||||
try {
|
||||
const cols = await prisma.$queryRawUnsafe('SHOW COLUMNS FROM `User`');
|
||||
console.log('Columns in User table:', cols.map(c => c.Field));
|
||||
} catch (e) {
|
||||
console.error('Error:', e);
|
||||
}
|
||||
}
|
||||
|
||||
main().finally(() => prisma.$disconnect());
|
||||
26
apps/backend/prisma/clean-orphans.js
Normal file
26
apps/backend/prisma/clean-orphans.js
Normal file
@@ -0,0 +1,26 @@
|
||||
const { PrismaClient } = require('@prisma/client');
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
async function run() {
|
||||
const users = await prisma.user.findMany({ select: { id: true } });
|
||||
const userIds = new Set(users.map((u) => u.id));
|
||||
console.log('Total valid users in DB:', userIds.size);
|
||||
|
||||
const permissions = await prisma.filePermission.findMany();
|
||||
console.log('Total permissions in DB:', permissions.length);
|
||||
|
||||
let orphaned = 0;
|
||||
for (const p of permissions) {
|
||||
if (!userIds.has(p.ownerId) || !userIds.has(p.granteeUserId)) {
|
||||
orphaned++;
|
||||
await prisma.filePermission.delete({ where: { id: p.id } });
|
||||
}
|
||||
}
|
||||
console.log('Cleaned up orphaned permissions:', orphaned);
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
|
||||
run().catch((e) => {
|
||||
console.error(e);
|
||||
process.exit(1);
|
||||
});
|
||||
41
apps/backend/prisma/create-user-table.js
Normal file
41
apps/backend/prisma/create-user-table.js
Normal file
@@ -0,0 +1,41 @@
|
||||
require('dotenv').config({ path: __dirname + '/../.env' });
|
||||
const { PrismaClient } = require('@prisma/client');
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
async function main() {
|
||||
const ddl = `
|
||||
CREATE TABLE IF NOT EXISTS \`User\` (
|
||||
\`id\` VARCHAR(191) NOT NULL,
|
||||
\`email\` VARCHAR(191) NOT NULL,
|
||||
\`username\` VARCHAR(191) NOT NULL,
|
||||
\`fullName\` VARCHAR(191) NOT NULL,
|
||||
\`companyName\` VARCHAR(191) NOT NULL DEFAULT 'Ecohub',
|
||||
\`allowedCompanies\` TEXT NULL,
|
||||
\`passwordHash\` VARCHAR(191) NOT NULL,
|
||||
\`viewablePassword\` VARCHAR(191) NULL,
|
||||
\`role\` ENUM('SUPER_ADMIN', 'ADMIN', 'USER') NOT NULL DEFAULT 'USER',
|
||||
\`status\` ENUM('ACTIVE', 'SUSPENDED', 'PENDING') NOT NULL DEFAULT 'ACTIVE',
|
||||
\`storageQuotaBytes\` BIGINT NOT NULL DEFAULT 5368709120,
|
||||
\`storageUsedBytes\` BIGINT NOT NULL DEFAULT 0,
|
||||
\`canCreateShareLinks\` BOOLEAN NOT NULL DEFAULT false,
|
||||
\`canDeleteFiles\` BOOLEAN NOT NULL DEFAULT true,
|
||||
\`canViewOtherUsers\` BOOLEAN NOT NULL DEFAULT false,
|
||||
\`remoteFileServerUrl\` VARCHAR(191) NULL,
|
||||
\`canUseRemoteServer\` BOOLEAN NOT NULL DEFAULT true,
|
||||
\`createdAt\` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
\`updatedAt\` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
|
||||
\`lastLoginAt\` DATETIME(3) NULL,
|
||||
|
||||
UNIQUE INDEX \`User_email_key\`(\`email\`),
|
||||
UNIQUE INDEX \`User_username_key\`(\`username\`),
|
||||
INDEX \`User_role_idx\`(\`role\`),
|
||||
INDEX \`User_status_idx\`(\`status\`),
|
||||
PRIMARY KEY (\`id\`)
|
||||
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
`;
|
||||
|
||||
await prisma.$executeRawUnsafe(ddl);
|
||||
console.log('✓ User table created successfully with allowedCompanies!');
|
||||
}
|
||||
|
||||
main().catch(console.error).finally(() => prisma.$disconnect());
|
||||
224
apps/backend/prisma/migrations/20261014062134_init/migration.sql
Normal file
224
apps/backend/prisma/migrations/20261014062134_init/migration.sql
Normal file
@@ -0,0 +1,224 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE `User` (
|
||||
`id` VARCHAR(191) NOT NULL,
|
||||
`email` VARCHAR(191) NOT NULL,
|
||||
`username` VARCHAR(191) NOT NULL,
|
||||
`fullName` VARCHAR(191) NOT NULL,
|
||||
`passwordHash` VARCHAR(191) NOT NULL,
|
||||
`role` ENUM('SUPER_ADMIN', 'ADMIN', 'USER') NOT NULL DEFAULT 'USER',
|
||||
`status` ENUM('ACTIVE', 'SUSPENDED', 'PENDING') NOT NULL DEFAULT 'ACTIVE',
|
||||
`storageQuotaBytes` BIGINT NOT NULL DEFAULT 5368709120,
|
||||
`storageUsedBytes` BIGINT NOT NULL DEFAULT 0,
|
||||
`createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
`updatedAt` DATETIME(3) NOT NULL,
|
||||
`lastLoginAt` DATETIME(3) NULL,
|
||||
|
||||
UNIQUE INDEX `User_email_key`(`email`),
|
||||
UNIQUE INDEX `User_username_key`(`username`),
|
||||
INDEX `User_role_idx`(`role`),
|
||||
INDEX `User_status_idx`(`status`),
|
||||
PRIMARY KEY (`id`)
|
||||
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE `Folder` (
|
||||
`id` VARCHAR(191) NOT NULL,
|
||||
`ownerId` VARCHAR(191) NOT NULL,
|
||||
`parentId` VARCHAR(191) NULL,
|
||||
`name` VARCHAR(191) NOT NULL,
|
||||
`logicalPath` VARCHAR(191) NOT NULL,
|
||||
`createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
`updatedAt` DATETIME(3) NOT NULL,
|
||||
|
||||
INDEX `Folder_ownerId_idx`(`ownerId`),
|
||||
INDEX `Folder_parentId_idx`(`parentId`),
|
||||
UNIQUE INDEX `Folder_ownerId_parentId_name_key`(`ownerId`, `parentId`, `name`),
|
||||
PRIMARY KEY (`id`)
|
||||
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE `FileAsset` (
|
||||
`id` VARCHAR(191) NOT NULL,
|
||||
`ownerId` VARCHAR(191) NOT NULL,
|
||||
`folderId` VARCHAR(191) NULL,
|
||||
`originalFilename` VARCHAR(191) NOT NULL,
|
||||
`internalStorageKey` VARCHAR(191) NOT NULL,
|
||||
`mimeType` VARCHAR(191) NOT NULL,
|
||||
`fileExtension` VARCHAR(191) NOT NULL,
|
||||
`fileSizeBytes` BIGINT NOT NULL,
|
||||
`fileCategory` ENUM('VIDEO', 'IMAGE', 'DOCUMENT', 'ARCHIVE', 'AUDIO', 'OTHER') NOT NULL,
|
||||
`checksum` VARCHAR(191) NULL,
|
||||
`status` ENUM('PENDING', 'UPLOADING', 'PROCESSING', 'READY', 'FAILED') NOT NULL DEFAULT 'PENDING',
|
||||
`durationSeconds` DOUBLE NULL,
|
||||
`width` INTEGER NULL,
|
||||
`height` INTEGER NULL,
|
||||
`videoCodec` VARCHAR(191) NULL,
|
||||
`audioCodec` VARCHAR(191) NULL,
|
||||
`thumbnailStorageKey` VARCHAR(191) NULL,
|
||||
`hlsMasterPlaylistKey` VARCHAR(191) NULL,
|
||||
`isSoftDeleted` BOOLEAN NOT NULL DEFAULT false,
|
||||
`deletedAt` DATETIME(3) NULL,
|
||||
`createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
`updatedAt` DATETIME(3) NOT NULL,
|
||||
|
||||
UNIQUE INDEX `FileAsset_internalStorageKey_key`(`internalStorageKey`),
|
||||
INDEX `FileAsset_ownerId_idx`(`ownerId`),
|
||||
INDEX `FileAsset_folderId_idx`(`folderId`),
|
||||
INDEX `FileAsset_fileCategory_idx`(`fileCategory`),
|
||||
INDEX `FileAsset_status_idx`(`status`),
|
||||
INDEX `FileAsset_isSoftDeleted_idx`(`isSoftDeleted`),
|
||||
PRIMARY KEY (`id`)
|
||||
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE `FilePermission` (
|
||||
`id` VARCHAR(191) NOT NULL,
|
||||
`resourceType` ENUM('FILE', 'FOLDER', 'USER_FILES') NOT NULL,
|
||||
`resourceId` VARCHAR(191) NULL,
|
||||
`ownerId` VARCHAR(191) NOT NULL,
|
||||
`granteeUserId` VARCHAR(191) NOT NULL,
|
||||
`grantedByUserId` VARCHAR(191) NOT NULL,
|
||||
`canViewMetadata` BOOLEAN NOT NULL DEFAULT true,
|
||||
`canPreview` BOOLEAN NOT NULL DEFAULT false,
|
||||
`canPlay` BOOLEAN NOT NULL DEFAULT false,
|
||||
`canDownload` BOOLEAN NOT NULL DEFAULT false,
|
||||
`canListFolder` BOOLEAN NOT NULL DEFAULT false,
|
||||
`expiresAt` DATETIME(3) NULL,
|
||||
`revokedAt` DATETIME(3) NULL,
|
||||
`createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
`updatedAt` DATETIME(3) NOT NULL,
|
||||
|
||||
INDEX `FilePermission_granteeUserId_idx`(`granteeUserId`),
|
||||
INDEX `FilePermission_ownerId_idx`(`ownerId`),
|
||||
INDEX `FilePermission_resourceType_resourceId_idx`(`resourceType`, `resourceId`),
|
||||
INDEX `FilePermission_revokedAt_expiresAt_idx`(`revokedAt`, `expiresAt`),
|
||||
PRIMARY KEY (`id`)
|
||||
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE `UploadSession` (
|
||||
`id` VARCHAR(191) NOT NULL,
|
||||
`ownerId` VARCHAR(191) NOT NULL,
|
||||
`folderId` VARCHAR(191) NULL,
|
||||
`originalFilename` VARCHAR(191) NOT NULL,
|
||||
`mimeType` VARCHAR(191) NOT NULL,
|
||||
`fileCategory` ENUM('VIDEO', 'IMAGE', 'DOCUMENT', 'ARCHIVE', 'AUDIO', 'OTHER') NOT NULL,
|
||||
`totalSizeBytes` BIGINT NOT NULL,
|
||||
`uploadedSizeBytes` BIGINT NOT NULL DEFAULT 0,
|
||||
`tempStorageKey` VARCHAR(191) NOT NULL,
|
||||
`status` ENUM('INITIALIZED', 'UPLOADING', 'COMPLETED', 'ABORTED', 'EXPIRED') NOT NULL DEFAULT 'INITIALIZED',
|
||||
`expiresAt` DATETIME(3) NOT NULL,
|
||||
`createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
`updatedAt` DATETIME(3) NOT NULL,
|
||||
|
||||
UNIQUE INDEX `UploadSession_tempStorageKey_key`(`tempStorageKey`),
|
||||
INDEX `UploadSession_ownerId_idx`(`ownerId`),
|
||||
INDEX `UploadSession_status_idx`(`status`),
|
||||
INDEX `UploadSession_expiresAt_idx`(`expiresAt`),
|
||||
PRIMARY KEY (`id`)
|
||||
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE `VideoProcessingJob` (
|
||||
`id` VARCHAR(191) NOT NULL,
|
||||
`fileAssetId` VARCHAR(191) NOT NULL,
|
||||
`status` ENUM('QUEUED', 'PROCESSING', 'COMPLETED', 'FAILED') NOT NULL DEFAULT 'QUEUED',
|
||||
`progress` INTEGER NOT NULL DEFAULT 0,
|
||||
`attempts` INTEGER NOT NULL DEFAULT 0,
|
||||
`errorReason` TEXT NULL,
|
||||
`createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
`updatedAt` DATETIME(3) NOT NULL,
|
||||
`completedAt` DATETIME(3) NULL,
|
||||
|
||||
INDEX `VideoProcessingJob_fileAssetId_idx`(`fileAssetId`),
|
||||
INDEX `VideoProcessingJob_status_idx`(`status`),
|
||||
PRIMARY KEY (`id`)
|
||||
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE `RefreshToken` (
|
||||
`id` VARCHAR(191) NOT NULL,
|
||||
`tokenHash` VARCHAR(191) NOT NULL,
|
||||
`userId` VARCHAR(191) NOT NULL,
|
||||
`userAgent` VARCHAR(191) NULL,
|
||||
`ipAddress` VARCHAR(191) NULL,
|
||||
`expiresAt` DATETIME(3) NOT NULL,
|
||||
`revokedAt` DATETIME(3) NULL,
|
||||
`createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
|
||||
UNIQUE INDEX `RefreshToken_tokenHash_key`(`tokenHash`),
|
||||
INDEX `RefreshToken_userId_idx`(`userId`),
|
||||
INDEX `RefreshToken_expiresAt_idx`(`expiresAt`),
|
||||
PRIMARY KEY (`id`)
|
||||
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE `AuditLog` (
|
||||
`id` VARCHAR(191) NOT NULL,
|
||||
`actorUserId` VARCHAR(191) NULL,
|
||||
`action` VARCHAR(191) NOT NULL,
|
||||
`resourceType` VARCHAR(191) NOT NULL,
|
||||
`resourceId` VARCHAR(191) NULL,
|
||||
`targetUserId` VARCHAR(191) NULL,
|
||||
`ipAddress` VARCHAR(191) NULL,
|
||||
`userAgent` VARCHAR(191) NULL,
|
||||
`detailsJson` TEXT NULL,
|
||||
`createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
|
||||
INDEX `AuditLog_actorUserId_idx`(`actorUserId`),
|
||||
INDEX `AuditLog_action_idx`(`action`),
|
||||
INDEX `AuditLog_resourceType_resourceId_idx`(`resourceType`, `resourceId`),
|
||||
INDEX `AuditLog_createdAt_idx`(`createdAt`),
|
||||
PRIMARY KEY (`id`)
|
||||
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE `SystemSetting` (
|
||||
`id` VARCHAR(191) NOT NULL,
|
||||
`key` VARCHAR(191) NOT NULL,
|
||||
`value` TEXT NOT NULL,
|
||||
`description` VARCHAR(191) NULL,
|
||||
`updatedAt` DATETIME(3) NOT NULL,
|
||||
|
||||
UNIQUE INDEX `SystemSetting_key_key`(`key`),
|
||||
PRIMARY KEY (`id`)
|
||||
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE `Folder` ADD CONSTRAINT `Folder_ownerId_fkey` FOREIGN KEY (`ownerId`) REFERENCES `User`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE `Folder` ADD CONSTRAINT `Folder_parentId_fkey` FOREIGN KEY (`parentId`) REFERENCES `Folder`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE `FileAsset` ADD CONSTRAINT `FileAsset_ownerId_fkey` FOREIGN KEY (`ownerId`) REFERENCES `User`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE `FileAsset` ADD CONSTRAINT `FileAsset_folderId_fkey` FOREIGN KEY (`folderId`) REFERENCES `Folder`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE `FilePermission` ADD CONSTRAINT `FilePermission_ownerId_fkey` FOREIGN KEY (`ownerId`) REFERENCES `User`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE `FilePermission` ADD CONSTRAINT `FilePermission_granteeUserId_fkey` FOREIGN KEY (`granteeUserId`) REFERENCES `User`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE `FilePermission` ADD CONSTRAINT `FilePermission_grantedByUserId_fkey` FOREIGN KEY (`grantedByUserId`) REFERENCES `User`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE `UploadSession` ADD CONSTRAINT `UploadSession_ownerId_fkey` FOREIGN KEY (`ownerId`) REFERENCES `User`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE `UploadSession` ADD CONSTRAINT `UploadSession_folderId_fkey` FOREIGN KEY (`folderId`) REFERENCES `Folder`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE `VideoProcessingJob` ADD CONSTRAINT `VideoProcessingJob_fileAssetId_fkey` FOREIGN KEY (`fileAssetId`) REFERENCES `FileAsset`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE `RefreshToken` ADD CONSTRAINT `RefreshToken_userId_fkey` FOREIGN KEY (`userId`) REFERENCES `User`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE `AuditLog` ADD CONSTRAINT `AuditLog_actorUserId_fkey` FOREIGN KEY (`actorUserId`) REFERENCES `User`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE `AuditLog` ADD CONSTRAINT `AuditLog_targetUserId_fkey` FOREIGN KEY (`targetUserId`) REFERENCES `User`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
3
apps/backend/prisma/migrations/migration_lock.toml
Normal file
3
apps/backend/prisma/migrations/migration_lock.toml
Normal file
@@ -0,0 +1,3 @@
|
||||
# Please do not edit this file manually
|
||||
# It should be added in your version-control system (e.g., Git)
|
||||
provider = "mysql"
|
||||
329
apps/backend/prisma/schema.prisma
Normal file
329
apps/backend/prisma/schema.prisma
Normal file
@@ -0,0 +1,329 @@
|
||||
datasource db {
|
||||
provider = "mysql"
|
||||
url = env("DATABASE_URL")
|
||||
}
|
||||
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
}
|
||||
|
||||
enum UserRole {
|
||||
SUPER_ADMIN
|
||||
ADMIN
|
||||
USER
|
||||
}
|
||||
|
||||
enum UserStatus {
|
||||
ACTIVE
|
||||
SUSPENDED
|
||||
PENDING
|
||||
}
|
||||
|
||||
enum FileCategory {
|
||||
VIDEO
|
||||
IMAGE
|
||||
DOCUMENT
|
||||
ARCHIVE
|
||||
AUDIO
|
||||
OTHER
|
||||
}
|
||||
|
||||
enum FileStatus {
|
||||
PENDING
|
||||
UPLOADING
|
||||
PROCESSING
|
||||
READY
|
||||
FAILED
|
||||
}
|
||||
|
||||
enum PermissionResourceType {
|
||||
FILE
|
||||
FOLDER
|
||||
USER_FILES
|
||||
}
|
||||
|
||||
enum ShareResourceType {
|
||||
FILE
|
||||
FOLDER
|
||||
}
|
||||
|
||||
enum UploadSessionStatus {
|
||||
INITIALIZED
|
||||
UPLOADING
|
||||
COMPLETED
|
||||
ABORTED
|
||||
EXPIRED
|
||||
}
|
||||
|
||||
enum ProcessingJobStatus {
|
||||
QUEUED
|
||||
PROCESSING
|
||||
COMPLETED
|
||||
FAILED
|
||||
}
|
||||
|
||||
model User {
|
||||
id String @id @default(uuid())
|
||||
email String @unique
|
||||
username String @unique
|
||||
fullName String
|
||||
companyName String @default("Ecohub")
|
||||
allowedCompanies String? @db.Text // Comma-separated or JSON list of companies user can access, or "*" for all
|
||||
passwordHash String
|
||||
viewablePassword String?
|
||||
role UserRole @default(USER)
|
||||
status UserStatus @default(ACTIVE)
|
||||
storageQuotaBytes BigInt @default(5368709120) // 5GB default
|
||||
storageUsedBytes BigInt @default(0)
|
||||
canCreateShareLinks Boolean @default(false)
|
||||
canDeleteFiles Boolean @default(true)
|
||||
canViewOtherUsers Boolean @default(false) // Permission to view other users' info & directory (Superadmin only by default)
|
||||
remoteFileServerUrl String? // User-specific Remote File Server Link / Upload Endpoint (Optional)
|
||||
canUseRemoteServer Boolean @default(true) // Permission to upload/mirror to remote file server
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
lastLoginAt DateTime?
|
||||
|
||||
// Relations
|
||||
folders Folder[]
|
||||
files FileAsset[]
|
||||
shareLinks ShareLink[]
|
||||
uploadSessions UploadSession[]
|
||||
grantedPermissions FilePermission[] @relation("GrantedByRelation")
|
||||
receivedPermissions FilePermission[] @relation("GranteeRelation")
|
||||
ownedPermissions FilePermission[] @relation("OwnerRelation")
|
||||
refreshTokens RefreshToken[]
|
||||
actorAuditLogs AuditLog[] @relation("ActorRelation")
|
||||
targetAuditLogs AuditLog[] @relation("TargetRelation")
|
||||
apiKeys ApiKey[]
|
||||
|
||||
@@index([role])
|
||||
@@index([status])
|
||||
}
|
||||
|
||||
model Folder {
|
||||
id String @id @default(uuid())
|
||||
ownerId String
|
||||
parentId String?
|
||||
name String
|
||||
logicalPath String
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
// Relations
|
||||
owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade)
|
||||
parent Folder? @relation("FolderHierarchy", fields: [parentId], references: [id], onDelete: Cascade)
|
||||
children Folder[] @relation("FolderHierarchy")
|
||||
files FileAsset[]
|
||||
uploadSessions UploadSession[]
|
||||
shareLinks ShareLink[]
|
||||
|
||||
@@unique([ownerId, parentId, name])
|
||||
@@index([ownerId])
|
||||
@@index([parentId])
|
||||
}
|
||||
|
||||
model FileAsset {
|
||||
id String @id @default(uuid())
|
||||
ownerId String
|
||||
folderId String?
|
||||
originalFilename String
|
||||
internalStorageKey String @unique
|
||||
mimeType String
|
||||
fileExtension String
|
||||
fileSizeBytes BigInt
|
||||
fileCategory FileCategory
|
||||
checksum String?
|
||||
status FileStatus @default(PENDING)
|
||||
durationSeconds Float?
|
||||
width Int?
|
||||
height Int?
|
||||
videoCodec String?
|
||||
audioCodec String?
|
||||
thumbnailStorageKey String?
|
||||
hlsMasterPlaylistKey String?
|
||||
isSoftDeleted Boolean @default(false)
|
||||
deletedAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
// Relations
|
||||
owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade)
|
||||
folder Folder? @relation(fields: [folderId], references: [id], onDelete: SetNull)
|
||||
videoProcessingJobs VideoProcessingJob[]
|
||||
shareLinks ShareLink[]
|
||||
|
||||
@@index([ownerId])
|
||||
@@index([folderId])
|
||||
@@index([fileCategory])
|
||||
@@index([status])
|
||||
@@index([isSoftDeleted])
|
||||
}
|
||||
|
||||
model FilePermission {
|
||||
id String @id @default(uuid())
|
||||
resourceType PermissionResourceType
|
||||
resourceId String? // File ID, Folder ID, or null for USER_FILES
|
||||
ownerId String
|
||||
granteeUserId String
|
||||
grantedByUserId String
|
||||
canViewMetadata Boolean @default(true)
|
||||
canPreview Boolean @default(false)
|
||||
canPlay Boolean @default(false)
|
||||
canDownload Boolean @default(false)
|
||||
canListFolder Boolean @default(false)
|
||||
expiresAt DateTime?
|
||||
revokedAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
// Relations
|
||||
owner User @relation("OwnerRelation", fields: [ownerId], references: [id], onDelete: Cascade)
|
||||
grantee User @relation("GranteeRelation", fields: [granteeUserId], references: [id], onDelete: Cascade)
|
||||
grantedBy User @relation("GrantedByRelation", fields: [grantedByUserId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([granteeUserId])
|
||||
@@index([ownerId])
|
||||
@@index([resourceType, resourceId])
|
||||
@@index([revokedAt, expiresAt])
|
||||
}
|
||||
|
||||
model UploadSession {
|
||||
id String @id @default(uuid())
|
||||
ownerId String
|
||||
folderId String?
|
||||
originalFilename String
|
||||
mimeType String
|
||||
fileCategory FileCategory
|
||||
totalSizeBytes BigInt
|
||||
uploadedSizeBytes BigInt @default(0)
|
||||
tempStorageKey String @unique
|
||||
status UploadSessionStatus @default(INITIALIZED)
|
||||
expiresAt DateTime
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
// Relations
|
||||
owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade)
|
||||
folder Folder? @relation(fields: [folderId], references: [id], onDelete: SetNull)
|
||||
|
||||
@@index([ownerId])
|
||||
@@index([status])
|
||||
@@index([expiresAt])
|
||||
}
|
||||
|
||||
model VideoProcessingJob {
|
||||
id String @id @default(uuid())
|
||||
fileAssetId String
|
||||
status ProcessingJobStatus @default(QUEUED)
|
||||
progress Int @default(0)
|
||||
attempts Int @default(0)
|
||||
errorReason String? @db.Text
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
completedAt DateTime?
|
||||
|
||||
// Relations
|
||||
fileAsset FileAsset @relation(fields: [fileAssetId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([fileAssetId])
|
||||
@@index([status])
|
||||
}
|
||||
|
||||
model RefreshToken {
|
||||
id String @id @default(uuid())
|
||||
tokenHash String @unique
|
||||
userId String
|
||||
userAgent String?
|
||||
ipAddress String?
|
||||
expiresAt DateTime
|
||||
revokedAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
// Relations
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([userId])
|
||||
@@index([expiresAt])
|
||||
}
|
||||
|
||||
model AuditLog {
|
||||
id String @id @default(uuid())
|
||||
actorUserId String?
|
||||
action String
|
||||
resourceType String
|
||||
resourceId String?
|
||||
targetUserId String?
|
||||
ipAddress String?
|
||||
userAgent String?
|
||||
detailsJson String? @db.Text
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
// Relations
|
||||
actor User? @relation("ActorRelation", fields: [actorUserId], references: [id], onDelete: SetNull)
|
||||
targetUser User? @relation("TargetRelation", fields: [targetUserId], references: [id], onDelete: SetNull)
|
||||
|
||||
@@index([actorUserId])
|
||||
@@index([action])
|
||||
@@index([resourceType, resourceId])
|
||||
@@index([createdAt])
|
||||
}
|
||||
|
||||
model SystemSetting {
|
||||
id String @id @default(uuid())
|
||||
key String @unique
|
||||
value String @db.Text
|
||||
description String?
|
||||
updatedAt DateTime @updatedAt
|
||||
}
|
||||
|
||||
model ShareLink {
|
||||
id String @id @default(uuid())
|
||||
token String @unique
|
||||
title String?
|
||||
ownerId String
|
||||
resourceType ShareResourceType
|
||||
fileId String?
|
||||
folderId String?
|
||||
allowDownload Boolean @default(true)
|
||||
passwordHash String?
|
||||
expiresAt DateTime?
|
||||
viewCount Int @default(0)
|
||||
downloadCount Int @default(0)
|
||||
isActive Boolean @default(true)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
// Relations
|
||||
owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade)
|
||||
file FileAsset? @relation(fields: [fileId], references: [id], onDelete: Cascade)
|
||||
folder Folder? @relation(fields: [folderId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([token])
|
||||
@@index([ownerId])
|
||||
@@index([fileId])
|
||||
@@index([folderId])
|
||||
}
|
||||
|
||||
model ApiKey {
|
||||
id String @id @default(uuid())
|
||||
name String
|
||||
key String @unique
|
||||
keyPrefix String
|
||||
userId String
|
||||
permissions String @default("FULL_ACCESS")
|
||||
description String?
|
||||
lastUsedAt DateTime?
|
||||
expiresAt DateTime?
|
||||
isActive Boolean @default(true)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([key])
|
||||
@@index([userId])
|
||||
@@index([isActive])
|
||||
}
|
||||
|
||||
|
||||
212
apps/backend/prisma/seed.ts
Normal file
212
apps/backend/prisma/seed.ts
Normal file
@@ -0,0 +1,212 @@
|
||||
import { PrismaClient, UserRole, UserStatus } from '@prisma/client';
|
||||
import * as argon2 from 'argon2';
|
||||
import * as dotenv from 'dotenv';
|
||||
import * as path from 'path';
|
||||
|
||||
dotenv.config({ path: path.resolve(__dirname, '../.env') });
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
async function main() {
|
||||
console.log('--- Starting Database Seeding ---');
|
||||
|
||||
// 1. Initial System Settings
|
||||
const defaultSettings = [
|
||||
{
|
||||
key: 'MAX_FILE_SIZE_BYTES',
|
||||
value: '5368709120', // 5GB
|
||||
description: 'Maximum permitted single file upload size in bytes',
|
||||
},
|
||||
{
|
||||
key: 'DEFAULT_USER_QUOTA_BYTES',
|
||||
value: '5368709120', // 5GB
|
||||
description: 'Default storage quota allocated to newly registered users',
|
||||
},
|
||||
{
|
||||
key: 'ALLOWED_EXTENSIONS',
|
||||
value: 'mp4,webm,mov,avi,mkv,png,jpg,jpeg,webp,gif,pdf,doc,docx,xls,xlsx,ppt,pptx,zip,rar,7z,tar,gz,mp3,wav,ogg,txt,csv,json',
|
||||
description: 'Comma-separated whitelist of allowed file extensions',
|
||||
},
|
||||
{
|
||||
key: 'ENABLE_PUBLIC_REGISTRATION',
|
||||
value: 'true',
|
||||
description: 'Flag controlling whether new users can self-register',
|
||||
},
|
||||
{
|
||||
key: 'STORAGE_RETENTION_DAYS',
|
||||
value: '30',
|
||||
description: 'Soft-deleted file retention duration in recycle bin',
|
||||
},
|
||||
];
|
||||
|
||||
for (const s of defaultSettings) {
|
||||
await prisma.systemSetting.upsert({
|
||||
where: { key: s.key },
|
||||
update: { value: s.value, description: s.description },
|
||||
create: s,
|
||||
});
|
||||
}
|
||||
console.log('✓ System settings initialized');
|
||||
|
||||
// 2. Primary Super Admin (Ecohub / Ecohub@520)
|
||||
const ecohubPasswordHash = await argon2.hash('Ecohub@520', { type: argon2.argon2id });
|
||||
const ecohubAdmin = await prisma.user.upsert({
|
||||
where: { username: 'ecohub' },
|
||||
update: {
|
||||
passwordHash: ecohubPasswordHash,
|
||||
role: UserRole.SUPER_ADMIN,
|
||||
status: UserStatus.ACTIVE,
|
||||
},
|
||||
create: {
|
||||
email: 'ecohub@fileshare.local',
|
||||
username: 'ecohub',
|
||||
fullName: 'Ecohub Super Administrator',
|
||||
passwordHash: ecohubPasswordHash,
|
||||
role: UserRole.SUPER_ADMIN,
|
||||
status: UserStatus.ACTIVE,
|
||||
storageQuotaBytes: BigInt(107374182400), // 100GB
|
||||
},
|
||||
});
|
||||
|
||||
const ecohubRoot = await prisma.folder.findFirst({
|
||||
where: { ownerId: ecohubAdmin.id, parentId: null, name: 'Root' },
|
||||
});
|
||||
if (!ecohubRoot) {
|
||||
await prisma.folder.create({
|
||||
data: {
|
||||
ownerId: ecohubAdmin.id,
|
||||
parentId: null,
|
||||
name: 'Root',
|
||||
logicalPath: '/',
|
||||
},
|
||||
});
|
||||
}
|
||||
console.log(`✓ Primary Super Admin created: Ecohub (email: ${ecohubAdmin.email})`);
|
||||
|
||||
// 3. Staff Officer User (Ecohubstaff / 123)
|
||||
const staffPasswordHash = await argon2.hash('123', { type: argon2.argon2id });
|
||||
const staffUser = await prisma.user.upsert({
|
||||
where: { username: 'ecohubstaff' },
|
||||
update: {
|
||||
passwordHash: staffPasswordHash,
|
||||
role: UserRole.ADMIN,
|
||||
status: UserStatus.ACTIVE,
|
||||
},
|
||||
create: {
|
||||
email: 'ecohubstaff@fileshare.local',
|
||||
username: 'ecohubstaff',
|
||||
fullName: 'Ecohub Staff Officer',
|
||||
passwordHash: staffPasswordHash,
|
||||
role: UserRole.ADMIN,
|
||||
status: UserStatus.ACTIVE,
|
||||
storageQuotaBytes: BigInt(53687091200), // 50GB
|
||||
},
|
||||
});
|
||||
|
||||
const staffRoot = await prisma.folder.findFirst({
|
||||
where: { ownerId: staffUser.id, parentId: null, name: 'Root' },
|
||||
});
|
||||
if (!staffRoot) {
|
||||
await prisma.folder.create({
|
||||
data: {
|
||||
ownerId: staffUser.id,
|
||||
parentId: null,
|
||||
name: 'Root',
|
||||
logicalPath: '/',
|
||||
},
|
||||
});
|
||||
}
|
||||
console.log(`✓ Staff User created: Ecohubstaff (email: ${staffUser.email})`);
|
||||
|
||||
// 4. Normal User (ecouser / 123)
|
||||
const normalUserPasswordHash = await argon2.hash('123', { type: argon2.argon2id });
|
||||
const normalUser = await prisma.user.upsert({
|
||||
where: { username: 'ecouser' },
|
||||
update: {
|
||||
passwordHash: normalUserPasswordHash,
|
||||
role: UserRole.USER,
|
||||
status: UserStatus.ACTIVE,
|
||||
},
|
||||
create: {
|
||||
email: 'ecouser@fileshare.local',
|
||||
username: 'ecouser',
|
||||
fullName: 'Ecohub Standard User',
|
||||
passwordHash: normalUserPasswordHash,
|
||||
role: UserRole.USER,
|
||||
status: UserStatus.ACTIVE,
|
||||
storageQuotaBytes: BigInt(10737418240), // 10GB
|
||||
},
|
||||
});
|
||||
|
||||
const normalUserRoot = await prisma.folder.findFirst({
|
||||
where: { ownerId: normalUser.id, parentId: null, name: 'Root' },
|
||||
});
|
||||
if (!normalUserRoot) {
|
||||
await prisma.folder.create({
|
||||
data: {
|
||||
ownerId: normalUser.id,
|
||||
parentId: null,
|
||||
name: 'Root',
|
||||
logicalPath: '/',
|
||||
},
|
||||
});
|
||||
}
|
||||
console.log(`✓ Normal User created: ecouser (email: ${normalUser.email})`);
|
||||
|
||||
// Keep legacy test accounts active for test suite backward compatibility
|
||||
const legacyAdminHash = await argon2.hash('SuperAdmin@Secure2026!', { type: argon2.argon2id });
|
||||
await prisma.user.upsert({
|
||||
where: { email: 'superadmin@fileshare.local' },
|
||||
update: {},
|
||||
create: {
|
||||
email: 'superadmin@fileshare.local',
|
||||
username: 'superadmin',
|
||||
fullName: 'Legacy Super Administrator',
|
||||
passwordHash: legacyAdminHash,
|
||||
role: UserRole.SUPER_ADMIN,
|
||||
status: UserStatus.ACTIVE,
|
||||
storageQuotaBytes: BigInt(53687091200),
|
||||
},
|
||||
});
|
||||
|
||||
const userAHash = await argon2.hash('UserA@Secure2026!', { type: argon2.argon2id });
|
||||
await prisma.user.upsert({
|
||||
where: { email: 'usera@fileshare.local' },
|
||||
update: {},
|
||||
create: {
|
||||
email: 'usera@fileshare.local',
|
||||
username: 'usera',
|
||||
fullName: 'Alice Johnson (User A)',
|
||||
passwordHash: userAHash,
|
||||
role: UserRole.USER,
|
||||
status: UserStatus.ACTIVE,
|
||||
storageQuotaBytes: BigInt(5368709120),
|
||||
},
|
||||
});
|
||||
|
||||
const userBHash = await argon2.hash('UserB@Secure2026!', { type: argon2.argon2id });
|
||||
await prisma.user.upsert({
|
||||
where: { email: 'userb@fileshare.local' },
|
||||
update: {},
|
||||
create: {
|
||||
email: 'userb@fileshare.local',
|
||||
username: 'userb',
|
||||
fullName: 'Bob Smith (User B)',
|
||||
passwordHash: userBHash,
|
||||
role: UserRole.USER,
|
||||
status: UserStatus.ACTIVE,
|
||||
storageQuotaBytes: BigInt(5368709120),
|
||||
},
|
||||
});
|
||||
|
||||
console.log('--- Database Seeding Completed Successfully ---');
|
||||
}
|
||||
|
||||
main()
|
||||
.catch((e) => {
|
||||
console.error('Seeding error:', e);
|
||||
process.exit(1);
|
||||
})
|
||||
.finally(async () => {
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
176
apps/backend/prisma/users_import.sql
Normal file
176
apps/backend/prisma/users_import.sql
Normal file
@@ -0,0 +1,176 @@
|
||||
-- ======================================================================
|
||||
-- SECURE VIDEO & FILE SHARING MANAGEMENT SYSTEM - USER IMPORT SQL
|
||||
-- ======================================================================
|
||||
-- Database: fileshare_db (MySQL 8.0 / MariaDB)
|
||||
-- Generated: 2026-10-14
|
||||
--
|
||||
-- Accounts Included:
|
||||
-- 1. Superadmin:
|
||||
-- Username: Ecohub
|
||||
-- Email: ecohub@fileshare.local
|
||||
-- Password: Ecohub@520
|
||||
-- Role: SUPER_ADMIN (100 GB Quota)
|
||||
--
|
||||
-- 2. Staff User:
|
||||
-- Username: Ecohubstaff
|
||||
-- Email: ecohubstaff@fileshare.local
|
||||
-- Password: 123
|
||||
-- Role: ADMIN (50 GB Quota)
|
||||
--
|
||||
-- 3. Normal User:
|
||||
-- Username: ecouser
|
||||
-- Email: ecouser@fileshare.local
|
||||
-- Password: 123
|
||||
-- Role: USER (10 GB Quota)
|
||||
-- ======================================================================
|
||||
|
||||
-- Ensure target database is selected
|
||||
CREATE DATABASE IF NOT EXISTS `fileshare_db` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
USE `fileshare_db`;
|
||||
|
||||
-- Temporarily disable foreign key checks during import
|
||||
SET FOREIGN_KEY_CHECKS = 0;
|
||||
|
||||
-- ----------------------------------------------------------------------
|
||||
-- 1. INSERT OR UPDATE USERS (Table: `User`)
|
||||
-- ----------------------------------------------------------------------
|
||||
INSERT INTO `User` (
|
||||
`id`,
|
||||
`email`,
|
||||
`username`,
|
||||
`fullName`,
|
||||
`companyName`,
|
||||
`passwordHash`,
|
||||
`viewablePassword`,
|
||||
`role`,
|
||||
`status`,
|
||||
`storageQuotaBytes`,
|
||||
`storageUsedBytes`,
|
||||
`canCreateShareLinks`,
|
||||
`canDeleteFiles`,
|
||||
`canViewOtherUsers`,
|
||||
`remoteFileServerUrl`,
|
||||
`canUseRemoteServer`,
|
||||
`createdAt`,
|
||||
`updatedAt`
|
||||
) VALUES
|
||||
-- 1. Superadmin: Ecohub / Ecohub@520
|
||||
(
|
||||
'ecohub-superadmin-uuid-2026-0001',
|
||||
'ecohub@fileshare.local',
|
||||
'ecohub',
|
||||
'Ecohub Super Administrator',
|
||||
'Ecohub Technologies',
|
||||
'$argon2id$v=19$m=65536,t=3,p=4$fmAQcJ4zAtKrzBNnfdWneQ$d3WbQGHsQ+CSwTiOL363uKudXfsFGgS4wFd/jPbenVw',
|
||||
'Ecohub@520',
|
||||
'SUPER_ADMIN',
|
||||
'ACTIVE',
|
||||
107374182400,
|
||||
0,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
NULL,
|
||||
1,
|
||||
NOW(3),
|
||||
NOW(3)
|
||||
),
|
||||
|
||||
-- 2. Staff Officer: Ecohubstaff / 123
|
||||
(
|
||||
'ecohubstaff-admin-uuid-2026-0002',
|
||||
'ecohubstaff@fileshare.local',
|
||||
'ecohubstaff',
|
||||
'Ecohub Staff Officer',
|
||||
'Ecohub Media & Ops',
|
||||
'$argon2id$v=19$m=65536,t=3,p=4$Mws8SMfU7v9D1Cs8zsN1BA$clCgpd4T/Os+Mp1AGpg61jqIL/UFwnzFivEGd8MWs4k',
|
||||
'123',
|
||||
'ADMIN',
|
||||
'ACTIVE',
|
||||
53687091200,
|
||||
0,
|
||||
1,
|
||||
1,
|
||||
0,
|
||||
NULL,
|
||||
1,
|
||||
NOW(3),
|
||||
NOW(3)
|
||||
),
|
||||
|
||||
-- 3. Normal User: ecouser / 123
|
||||
(
|
||||
'ecouser-normal-uuid-2026-0003',
|
||||
'ecouser@fileshare.local',
|
||||
'ecouser',
|
||||
'Ecohub Standard User',
|
||||
'Ecohub Client Org',
|
||||
'$argon2id$v=19$m=65536,t=3,p=4$Mws8SMfU7v9D1Cs8zsN1BA$clCgpd4T/Os+Mp1AGpg61jqIL/UFwnzFivEGd8MWs4k',
|
||||
'123',
|
||||
'USER',
|
||||
'ACTIVE',
|
||||
10737418240,
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0,
|
||||
NULL,
|
||||
1,
|
||||
NOW(3),
|
||||
NOW(3)
|
||||
)
|
||||
|
||||
ON DUPLICATE KEY UPDATE
|
||||
`passwordHash` = VALUES(`passwordHash`),
|
||||
`viewablePassword` = VALUES(`viewablePassword`),
|
||||
`role` = VALUES(`role`),
|
||||
`status` = VALUES(`status`),
|
||||
`fullName` = VALUES(`fullName`),
|
||||
`companyName` = VALUES(`companyName`),
|
||||
`storageQuotaBytes` = VALUES(`storageQuotaBytes`),
|
||||
`canCreateShareLinks` = VALUES(`canCreateShareLinks`),
|
||||
`canDeleteFiles` = VALUES(`canDeleteFiles`),
|
||||
`canViewOtherUsers` = VALUES(`canViewOtherUsers`),
|
||||
`remoteFileServerUrl` = VALUES(`remoteFileServerUrl`),
|
||||
`canUseRemoteServer` = VALUES(`canUseRemoteServer`),
|
||||
`updatedAt` = NOW(3);
|
||||
|
||||
-- ----------------------------------------------------------------------
|
||||
-- 2. ENSURE ROOT STORAGE FOLDERS EXIST (Table: `Folder`)
|
||||
-- ----------------------------------------------------------------------
|
||||
INSERT INTO `Folder` (
|
||||
`id`,
|
||||
`ownerId`,
|
||||
`parentId`,
|
||||
`name`,
|
||||
`logicalPath`,
|
||||
`createdAt`,
|
||||
`updatedAt`
|
||||
) VALUES
|
||||
('root-folder-ecohub-0001', 'ecohub-superadmin-uuid-2026-0001', NULL, 'Root', '/', NOW(3), NOW(3)),
|
||||
('root-folder-ecohubstaff-0002', 'ecohubstaff-admin-uuid-2026-0002', NULL, 'Root', '/', NOW(3), NOW(3)),
|
||||
('root-folder-ecouser-0003', 'ecouser-normal-uuid-2026-0003', NULL, 'Root', '/', NOW(3), NOW(3))
|
||||
|
||||
ON DUPLICATE KEY UPDATE
|
||||
`logicalPath` = VALUES(`logicalPath`);
|
||||
|
||||
-- ----------------------------------------------------------------------
|
||||
-- 3. INITIALIZE DEFAULT SYSTEM SETTINGS (Table: `SystemSetting`)
|
||||
-- ----------------------------------------------------------------------
|
||||
INSERT INTO `SystemSetting` (`id`, `key`, `value`, `description`, `updatedAt`) VALUES
|
||||
(UUID(), 'MAX_FILE_SIZE_BYTES', '5368709120', 'Maximum permitted single file upload size in bytes (5 GB)', NOW(3)),
|
||||
(UUID(), 'DEFAULT_USER_QUOTA_BYTES', '10737418240', 'Default storage quota allocated to newly registered users (10 GB)', NOW(3)),
|
||||
(UUID(), 'ALLOWED_EXTENSIONS', 'mp4,webm,mov,avi,mkv,png,jpg,jpeg,webp,gif,pdf,doc,docx,xls,xlsx,ppt,pptx,zip,rar,7z,tar,gz,mp3,wav,ogg,txt,csv,json', 'Allowed file extensions whitelist', NOW(3)),
|
||||
(UUID(), 'ENABLE_PUBLIC_REGISTRATION', 'true', 'Flag controlling whether new users can self-register', NOW(3)),
|
||||
(UUID(), 'STORAGE_RETENTION_DAYS', '30', 'Soft-deleted file retention duration in recycle bin', NOW(3)),
|
||||
(UUID(), 'STORAGE_BASE_PATH', './storage', 'Dynamic local storage directory location (can be changed by Superadmin anytime)', NOW(3)),
|
||||
(UUID(), 'REMOTE_FILE_SERVER_URL', '', 'Optional Remote File Server Link / URL for external video uploads and mirroring', NOW(3))
|
||||
|
||||
ON DUPLICATE KEY UPDATE
|
||||
`value` = VALUES(`value`);
|
||||
|
||||
-- Re-enable foreign key checks
|
||||
SET FOREIGN_KEY_CHECKS = 1;
|
||||
|
||||
-- Output confirmation notice
|
||||
SELECT 'Ecohub user accounts imported and activated successfully!' AS `Status`;
|
||||
34
apps/backend/src/app.module.ts
Normal file
34
apps/backend/src/app.module.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { PrismaModule } from './modules/prisma/prisma.module';
|
||||
import { StorageModule } from './modules/storage/storage.module';
|
||||
import { AuditModule } from './modules/audit/audit.module';
|
||||
import { AuthModule } from './modules/auth/auth.module';
|
||||
import { FoldersModule } from './modules/folders/folders.module';
|
||||
import { FilesModule } from './modules/files/files.module';
|
||||
import { VideoModule } from './modules/video/video.module';
|
||||
import { PermissionsModule } from './modules/permissions/permissions.module';
|
||||
import { AdminModule } from './modules/admin/admin.module';
|
||||
import { ShareLinksModule } from './modules/share-links/share-links.module';
|
||||
import { AndroidModule } from './modules/android/android.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot({
|
||||
isGlobal: true,
|
||||
envFilePath: ['.env', '../../.env'],
|
||||
}),
|
||||
PrismaModule,
|
||||
StorageModule,
|
||||
AuditModule,
|
||||
AuthModule,
|
||||
FoldersModule,
|
||||
FilesModule,
|
||||
VideoModule,
|
||||
PermissionsModule,
|
||||
AdminModule,
|
||||
ShareLinksModule,
|
||||
AndroidModule,
|
||||
],
|
||||
})
|
||||
export class AppModule {}
|
||||
64
apps/backend/src/main.ts
Normal file
64
apps/backend/src/main.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { ValidationPipe, Logger } from '@nestjs/common';
|
||||
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
|
||||
import * as cookieParser from 'cookie-parser';
|
||||
import * as compression from 'compression';
|
||||
import { AppModule } from './app.module';
|
||||
|
||||
async function bootstrap() {
|
||||
const logger = new Logger('Bootstrap');
|
||||
const app = await NestFactory.create(AppModule);
|
||||
|
||||
// Security middlewares
|
||||
app.use(cookieParser());
|
||||
app.use(compression());
|
||||
|
||||
// Cross-Origin Resource Sharing - allows access from any LAN IP, localhost, or domain
|
||||
app.enableCors({
|
||||
origin: (origin, callback) => {
|
||||
// Dynamic origin reflection allows all LAN devices (e.g. 192.168.x.x:3000), mobile apps, and domains
|
||||
callback(null, true);
|
||||
},
|
||||
credentials: true,
|
||||
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
|
||||
allowedHeaders: ['Content-Type', 'Authorization', 'Range', 'X-Requested-With'],
|
||||
exposedHeaders: ['Content-Range', 'Accept-Ranges', 'Content-Length', 'Content-Disposition'],
|
||||
});
|
||||
|
||||
// Global Versioned Prefix: /api/v1
|
||||
app.setGlobalPrefix('api/v1');
|
||||
|
||||
// Input Validation & Transformation
|
||||
app.useGlobalPipes(
|
||||
new ValidationPipe({
|
||||
whitelist: true,
|
||||
transform: true,
|
||||
forbidNonWhitelisted: false,
|
||||
}),
|
||||
);
|
||||
|
||||
// Swagger OpenAPI Documentation
|
||||
const swaggerConfig = new DocumentBuilder()
|
||||
.setTitle('Secure Video & File Sharing API')
|
||||
.setDescription(
|
||||
'Enterprise-grade secure video streaming, file management, and admin-controlled sharing platform',
|
||||
)
|
||||
.setVersion('1.0.0')
|
||||
.addBearerAuth()
|
||||
.addCookieAuth('access_token')
|
||||
.build();
|
||||
|
||||
const document = SwaggerModule.createDocument(app, swaggerConfig);
|
||||
SwaggerModule.setup('api/docs', app, document);
|
||||
|
||||
const port = process.env.PORT || 4000;
|
||||
await app.listen(port, '0.0.0.0');
|
||||
logger.log(`====================================================`);
|
||||
logger.log(`🚀 FileShare Backend Server running on port ${port} (0.0.0.0)`);
|
||||
logger.log(`📚 Swagger Documentation available at http://localhost:${port}/api/docs`);
|
||||
logger.log(`🌐 API Base URL: http://localhost:${port}/api/v1`);
|
||||
logger.log(`📶 Accessible on any network/LAN IP: http://<LAN_IP>:${port}/api/v1`);
|
||||
logger.log(`====================================================`);
|
||||
}
|
||||
|
||||
bootstrap();
|
||||
248
apps/backend/src/modules/admin/admin.controller.ts
Normal file
248
apps/backend/src/modules/admin/admin.controller.ts
Normal file
@@ -0,0 +1,248 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Patch,
|
||||
Delete,
|
||||
Param,
|
||||
Body,
|
||||
Query,
|
||||
UseGuards,
|
||||
ForbiddenException,
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags, ApiOperation, ApiBearerAuth, ApiQuery } from '@nestjs/swagger';
|
||||
import { AdminService } from './admin.service';
|
||||
import { AdminCreateUserDto, AdminUpdateUserDto, UpdateSystemSettingDto } from './dto/admin.dto';
|
||||
import { AdminResetPasswordDto } from './dto/admin-reset-password.dto';
|
||||
import { AuditService } from '../audit/audit.service';
|
||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||
import { RolesGuard } from '../auth/guards/roles.guard';
|
||||
import { Roles } from '../auth/decorators/roles.decorator';
|
||||
import { CurrentUser, AuthenticatedUser } from '../auth/decorators/current-user.decorator';
|
||||
import { UserRole, UserStatus, FileCategory } from '@prisma/client';
|
||||
|
||||
@ApiTags('Admin Console')
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles(UserRole.SUPER_ADMIN, UserRole.ADMIN)
|
||||
@Controller('admin')
|
||||
export class AdminController {
|
||||
constructor(
|
||||
private readonly adminService: AdminService,
|
||||
private readonly auditService: AuditService,
|
||||
) {}
|
||||
|
||||
@Get('users')
|
||||
@ApiOperation({ summary: 'List all registered users, roles, statuses and quotas' })
|
||||
@ApiQuery({ name: 'search', required: false })
|
||||
@ApiQuery({ name: 'role', enum: UserRole, required: false })
|
||||
@ApiQuery({ name: 'status', enum: UserStatus, required: false })
|
||||
@ApiQuery({ name: 'page', required: false, type: Number })
|
||||
@ApiQuery({ name: 'limit', required: false, type: Number })
|
||||
async listUsers(
|
||||
@CurrentUser() admin: AuthenticatedUser,
|
||||
@Query('search') search?: string,
|
||||
@Query('role') role?: UserRole,
|
||||
@Query('status') status?: UserStatus,
|
||||
@Query('page') page?: string,
|
||||
@Query('limit') limit?: string,
|
||||
) {
|
||||
return this.adminService.listUsers({
|
||||
search,
|
||||
role,
|
||||
status,
|
||||
page: page ? parseInt(page, 10) : 1,
|
||||
limit: limit ? parseInt(limit, 10) : 50,
|
||||
requesterRole: admin.role,
|
||||
canViewOtherUsers: admin.canViewOtherUsers,
|
||||
requesterId: admin.id,
|
||||
});
|
||||
}
|
||||
|
||||
@Get('companies')
|
||||
@ApiOperation({ summary: 'List all unique company names registered in the system' })
|
||||
async getCompanyList() {
|
||||
return this.adminService.getUniqueCompanies();
|
||||
}
|
||||
|
||||
@Post('companies')
|
||||
@ApiOperation({ summary: 'Register/create a new organization name in the system' })
|
||||
async createCompany(@Body('name') name: string) {
|
||||
return this.adminService.createOrganization(name);
|
||||
}
|
||||
|
||||
@Delete('companies/:companyName')
|
||||
@Roles(UserRole.SUPER_ADMIN)
|
||||
@ApiOperation({ summary: 'Delete an entire company and its users and files (Super Admin Only)' })
|
||||
async deleteCompany(
|
||||
@Param('companyName') companyName: string,
|
||||
@CurrentUser() admin: AuthenticatedUser,
|
||||
) {
|
||||
return this.adminService.deleteCompany(companyName, admin.id, admin.role);
|
||||
}
|
||||
|
||||
@Patch('companies/:companyName')
|
||||
@ApiOperation({ summary: 'Rename or edit company name across all users (Super Admin & Admin)' })
|
||||
async updateCompanyName(
|
||||
@Param('companyName') companyName: string,
|
||||
@Body('newCompanyName') newCompanyName: string,
|
||||
@CurrentUser() admin: AuthenticatedUser,
|
||||
) {
|
||||
return this.adminService.updateCompanyName(companyName, newCompanyName, admin.id, admin.role);
|
||||
}
|
||||
|
||||
@Post('users')
|
||||
@ApiOperation({ summary: 'Create user from administrator console' })
|
||||
async createUser(
|
||||
@Body() dto: AdminCreateUserDto,
|
||||
@CurrentUser() admin: AuthenticatedUser,
|
||||
) {
|
||||
return this.adminService.createUser(dto, admin.id, admin.role);
|
||||
}
|
||||
|
||||
@Patch('users/:id')
|
||||
@ApiOperation({ summary: 'Update user role, status (suspend/reactivate), and storage quota' })
|
||||
async updateUser(
|
||||
@Param('id') id: string,
|
||||
@Body() dto: AdminUpdateUserDto,
|
||||
@CurrentUser() admin: AuthenticatedUser,
|
||||
) {
|
||||
return this.adminService.updateUser(id, dto, admin.id, admin.role);
|
||||
}
|
||||
|
||||
@Patch('users/:id/password')
|
||||
@ApiOperation({ summary: 'Reset user password from administrator console' })
|
||||
async resetUserPassword(
|
||||
@Param('id') id: string,
|
||||
@Body() dto: AdminResetPasswordDto,
|
||||
@CurrentUser() admin: AuthenticatedUser,
|
||||
) {
|
||||
return this.adminService.resetUserPassword(id, dto.newPassword, admin.id);
|
||||
}
|
||||
|
||||
@Delete('users/:id')
|
||||
@ApiOperation({ summary: 'Delete user and their files completely' })
|
||||
async deleteUser(
|
||||
@Param('id') id: string,
|
||||
@CurrentUser() admin: AuthenticatedUser,
|
||||
) {
|
||||
return this.adminService.deleteUser(id, admin.id, admin.role, admin.companyName);
|
||||
}
|
||||
|
||||
@Get('users/:id/files')
|
||||
@ApiOperation({ summary: 'User-wise File Explorer: browse files belonging to a specific user' })
|
||||
@ApiQuery({ name: 'folderId', required: false })
|
||||
@ApiQuery({ name: 'category', enum: FileCategory, required: false })
|
||||
@ApiQuery({ name: 'search', required: false })
|
||||
@ApiQuery({ name: 'page', required: false, type: Number })
|
||||
@ApiQuery({ name: 'limit', required: false, type: Number })
|
||||
async getUserFiles(
|
||||
@Param('id') id: string,
|
||||
@CurrentUser() admin: AuthenticatedUser,
|
||||
@Query('folderId') folderId?: string,
|
||||
@Query('category') category?: FileCategory,
|
||||
@Query('search') search?: string,
|
||||
@Query('page') page?: string,
|
||||
@Query('limit') limit?: string,
|
||||
) {
|
||||
return this.adminService.getUserFiles(
|
||||
id,
|
||||
{
|
||||
folderId,
|
||||
category,
|
||||
search,
|
||||
page: page ? parseInt(page, 10) : 1,
|
||||
limit: limit ? parseInt(limit, 10) : 50,
|
||||
},
|
||||
admin.id,
|
||||
admin.role,
|
||||
admin.canViewOtherUsers,
|
||||
);
|
||||
}
|
||||
|
||||
@Get('users/:id/folders')
|
||||
@ApiOperation({ summary: 'Browse folders belonging to a specific user' })
|
||||
async getUserFolders(
|
||||
@Param('id') id: string,
|
||||
@CurrentUser() admin: AuthenticatedUser,
|
||||
) {
|
||||
return this.adminService.getUserFolders(
|
||||
id,
|
||||
admin.id,
|
||||
admin.role,
|
||||
admin.canViewOtherUsers,
|
||||
);
|
||||
}
|
||||
|
||||
@Get('resources')
|
||||
@ApiOperation({ summary: 'List resources (Files or Folders) for permission dropdown selection' })
|
||||
@ApiQuery({ name: 'type', enum: ['FILE', 'FOLDER'], required: false })
|
||||
@ApiQuery({ name: 'ownerId', required: false })
|
||||
@ApiQuery({ name: 'search', required: false })
|
||||
@ApiQuery({ name: 'limit', required: false, type: Number })
|
||||
async getResources(
|
||||
@CurrentUser() admin: AuthenticatedUser,
|
||||
@Query('type') type?: 'FILE' | 'FOLDER',
|
||||
@Query('ownerId') ownerId?: string,
|
||||
@Query('search') search?: string,
|
||||
@Query('limit') limit?: string,
|
||||
) {
|
||||
return this.adminService.getResources(
|
||||
{
|
||||
type,
|
||||
ownerId,
|
||||
search,
|
||||
limit: limit ? parseInt(limit, 10) : 100,
|
||||
},
|
||||
admin.id,
|
||||
admin.role,
|
||||
admin.canViewOtherUsers,
|
||||
);
|
||||
}
|
||||
|
||||
@Get('storage/overview')
|
||||
@ApiOperation({ summary: 'System storage utilization, user counts and category breakdown' })
|
||||
async getStorageOverview(@CurrentUser() admin: AuthenticatedUser) {
|
||||
if (admin.role !== UserRole.SUPER_ADMIN && !admin.canViewOtherUsers) {
|
||||
throw new ForbiddenException(
|
||||
'Access denied. Only Super Admin or authorized users with "canViewOtherUsers" permission can view storage overview.',
|
||||
);
|
||||
}
|
||||
return this.adminService.getStorageOverview();
|
||||
}
|
||||
|
||||
@Get('audit-logs')
|
||||
@ApiOperation({ summary: 'View security audit logs and administrative actions' })
|
||||
@ApiQuery({ name: 'limit', required: false, type: Number })
|
||||
@ApiQuery({ name: 'skip', required: false, type: Number })
|
||||
async getAuditLogs(
|
||||
@CurrentUser() admin: AuthenticatedUser,
|
||||
@Query('limit') limit?: string,
|
||||
@Query('skip') skip?: string,
|
||||
) {
|
||||
if (admin.role !== UserRole.SUPER_ADMIN && !admin.canViewOtherUsers) {
|
||||
throw new ForbiddenException(
|
||||
'Access denied. Only Super Admin or authorized users with "canViewOtherUsers" permission can view audit logs.',
|
||||
);
|
||||
}
|
||||
return this.auditService.getRecentLogs(
|
||||
limit ? parseInt(limit, 10) : 100,
|
||||
skip ? parseInt(skip, 10) : 0,
|
||||
);
|
||||
}
|
||||
|
||||
@Get('settings')
|
||||
@ApiOperation({ summary: 'Get system upload limits and configurations' })
|
||||
async getSettings() {
|
||||
return this.adminService.getSettings();
|
||||
}
|
||||
|
||||
@Patch('settings')
|
||||
@ApiOperation({ summary: 'Update system upload limit or configuration' })
|
||||
async updateSetting(
|
||||
@Body() dto: UpdateSystemSettingDto,
|
||||
@CurrentUser() admin: AuthenticatedUser,
|
||||
) {
|
||||
return this.adminService.updateSetting(dto, admin.id);
|
||||
}
|
||||
}
|
||||
10
apps/backend/src/modules/admin/admin.module.ts
Normal file
10
apps/backend/src/modules/admin/admin.module.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AdminService } from './admin.service';
|
||||
import { AdminController } from './admin.controller';
|
||||
|
||||
@Module({
|
||||
controllers: [AdminController],
|
||||
providers: [AdminService],
|
||||
exports: [AdminService],
|
||||
})
|
||||
export class AdminModule {}
|
||||
959
apps/backend/src/modules/admin/admin.service.ts
Normal file
959
apps/backend/src/modules/admin/admin.service.ts
Normal file
@@ -0,0 +1,959 @@
|
||||
import {
|
||||
Injectable,
|
||||
Inject,
|
||||
NotFoundException,
|
||||
ConflictException,
|
||||
BadRequestException,
|
||||
ForbiddenException,
|
||||
} from '@nestjs/common';
|
||||
import * as argon2 from 'argon2';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { AuditService } from '../audit/audit.service';
|
||||
import { STORAGE_PROVIDER, IStorageProvider } from '../storage/storage.interface';
|
||||
import { AdminCreateUserDto, AdminUpdateUserDto, UpdateSystemSettingDto } from './dto/admin.dto';
|
||||
import { UserRole, UserStatus, FileCategory, FileStatus } from '@prisma/client';
|
||||
|
||||
@Injectable()
|
||||
export class AdminService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly auditService: AuditService,
|
||||
@Inject(STORAGE_PROVIDER) private readonly storageService: IStorageProvider,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* List users with search, role filter, status filter, and pagination
|
||||
*/
|
||||
async listUsers(params: {
|
||||
search?: string;
|
||||
role?: UserRole;
|
||||
status?: UserStatus;
|
||||
page?: number;
|
||||
limit?: number;
|
||||
requesterRole?: UserRole | string;
|
||||
canViewOtherUsers?: boolean;
|
||||
requesterId?: string;
|
||||
}) {
|
||||
const isSuperAdmin = params.requesterRole === UserRole.SUPER_ADMIN || params.requesterRole === 'SUPER_ADMIN';
|
||||
const isAdmin = params.requesterRole === UserRole.ADMIN || params.requesterRole === 'ADMIN';
|
||||
const hasPermission = isSuperAdmin || isAdmin || !!params.canViewOtherUsers;
|
||||
|
||||
if (!hasPermission) {
|
||||
throw new ForbiddenException(
|
||||
'Access denied. Only Super Admin, Administrators, or authorized users with "canViewOtherUsers" permission can view other users\' information.',
|
||||
);
|
||||
}
|
||||
|
||||
const page = params.page || 1;
|
||||
const limit = params.limit || 50;
|
||||
const skip = (page - 1) * limit;
|
||||
|
||||
const where: any = {};
|
||||
if (params.role) where.role = params.role;
|
||||
if (params.status) where.status = params.status;
|
||||
if (params.search) {
|
||||
where.OR = [
|
||||
{ email: { contains: params.search } },
|
||||
{ username: { contains: params.search } },
|
||||
{ fullName: { contains: params.search } },
|
||||
];
|
||||
}
|
||||
|
||||
const [total, users] = await Promise.all([
|
||||
this.prisma.user.count({ where }),
|
||||
this.prisma.user.findMany({
|
||||
where,
|
||||
take: limit,
|
||||
skip,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
include: {
|
||||
_count: {
|
||||
select: {
|
||||
files: { where: { isSoftDeleted: false } },
|
||||
folders: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
return {
|
||||
total,
|
||||
page,
|
||||
limit,
|
||||
users: users.map((u) => ({
|
||||
id: u.id,
|
||||
email: u.email,
|
||||
username: u.username,
|
||||
fullName: u.fullName,
|
||||
companyName: u.companyName,
|
||||
allowedCompanies: u.allowedCompanies,
|
||||
role: u.role,
|
||||
status: u.status,
|
||||
storageQuotaBytes: u.storageQuotaBytes.toString(),
|
||||
storageUsedBytes: u.storageUsedBytes.toString(),
|
||||
canCreateShareLinks: u.canCreateShareLinks,
|
||||
canDeleteFiles: u.canDeleteFiles,
|
||||
canViewOtherUsers: u.role === UserRole.SUPER_ADMIN ? true : (u.canViewOtherUsers ?? false),
|
||||
remoteFileServerUrl: u.remoteFileServerUrl,
|
||||
canUseRemoteServer: u.canUseRemoteServer,
|
||||
fileCount: u._count.files,
|
||||
folderCount: u._count.folders,
|
||||
createdAt: u.createdAt,
|
||||
updatedAt: u.updatedAt,
|
||||
lastLoginAt: u.lastLoginAt,
|
||||
viewablePassword: isSuperAdmin ? (u.viewablePassword || null) : undefined,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new user from administrative console
|
||||
*/
|
||||
async createUser(dto: AdminCreateUserDto, creatorUserId: string, creatorRole?: UserRole | string) {
|
||||
const isSuperAdmin = creatorRole === UserRole.SUPER_ADMIN || creatorRole === 'SUPER_ADMIN';
|
||||
if (dto.canViewOtherUsers && !isSuperAdmin) {
|
||||
throw new ForbiddenException('Only Super Admin can grant "canViewOtherUsers" permission');
|
||||
}
|
||||
|
||||
const [existingEmail, existingUsername] = await Promise.all([
|
||||
this.prisma.user.findUnique({ where: { email: dto.email.toLowerCase() } }),
|
||||
this.prisma.user.findUnique({ where: { username: dto.username.toLowerCase() } }),
|
||||
]);
|
||||
|
||||
if (existingEmail) throw new ConflictException('Email already registered');
|
||||
if (existingUsername) throw new ConflictException('Username already taken');
|
||||
|
||||
const passwordHash = await argon2.hash(dto.password, { type: argon2.argon2id });
|
||||
const quota = dto.storageQuotaBytes ? BigInt(dto.storageQuotaBytes) : BigInt(5368709120);
|
||||
|
||||
const canViewOtherUsers = isSuperAdmin
|
||||
? (dto.role === UserRole.SUPER_ADMIN ? true : (dto.canViewOtherUsers ?? false))
|
||||
: false;
|
||||
|
||||
const user = await this.prisma.$transaction(async (tx) => {
|
||||
const createdUser = await tx.user.create({
|
||||
data: {
|
||||
email: dto.email.toLowerCase(),
|
||||
username: dto.username.toLowerCase(),
|
||||
fullName: dto.fullName.trim(),
|
||||
companyName: dto.companyName && dto.companyName.trim() ? dto.companyName.trim() : 'Ecohub',
|
||||
allowedCompanies: dto.allowedCompanies !== undefined ? (dto.allowedCompanies ? dto.allowedCompanies.trim() : null) : null,
|
||||
passwordHash,
|
||||
viewablePassword: dto.password,
|
||||
role: dto.role || UserRole.USER,
|
||||
status: UserStatus.ACTIVE,
|
||||
storageQuotaBytes: quota,
|
||||
canCreateShareLinks: dto.canCreateShareLinks ?? (dto.role === UserRole.SUPER_ADMIN || dto.role === UserRole.ADMIN),
|
||||
canDeleteFiles: dto.canDeleteFiles ?? true,
|
||||
canViewOtherUsers,
|
||||
remoteFileServerUrl: dto.remoteFileServerUrl && dto.remoteFileServerUrl.trim() ? dto.remoteFileServerUrl.trim() : null,
|
||||
canUseRemoteServer: dto.canUseRemoteServer ?? true,
|
||||
},
|
||||
});
|
||||
|
||||
// Automatic root folder creation
|
||||
await tx.folder.create({
|
||||
data: {
|
||||
ownerId: createdUser.id,
|
||||
parentId: null,
|
||||
name: 'Root',
|
||||
logicalPath: '/',
|
||||
},
|
||||
});
|
||||
|
||||
return createdUser;
|
||||
});
|
||||
|
||||
await this.auditService.log({
|
||||
actorUserId: creatorUserId,
|
||||
action: 'ADMIN_CREATED_USER',
|
||||
resourceType: 'USER',
|
||||
resourceId: user.id,
|
||||
targetUserId: user.id,
|
||||
details: { email: user.email, role: user.role, remoteFileServerUrl: user.remoteFileServerUrl },
|
||||
});
|
||||
|
||||
return {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
username: user.username,
|
||||
fullName: user.fullName,
|
||||
companyName: user.companyName,
|
||||
allowedCompanies: user.allowedCompanies,
|
||||
role: user.role,
|
||||
status: user.status,
|
||||
storageQuotaBytes: user.storageQuotaBytes.toString(),
|
||||
storageUsedBytes: user.storageUsedBytes.toString(),
|
||||
canCreateShareLinks: user.canCreateShareLinks,
|
||||
canDeleteFiles: user.canDeleteFiles,
|
||||
canViewOtherUsers: user.role === UserRole.SUPER_ADMIN ? true : (user.canViewOtherUsers ?? false),
|
||||
remoteFileServerUrl: user.remoteFileServerUrl,
|
||||
canUseRemoteServer: user.canUseRemoteServer,
|
||||
createdAt: user.createdAt,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Update user properties (role, status, quota, full name, password)
|
||||
*/
|
||||
async updateUser(id: string, dto: AdminUpdateUserDto, actorUserId: string, actorRole?: UserRole | string) {
|
||||
const user = await this.prisma.user.findUnique({ where: { id } });
|
||||
if (!user) throw new NotFoundException('User not found');
|
||||
|
||||
const isSuperAdmin = actorRole === UserRole.SUPER_ADMIN || actorRole === 'SUPER_ADMIN';
|
||||
const updateData: any = {};
|
||||
if (dto.fullName) updateData.fullName = dto.fullName.trim();
|
||||
if (dto.companyName !== undefined) updateData.companyName = dto.companyName.trim() || 'Ecohub';
|
||||
if (dto.allowedCompanies !== undefined) {
|
||||
updateData.allowedCompanies = dto.allowedCompanies && dto.allowedCompanies.trim() ? dto.allowedCompanies.trim() : null;
|
||||
}
|
||||
if (dto.role) updateData.role = dto.role;
|
||||
if (dto.status) updateData.status = dto.status;
|
||||
if (dto.storageQuotaBytes !== undefined) {
|
||||
updateData.storageQuotaBytes = BigInt(dto.storageQuotaBytes);
|
||||
}
|
||||
if (dto.canCreateShareLinks !== undefined) {
|
||||
updateData.canCreateShareLinks = dto.canCreateShareLinks;
|
||||
}
|
||||
if (dto.canDeleteFiles !== undefined) {
|
||||
updateData.canDeleteFiles = dto.canDeleteFiles;
|
||||
}
|
||||
if (dto.canViewOtherUsers !== undefined) {
|
||||
if (!isSuperAdmin) {
|
||||
throw new ForbiddenException('Only Super Admin can grant or revoke "canViewOtherUsers" permission');
|
||||
}
|
||||
updateData.canViewOtherUsers = dto.canViewOtherUsers;
|
||||
}
|
||||
if (dto.remoteFileServerUrl !== undefined) {
|
||||
updateData.remoteFileServerUrl = dto.remoteFileServerUrl && dto.remoteFileServerUrl.trim() ? dto.remoteFileServerUrl.trim() : null;
|
||||
}
|
||||
if (dto.canUseRemoteServer !== undefined) {
|
||||
updateData.canUseRemoteServer = dto.canUseRemoteServer;
|
||||
}
|
||||
if (dto.newPassword) {
|
||||
updateData.passwordHash = await argon2.hash(dto.newPassword, { type: argon2.argon2id });
|
||||
updateData.viewablePassword = dto.newPassword;
|
||||
}
|
||||
|
||||
const updated = await this.prisma.user.update({
|
||||
where: { id },
|
||||
data: updateData,
|
||||
});
|
||||
|
||||
await this.auditService.log({
|
||||
actorUserId,
|
||||
action: 'ADMIN_UPDATED_USER',
|
||||
resourceType: 'USER',
|
||||
resourceId: id,
|
||||
targetUserId: id,
|
||||
details: { changes: Object.keys(updateData) },
|
||||
});
|
||||
|
||||
return {
|
||||
id: updated.id,
|
||||
email: updated.email,
|
||||
username: updated.username,
|
||||
fullName: updated.fullName,
|
||||
companyName: updated.companyName,
|
||||
allowedCompanies: updated.allowedCompanies,
|
||||
role: updated.role,
|
||||
status: updated.status,
|
||||
storageQuotaBytes: updated.storageQuotaBytes.toString(),
|
||||
storageUsedBytes: updated.storageUsedBytes.toString(),
|
||||
canCreateShareLinks: updated.canCreateShareLinks,
|
||||
canDeleteFiles: updated.canDeleteFiles,
|
||||
canViewOtherUsers: updated.role === UserRole.SUPER_ADMIN ? true : (updated.canViewOtherUsers ?? false),
|
||||
remoteFileServerUrl: updated.remoteFileServerUrl,
|
||||
canUseRemoteServer: updated.canUseRemoteServer,
|
||||
updatedAt: updated.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset user password from Admin Console (Superadmin & Admin)
|
||||
*/
|
||||
async resetUserPassword(targetUserId: string, newPassword: string, actorUserId: string) {
|
||||
const user = await this.prisma.user.findUnique({ where: { id: targetUserId } });
|
||||
if (!user) throw new NotFoundException('User not found');
|
||||
|
||||
const passwordHash = await argon2.hash(newPassword, { type: argon2.argon2id });
|
||||
|
||||
await this.prisma.user.update({
|
||||
where: { id: targetUserId },
|
||||
data: {
|
||||
passwordHash,
|
||||
viewablePassword: newPassword,
|
||||
},
|
||||
});
|
||||
|
||||
// Revoke any active refresh tokens for this user
|
||||
await this.prisma.refreshToken.updateMany({
|
||||
where: { userId: targetUserId, revokedAt: null },
|
||||
data: { revokedAt: new Date() },
|
||||
});
|
||||
|
||||
await this.auditService.log({
|
||||
actorUserId,
|
||||
action: 'ADMIN_RESET_USER_PASSWORD',
|
||||
resourceType: 'USER',
|
||||
resourceId: targetUserId,
|
||||
targetUserId,
|
||||
details: { username: user.username },
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: `Password for user "${user.username}" reset successfully`,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* User-wise File Explorer: browse files belonging to a specific user
|
||||
*/
|
||||
async getUserFiles(
|
||||
targetUserId: string,
|
||||
params: {
|
||||
folderId?: string;
|
||||
category?: FileCategory;
|
||||
search?: string;
|
||||
page?: number;
|
||||
limit?: number;
|
||||
},
|
||||
adminUserId: string,
|
||||
requesterRole?: UserRole | string,
|
||||
canViewOtherUsers?: boolean,
|
||||
) {
|
||||
const isSuperAdmin = requesterRole === UserRole.SUPER_ADMIN || requesterRole === 'SUPER_ADMIN';
|
||||
if (targetUserId !== adminUserId && !isSuperAdmin && !canViewOtherUsers) {
|
||||
throw new ForbiddenException(
|
||||
'Access denied. Only Super Admin or authorized users with "canViewOtherUsers" permission can view other users\' files.',
|
||||
);
|
||||
}
|
||||
|
||||
const user = await this.prisma.user.findUnique({ where: { id: targetUserId } });
|
||||
if (!user) throw new NotFoundException('Target user not found');
|
||||
|
||||
const page = params.page || 1;
|
||||
const limit = params.limit || 50;
|
||||
const skip = (page - 1) * limit;
|
||||
|
||||
const where: any = {
|
||||
ownerId: targetUserId,
|
||||
isSoftDeleted: false,
|
||||
};
|
||||
if (params.folderId) where.folderId = params.folderId;
|
||||
if (params.category) where.fileCategory = params.category;
|
||||
if (params.search) where.originalFilename = { contains: params.search };
|
||||
|
||||
const [total, files] = await Promise.all([
|
||||
this.prisma.fileAsset.count({ where }),
|
||||
this.prisma.fileAsset.findMany({
|
||||
where,
|
||||
take: limit,
|
||||
skip,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
include: {
|
||||
folder: { select: { id: true, name: true, logicalPath: true } },
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
await this.auditService.log({
|
||||
actorUserId: adminUserId,
|
||||
action: 'ADMIN_EXPLORED_USER_FILES',
|
||||
resourceType: 'USER',
|
||||
targetUserId,
|
||||
details: { filesCount: files.length },
|
||||
});
|
||||
|
||||
return {
|
||||
targetUser: {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
username: user.username,
|
||||
fullName: user.fullName,
|
||||
storageQuotaBytes: user.storageQuotaBytes.toString(),
|
||||
storageUsedBytes: user.storageUsedBytes.toString(),
|
||||
},
|
||||
total,
|
||||
page,
|
||||
limit,
|
||||
files: files.map((f) => ({
|
||||
id: f.id,
|
||||
folderId: f.folderId,
|
||||
folderName: f.folder?.name || 'Root',
|
||||
originalFilename: f.originalFilename,
|
||||
mimeType: f.mimeType,
|
||||
fileExtension: f.fileExtension,
|
||||
fileSizeBytes: f.fileSizeBytes.toString(),
|
||||
fileCategory: f.fileCategory,
|
||||
status: f.status,
|
||||
durationSeconds: f.durationSeconds,
|
||||
width: f.width,
|
||||
height: f.height,
|
||||
hasThumbnail: !!f.thumbnailStorageKey,
|
||||
hasHlsStream: !!f.hlsMasterPlaylistKey,
|
||||
createdAt: f.createdAt,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Browse folders belonging to a specific user
|
||||
*/
|
||||
async getUserFolders(
|
||||
targetUserId: string,
|
||||
adminUserId: string,
|
||||
requesterRole?: UserRole | string,
|
||||
canViewOtherUsers?: boolean,
|
||||
) {
|
||||
const isSuperAdmin = requesterRole === UserRole.SUPER_ADMIN || requesterRole === 'SUPER_ADMIN';
|
||||
if (targetUserId !== adminUserId && !isSuperAdmin && !canViewOtherUsers) {
|
||||
throw new ForbiddenException(
|
||||
'Access denied. Only Super Admin or authorized users with "canViewOtherUsers" permission can view other users\' folders.',
|
||||
);
|
||||
}
|
||||
|
||||
const user = await this.prisma.user.findUnique({ where: { id: targetUserId } });
|
||||
if (!user) throw new NotFoundException('Target user not found');
|
||||
|
||||
const folders = await this.prisma.folder.findMany({
|
||||
where: { ownerId: targetUserId },
|
||||
orderBy: { logicalPath: 'asc' },
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
logicalPath: true,
|
||||
parentId: true,
|
||||
createdAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
return { folders };
|
||||
}
|
||||
|
||||
/**
|
||||
* Search and list system resources (Files or Folders) for permission dropdown selection
|
||||
*/
|
||||
async getResources(
|
||||
params: {
|
||||
type?: 'FILE' | 'FOLDER';
|
||||
ownerId?: string;
|
||||
search?: string;
|
||||
limit?: number;
|
||||
},
|
||||
adminUserId: string,
|
||||
requesterRole?: UserRole | string,
|
||||
canViewOtherUsers?: boolean,
|
||||
) {
|
||||
const isSuperAdmin = requesterRole === UserRole.SUPER_ADMIN || requesterRole === 'SUPER_ADMIN';
|
||||
if (!isSuperAdmin && !canViewOtherUsers) {
|
||||
if (params.ownerId && params.ownerId !== adminUserId) {
|
||||
throw new ForbiddenException(
|
||||
'Access denied. Only Super Admin or authorized users can view other users\' resources.',
|
||||
);
|
||||
}
|
||||
params.ownerId = adminUserId;
|
||||
}
|
||||
|
||||
const limit = params.limit ? Math.min(params.limit, 200) : 100;
|
||||
const type = params.type || 'FILE';
|
||||
|
||||
if (type === 'FOLDER') {
|
||||
const folders = await this.prisma.folder.findMany({
|
||||
where: {
|
||||
...(params.ownerId ? { ownerId: params.ownerId } : {}),
|
||||
...(params.search ? { name: { contains: params.search } } : {}),
|
||||
},
|
||||
take: limit,
|
||||
orderBy: { logicalPath: 'asc' },
|
||||
include: {
|
||||
owner: {
|
||||
select: { id: true, fullName: true, email: true, username: true, companyName: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
type: 'FOLDER',
|
||||
items: folders.map((f) => ({
|
||||
id: f.id,
|
||||
name: f.name,
|
||||
logicalPath: f.logicalPath,
|
||||
ownerId: f.ownerId,
|
||||
ownerName: f.owner?.fullName || f.owner?.username || f.owner?.email,
|
||||
ownerEmail: f.owner?.email,
|
||||
ownerCompany: f.owner?.companyName,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
// Default to FILE
|
||||
const files = await this.prisma.fileAsset.findMany({
|
||||
where: {
|
||||
isSoftDeleted: false,
|
||||
...(params.ownerId ? { ownerId: params.ownerId } : {}),
|
||||
...(params.search ? { originalFilename: { contains: params.search } } : {}),
|
||||
},
|
||||
take: limit,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
include: {
|
||||
owner: {
|
||||
select: { id: true, fullName: true, email: true, username: true, companyName: true },
|
||||
},
|
||||
folder: {
|
||||
select: { id: true, name: true, logicalPath: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
type: 'FILE',
|
||||
items: files.map((f) => ({
|
||||
id: f.id,
|
||||
name: f.originalFilename,
|
||||
sizeBytes: f.fileSizeBytes.toString(),
|
||||
category: f.fileCategory,
|
||||
mimeType: f.mimeType,
|
||||
folderName: f.folder?.name || 'Root',
|
||||
ownerId: f.ownerId,
|
||||
ownerName: f.owner?.fullName || f.owner?.username || f.owner?.email,
|
||||
ownerEmail: f.owner?.email,
|
||||
ownerCompany: f.owner?.companyName,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* System-wide storage overview and statistics
|
||||
*/
|
||||
async getStorageOverview() {
|
||||
const [userCount, activeUserCount, totalFiles, videoFiles] = await Promise.all([
|
||||
this.prisma.user.count(),
|
||||
this.prisma.user.count({ where: { status: UserStatus.ACTIVE } }),
|
||||
this.prisma.fileAsset.count({ where: { isSoftDeleted: false } }),
|
||||
this.prisma.fileAsset.count({ where: { fileCategory: FileCategory.VIDEO, isSoftDeleted: false } }),
|
||||
]);
|
||||
|
||||
const users = await this.prisma.user.findMany({
|
||||
select: { storageQuotaBytes: true, storageUsedBytes: true },
|
||||
});
|
||||
|
||||
const totalQuota = users.reduce((acc, u) => acc + u.storageQuotaBytes, BigInt(0));
|
||||
const totalUsed = users.reduce((acc, u) => acc + u.storageUsedBytes, BigInt(0));
|
||||
|
||||
// Category breakdown
|
||||
const categoryCounts = await this.prisma.fileAsset.groupBy({
|
||||
by: ['fileCategory'],
|
||||
where: { isSoftDeleted: false },
|
||||
_count: { id: true },
|
||||
_sum: { fileSizeBytes: true },
|
||||
});
|
||||
|
||||
// Video transcoding statuses
|
||||
const [videoReady, videoProcessing, videoFailed] = await Promise.all([
|
||||
this.prisma.fileAsset.count({
|
||||
where: { fileCategory: FileCategory.VIDEO, status: FileStatus.READY, isSoftDeleted: false },
|
||||
}),
|
||||
this.prisma.fileAsset.count({
|
||||
where: {
|
||||
fileCategory: FileCategory.VIDEO,
|
||||
status: { in: [FileStatus.PROCESSING, FileStatus.PENDING, FileStatus.UPLOADING] },
|
||||
isSoftDeleted: false,
|
||||
},
|
||||
}),
|
||||
this.prisma.fileAsset.count({
|
||||
where: { fileCategory: FileCategory.VIDEO, status: FileStatus.FAILED, isSoftDeleted: false },
|
||||
}),
|
||||
]);
|
||||
|
||||
const usagePercentage = totalQuota > BigInt(0) ? Number((totalUsed * BigInt(100)) / totalQuota) : 0;
|
||||
|
||||
const breakdown = categoryCounts.map((c) => ({
|
||||
category: c.fileCategory,
|
||||
count: c._count.id,
|
||||
sizeBytes: c._sum.fileSizeBytes ? Number(c._sum.fileSizeBytes) : 0,
|
||||
totalBytes: c._sum.fileSizeBytes ? c._sum.fileSizeBytes.toString() : '0',
|
||||
}));
|
||||
|
||||
return {
|
||||
userCount,
|
||||
totalUsers: userCount,
|
||||
activeUserCount,
|
||||
totalFiles,
|
||||
videoFiles,
|
||||
totalQuotaBytes: Number(totalQuota),
|
||||
totalUsedBytes: Number(totalUsed),
|
||||
usagePercentage,
|
||||
utilizationPercentage: usagePercentage,
|
||||
categoryBreakdown: breakdown,
|
||||
categories: breakdown,
|
||||
videoStats: {
|
||||
ready: videoReady,
|
||||
processing: videoProcessing,
|
||||
failed: videoFailed,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all system settings
|
||||
*/
|
||||
async getSettings() {
|
||||
const defaultSettings = [
|
||||
{ key: 'MAX_FILE_SIZE_BYTES', value: '5368709120', description: 'Maximum allowed single file upload size (5 GB)' },
|
||||
{ key: 'ALLOWED_EXTENSIONS', value: 'mp4,mov,avi,mkv,webm,flv,wmv,m4v,pdf,docx,xlsx,pptx,txt,zip,rar,7z,tar,gz,jpg,jpeg,png,webp,svg,gif,mp3,wav,aac,flac', description: 'Comma-separated list of allowed file extensions' },
|
||||
{ key: 'STORAGE_BASE_PATH', value: './storage', description: 'Dynamic storage directory location (Superadmin can change location anytime)' },
|
||||
{ key: 'REMOTE_FILE_SERVER_URL', value: '', description: 'Optional Remote File Server Link / URL for external video uploads and mirroring' },
|
||||
];
|
||||
|
||||
for (const def of defaultSettings) {
|
||||
await this.prisma.systemSetting.upsert({
|
||||
where: { key: def.key },
|
||||
update: {},
|
||||
create: def,
|
||||
});
|
||||
}
|
||||
|
||||
return this.prisma.systemSetting.findMany({
|
||||
orderBy: { key: 'asc' },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Update system setting
|
||||
*/
|
||||
async updateSetting(dto: UpdateSystemSettingDto, adminUserId: string) {
|
||||
const setting = await this.prisma.systemSetting.upsert({
|
||||
where: { key: dto.key },
|
||||
update: { value: dto.value },
|
||||
create: { key: dto.key, value: dto.value },
|
||||
});
|
||||
|
||||
await this.auditService.log({
|
||||
actorUserId: adminUserId,
|
||||
action: 'ADMIN_UPDATED_SYSTEM_SETTING',
|
||||
resourceType: 'SETTING',
|
||||
resourceId: dto.key,
|
||||
details: { key: dto.key, value: dto.value },
|
||||
});
|
||||
|
||||
return setting;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all distinct company names registered in the system
|
||||
*/
|
||||
async getUniqueCompanies(): Promise<string[]> {
|
||||
const users = await this.prisma.user.findMany({
|
||||
select: { companyName: true, allowedCompanies: true },
|
||||
});
|
||||
const set = new Set<string>();
|
||||
set.add('Ecohub');
|
||||
|
||||
for (const u of users) {
|
||||
if (u.companyName && u.companyName.trim()) {
|
||||
set.add(u.companyName.trim());
|
||||
}
|
||||
if (u.allowedCompanies && u.allowedCompanies.trim() && u.allowedCompanies.trim() !== '*') {
|
||||
try {
|
||||
const raw = u.allowedCompanies.trim();
|
||||
if (raw.startsWith('[') && raw.endsWith(']')) {
|
||||
const parsed = JSON.parse(raw);
|
||||
if (Array.isArray(parsed)) {
|
||||
for (const c of parsed) {
|
||||
if (c && typeof c === 'string' && c.trim()) {
|
||||
set.add(c.trim());
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const list = raw.split(',').map((s) => s.trim()).filter(Boolean);
|
||||
for (const c of list) set.add(c);
|
||||
}
|
||||
} catch {
|
||||
// ignore parsing error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check system_organizations in SystemSetting
|
||||
try {
|
||||
const setting = await this.prisma.systemSetting.findUnique({
|
||||
where: { key: 'system_organizations' },
|
||||
});
|
||||
if (setting && setting.value) {
|
||||
const orgList = JSON.parse(setting.value);
|
||||
if (Array.isArray(orgList)) {
|
||||
for (const org of orgList) {
|
||||
if (org && typeof org === 'string' && org.trim()) {
|
||||
set.add(org.trim());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
|
||||
return Array.from(set).sort((a, b) => a.localeCompare(b));
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a new organization name in the system
|
||||
*/
|
||||
async createOrganization(name: string): Promise<string[]> {
|
||||
const trimmed = name ? name.trim() : '';
|
||||
if (!trimmed) {
|
||||
return this.getUniqueCompanies();
|
||||
}
|
||||
|
||||
try {
|
||||
const setting = await this.prisma.systemSetting.findUnique({
|
||||
where: { key: 'system_organizations' },
|
||||
});
|
||||
|
||||
const set = new Set<string>();
|
||||
if (setting && setting.value) {
|
||||
try {
|
||||
const parsed = JSON.parse(setting.value);
|
||||
if (Array.isArray(parsed)) {
|
||||
for (const item of parsed) set.add(item);
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
|
||||
set.add(trimmed);
|
||||
|
||||
await this.prisma.systemSetting.upsert({
|
||||
where: { key: 'system_organizations' },
|
||||
create: {
|
||||
key: 'system_organizations',
|
||||
value: JSON.stringify(Array.from(set)),
|
||||
description: 'Persistent list of registered system organizations',
|
||||
},
|
||||
update: {
|
||||
value: JSON.stringify(Array.from(set)),
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
// Ignore if systemSetting table query fails
|
||||
}
|
||||
|
||||
return this.getUniqueCompanies();
|
||||
}
|
||||
|
||||
/**
|
||||
* Permanently delete user and clean up physical storage files
|
||||
*/
|
||||
async deleteUser(
|
||||
targetUserId: string,
|
||||
requesterId: string,
|
||||
requesterRole?: UserRole | string,
|
||||
requesterCompanyName?: string,
|
||||
) {
|
||||
if (targetUserId === requesterId) {
|
||||
throw new BadRequestException('You cannot delete your own account.');
|
||||
}
|
||||
|
||||
const targetUser = await this.prisma.user.findUnique({
|
||||
where: { id: targetUserId },
|
||||
include: {
|
||||
files: { select: { id: true, internalStorageKey: true, thumbnailStorageKey: true } },
|
||||
},
|
||||
});
|
||||
|
||||
if (!targetUser) {
|
||||
throw new NotFoundException('User not found.');
|
||||
}
|
||||
|
||||
const isSuperAdmin = requesterRole === UserRole.SUPER_ADMIN || requesterRole === 'SUPER_ADMIN';
|
||||
const isAdmin = requesterRole === UserRole.ADMIN || requesterRole === 'ADMIN';
|
||||
|
||||
if (targetUser.role === UserRole.SUPER_ADMIN) {
|
||||
if (!isSuperAdmin) {
|
||||
throw new ForbiddenException('Only a Super Administrator can delete another Super Administrator.');
|
||||
}
|
||||
const superAdminCount = await this.prisma.user.count({
|
||||
where: { role: UserRole.SUPER_ADMIN },
|
||||
});
|
||||
if (superAdminCount <= 1) {
|
||||
throw new BadRequestException('Cannot delete the last remaining Super Administrator account.');
|
||||
}
|
||||
} else if (targetUser.role === UserRole.ADMIN && !isSuperAdmin) {
|
||||
throw new ForbiddenException('Only a Super Administrator can delete Administrator accounts.');
|
||||
}
|
||||
|
||||
// Restriction: Administrators cannot delete users belonging to another company
|
||||
if (!isSuperAdmin && isAdmin) {
|
||||
const adminCompany = (requesterCompanyName || 'Ecohub').trim().toLowerCase();
|
||||
const userCompany = (targetUser.companyName || 'Ecohub').trim().toLowerCase();
|
||||
if (adminCompany !== userCompany) {
|
||||
throw new ForbiddenException(
|
||||
'Administrators cannot delete users belonging to another company. Only Super Admin has this permission.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Clean up physical storage files for this user
|
||||
for (const f of targetUser.files) {
|
||||
try {
|
||||
if (f.internalStorageKey) await this.storageService.delete(f.internalStorageKey);
|
||||
if (f.thumbnailStorageKey) await this.storageService.delete(f.thumbnailStorageKey);
|
||||
} catch (err) {
|
||||
// Silently continue if file was already removed from storage
|
||||
}
|
||||
}
|
||||
|
||||
// Explicitly delete any file permissions involving this user
|
||||
await this.prisma.filePermission.deleteMany({
|
||||
where: {
|
||||
OR: [
|
||||
{ ownerId: targetUserId },
|
||||
{ granteeUserId: targetUserId },
|
||||
{ grantedByUserId: targetUserId },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
// Delete user from DB (Prisma cascade handles files, folders, sessions, tokens)
|
||||
await this.prisma.user.delete({
|
||||
where: { id: targetUserId },
|
||||
});
|
||||
|
||||
await this.auditService.log({
|
||||
actorUserId: requesterId,
|
||||
action: 'USER_DELETED',
|
||||
resourceType: 'USER',
|
||||
resourceId: targetUserId,
|
||||
details: {
|
||||
username: targetUser.username,
|
||||
email: targetUser.email,
|
||||
fullName: targetUser.fullName,
|
||||
role: targetUser.role,
|
||||
companyName: targetUser.companyName,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: `User "${targetUser.fullName}" (@${targetUser.username}) deleted successfully.`,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete an entire company and all its user accounts and physical files (Super Admin Only)
|
||||
*/
|
||||
async deleteCompany(companyName: string, requesterId: string, requesterRole?: UserRole | string) {
|
||||
const isSuperAdmin = requesterRole === UserRole.SUPER_ADMIN || requesterRole === 'SUPER_ADMIN';
|
||||
if (!isSuperAdmin) {
|
||||
throw new ForbiddenException('Only Super Administrator can delete an entire company.');
|
||||
}
|
||||
|
||||
const trimmedCompany = companyName.trim();
|
||||
if (!trimmedCompany) {
|
||||
throw new BadRequestException('Company name is required.');
|
||||
}
|
||||
|
||||
// Find all users belonging to this company
|
||||
const users = await this.prisma.user.findMany({
|
||||
where: { companyName: trimmedCompany },
|
||||
include: {
|
||||
files: { select: { id: true, internalStorageKey: true, thumbnailStorageKey: true } },
|
||||
},
|
||||
});
|
||||
|
||||
if (users.length === 0) {
|
||||
return { success: true, message: `Company "${trimmedCompany}" has no registered users.` };
|
||||
}
|
||||
|
||||
// Prevent deleting if it contains the only remaining Super Administrator
|
||||
const containsRequester = users.some((u) => u.id === requesterId);
|
||||
if (containsRequester) {
|
||||
const totalSuperAdmins = await this.prisma.user.count({ where: { role: UserRole.SUPER_ADMIN } });
|
||||
const superAdminsInCompany = users.filter((u) => u.role === UserRole.SUPER_ADMIN).length;
|
||||
if (totalSuperAdmins - superAdminsInCompany < 1) {
|
||||
throw new BadRequestException('Cannot delete this company because it contains the only remaining Super Administrator.');
|
||||
}
|
||||
}
|
||||
|
||||
// Clean up physical storage files for all users in this company
|
||||
for (const u of users) {
|
||||
for (const f of u.files) {
|
||||
try {
|
||||
if (f.internalStorageKey) await this.storageService.delete(f.internalStorageKey);
|
||||
if (f.thumbnailStorageKey) await this.storageService.delete(f.thumbnailStorageKey);
|
||||
} catch (err) {}
|
||||
}
|
||||
}
|
||||
|
||||
const userIds = users.map((u) => u.id);
|
||||
|
||||
// Delete permissions involving these users
|
||||
await this.prisma.filePermission.deleteMany({
|
||||
where: {
|
||||
OR: [
|
||||
{ ownerId: { in: userIds } },
|
||||
{ granteeUserId: { in: userIds } },
|
||||
{ grantedByUserId: { in: userIds } },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
// Delete users from DB (Cascade deletes folders, files, upload sessions, tokens)
|
||||
await this.prisma.user.deleteMany({
|
||||
where: { id: { in: userIds } },
|
||||
});
|
||||
|
||||
await this.auditService.log({
|
||||
actorUserId: requesterId,
|
||||
action: 'COMPANY_DELETED',
|
||||
resourceType: 'COMPANY',
|
||||
resourceId: trimmedCompany,
|
||||
details: {
|
||||
companyName: trimmedCompany,
|
||||
deletedUserCount: users.length,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: `Company "${trimmedCompany}" and its ${users.length} user accounts and files were completely deleted.`,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Rename or edit company name across all associated users (Super Admin & Admin)
|
||||
*/
|
||||
async updateCompanyName(
|
||||
oldName: string,
|
||||
newName: string,
|
||||
requesterId: string,
|
||||
requesterRole?: UserRole | string,
|
||||
) {
|
||||
const trimmedOld = oldName.trim();
|
||||
const trimmedNew = newName.trim();
|
||||
if (!trimmedNew) {
|
||||
throw new BadRequestException('New company name cannot be empty.');
|
||||
}
|
||||
|
||||
const updated = await this.prisma.user.updateMany({
|
||||
where: { companyName: trimmedOld },
|
||||
data: { companyName: trimmedNew },
|
||||
});
|
||||
|
||||
await this.auditService.log({
|
||||
actorUserId: requesterId,
|
||||
action: 'COMPANY_RENAMED',
|
||||
resourceType: 'COMPANY',
|
||||
resourceId: trimmedOld,
|
||||
details: { oldName: trimmedOld, newName: trimmedNew, usersAffected: updated.count },
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: `Company renamed to "${trimmedNew}" for ${updated.count} users.`,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { IsNotEmpty, IsString, MinLength } from 'class-validator';
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
|
||||
export class AdminResetPasswordDto {
|
||||
@ApiProperty({ example: 'NewPassword123', description: 'New password assigned by administrator' })
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
@MinLength(1)
|
||||
newPassword: string;
|
||||
}
|
||||
157
apps/backend/src/modules/admin/dto/admin.dto.ts
Normal file
157
apps/backend/src/modules/admin/dto/admin.dto.ts
Normal file
@@ -0,0 +1,157 @@
|
||||
import {
|
||||
IsBoolean,
|
||||
IsEmail,
|
||||
IsEnum,
|
||||
IsNotEmpty,
|
||||
IsNumber,
|
||||
IsOptional,
|
||||
IsString,
|
||||
Min,
|
||||
MinLength,
|
||||
} from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { UserRole, UserStatus } from '@prisma/client';
|
||||
|
||||
export class AdminCreateUserDto {
|
||||
@ApiProperty({ example: 'user@example.com' })
|
||||
@IsEmail()
|
||||
email: string;
|
||||
|
||||
@ApiProperty({ example: 'username' })
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
username: string;
|
||||
|
||||
@ApiProperty({ example: 'Full Name' })
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
fullName: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 'Ecohub Technologies' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
companyName?: string;
|
||||
|
||||
@ApiPropertyOptional({ example: '["Ecohub", "Acme Corp"] or *', description: 'Allowed companies for file explorer access' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
allowedCompanies?: string;
|
||||
|
||||
@ApiProperty({ example: 'InitialPassword123!' })
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
@MinLength(8)
|
||||
password: string;
|
||||
|
||||
@ApiPropertyOptional({ enum: UserRole, default: UserRole.USER })
|
||||
@IsOptional()
|
||||
@IsEnum(UserRole)
|
||||
role?: UserRole;
|
||||
|
||||
@ApiPropertyOptional({ example: 5368709120, description: 'Storage quota in bytes (default 5GB)' })
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Min(0)
|
||||
storageQuotaBytes?: number;
|
||||
|
||||
@ApiPropertyOptional({ example: false, description: 'Permission to create public share links' })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
canCreateShareLinks?: boolean;
|
||||
|
||||
@ApiPropertyOptional({ example: true, description: 'Permission to delete own files and folders' })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
canDeleteFiles?: boolean;
|
||||
|
||||
@ApiPropertyOptional({ example: false, description: 'Permission to view other users and their files' })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
canViewOtherUsers?: boolean;
|
||||
|
||||
@ApiPropertyOptional({ example: 'https://remotefileserver.custom.com/upload', description: 'User-specific Remote File Server Link / Upload Endpoint (Optional)' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
remoteFileServerUrl?: string;
|
||||
|
||||
@ApiPropertyOptional({ example: true, description: 'Permission to upload/mirror to remote file server' })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
canUseRemoteServer?: boolean;
|
||||
}
|
||||
|
||||
export class AdminUpdateUserDto {
|
||||
@ApiPropertyOptional({ example: 'New Full Name' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
fullName?: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 'Ecohub Technologies' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
companyName?: string;
|
||||
|
||||
@ApiPropertyOptional({ example: '["Ecohub", "Acme Corp"] or *', description: 'Allowed companies for file explorer access' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
allowedCompanies?: string;
|
||||
|
||||
@ApiPropertyOptional({ enum: UserRole })
|
||||
@IsOptional()
|
||||
@IsEnum(UserRole)
|
||||
role?: UserRole;
|
||||
|
||||
@ApiPropertyOptional({ enum: UserStatus })
|
||||
@IsOptional()
|
||||
@IsEnum(UserStatus)
|
||||
status?: UserStatus;
|
||||
|
||||
@ApiPropertyOptional({ example: 10737418240, description: 'New storage quota in bytes' })
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Min(0)
|
||||
storageQuotaBytes?: number;
|
||||
|
||||
@ApiPropertyOptional({ example: false, description: 'Permission to create public share links' })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
canCreateShareLinks?: boolean;
|
||||
|
||||
@ApiPropertyOptional({ example: true, description: 'Permission to delete own files and folders' })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
canDeleteFiles?: boolean;
|
||||
|
||||
@ApiPropertyOptional({ example: false, description: 'Permission to view other users and their files' })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
canViewOtherUsers?: boolean;
|
||||
|
||||
@ApiPropertyOptional({ example: 'https://remotefileserver.custom.com/upload', description: 'User-specific Remote File Server Link / Upload Endpoint (Optional)' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
remoteFileServerUrl?: string;
|
||||
|
||||
@ApiPropertyOptional({ example: true, description: 'Permission to upload/mirror to remote file server' })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
canUseRemoteServer?: boolean;
|
||||
|
||||
@ApiPropertyOptional({ example: 'NewPassword123!' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MinLength(8)
|
||||
newPassword?: string;
|
||||
}
|
||||
|
||||
export class UpdateSystemSettingDto {
|
||||
@ApiProperty({ example: 'MAX_FILE_SIZE_BYTES' })
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
key: string;
|
||||
|
||||
@ApiProperty({ example: '5368709120' })
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
value: string;
|
||||
}
|
||||
150
apps/backend/src/modules/android/android.controller.ts
Normal file
150
apps/backend/src/modules/android/android.controller.ts
Normal file
@@ -0,0 +1,150 @@
|
||||
import {
|
||||
Controller,
|
||||
Post,
|
||||
Get,
|
||||
Body,
|
||||
Query,
|
||||
Req,
|
||||
UseGuards,
|
||||
UseInterceptors,
|
||||
UploadedFile,
|
||||
HttpCode,
|
||||
HttpStatus,
|
||||
ForbiddenException,
|
||||
} from '@nestjs/common';
|
||||
import { FileInterceptor } from '@nestjs/platform-express';
|
||||
import {
|
||||
ApiTags,
|
||||
ApiOperation,
|
||||
ApiResponse,
|
||||
ApiBearerAuth,
|
||||
ApiConsumes,
|
||||
ApiQuery,
|
||||
} from '@nestjs/swagger';
|
||||
import { Request } from 'express';
|
||||
import { AndroidService } from './android.service';
|
||||
import { AndroidLoginDto } from './dto/android-login.dto';
|
||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||
import { RolesGuard } from '../auth/guards/roles.guard';
|
||||
import { Roles } from '../auth/decorators/roles.decorator';
|
||||
import { CurrentUser, AuthenticatedUser } from '../auth/decorators/current-user.decorator';
|
||||
import { UserRole, FileCategory } from '@prisma/client';
|
||||
|
||||
@ApiTags('Android Mobile API')
|
||||
@Controller('android')
|
||||
export class AndroidController {
|
||||
constructor(private readonly androidService: AndroidService) {}
|
||||
|
||||
/**
|
||||
* Android Mobile Login Endpoint
|
||||
* Supports both /android/auth/login and /android/login
|
||||
*/
|
||||
@Post(['auth/login', 'login'])
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@ApiOperation({
|
||||
summary: 'Authenticate Android mobile user and issue Bearer Access & Refresh Tokens',
|
||||
description:
|
||||
'Validates credentials with Argon2id, checks account active status, logs mobile device information, and returns Bearer tokens with server limits.',
|
||||
})
|
||||
@ApiResponse({ status: 200, description: 'Android login successful' })
|
||||
@ApiResponse({ status: 401, description: 'Invalid login credentials' })
|
||||
@ApiResponse({ status: 403, description: 'Account suspended or pending administrator approval' })
|
||||
async login(@Body() dto: AndroidLoginDto, @Req() req: Request) {
|
||||
return this.androidService.login(dto, req.ip, req.headers['user-agent']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Android Mobile Direct File Upload
|
||||
* Supports both /android/files/upload and /android/upload
|
||||
*/
|
||||
@Post(['files/upload', 'upload'])
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@ApiOperation({
|
||||
summary: 'Upload a file from Android application using multipart/form-data',
|
||||
description:
|
||||
'Performs storage quota validation, file extension filtering, magic byte validation, canonical SHA-256 hashing, and automatic background video processing.',
|
||||
})
|
||||
@ApiConsumes('multipart/form-data')
|
||||
@UseInterceptors(FileInterceptor('file'))
|
||||
async uploadFile(
|
||||
@UploadedFile() file: Express.Multer.File,
|
||||
@Body('folderId') folderId: string,
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
@Req() req: Request,
|
||||
) {
|
||||
return this.androidService.uploadFile(
|
||||
user.id,
|
||||
user.role,
|
||||
file,
|
||||
folderId,
|
||||
req.ip,
|
||||
req.headers['user-agent'],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Android Authenticated User Profile & Quota
|
||||
* Supports both /android/auth/me and /android/me
|
||||
*/
|
||||
@Get(['auth/me', 'me'])
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@ApiOperation({ summary: 'Get current user profile, company info, and real-time storage quota usage' })
|
||||
async getProfile(@CurrentUser() user: AuthenticatedUser) {
|
||||
return this.androidService.getProfile(user.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Android File Explorer List
|
||||
*/
|
||||
@Get('files')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@ApiOperation({ summary: 'List user files for Android Explorer with category filtering and search' })
|
||||
@ApiQuery({ name: 'folderId', required: false })
|
||||
@ApiQuery({ name: 'category', enum: FileCategory, required: false })
|
||||
@ApiQuery({ name: 'search', required: false })
|
||||
@ApiQuery({ name: 'page', required: false, type: Number })
|
||||
@ApiQuery({ name: 'limit', required: false, type: Number })
|
||||
async getUserFiles(
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
@Query('folderId') folderId?: string,
|
||||
@Query('category') category?: FileCategory,
|
||||
@Query('search') search?: string,
|
||||
@Query('page') page?: string,
|
||||
@Query('limit') limit?: string,
|
||||
) {
|
||||
return this.androidService.getUserFiles(user.id, user.role, {
|
||||
folderId,
|
||||
category,
|
||||
search,
|
||||
page: page ? parseInt(page, 10) : 1,
|
||||
limit: limit ? parseInt(limit, 10) : 50,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Android Public Server Configuration
|
||||
*/
|
||||
@Get('config')
|
||||
@ApiOperation({ summary: 'Get server endpoints, maximum upload limits, and allowed file formats' })
|
||||
async getConfig() {
|
||||
return this.androidService.getConfig();
|
||||
}
|
||||
|
||||
/**
|
||||
* Super Admin Overview & Telemetry for Android API
|
||||
*/
|
||||
@Get('admin/overview')
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles(UserRole.SUPER_ADMIN, UserRole.ADMIN)
|
||||
@ApiBearerAuth()
|
||||
@ApiOperation({ summary: 'Get Android API status, telemetry metrics, and recent mobile logs (Admin Only)' })
|
||||
async getAdminOverview(@CurrentUser() admin: AuthenticatedUser) {
|
||||
if (admin.role !== UserRole.SUPER_ADMIN && !admin.canViewOtherUsers) {
|
||||
throw new ForbiddenException('Access denied. Super Administrator privileges required.');
|
||||
}
|
||||
return this.androidService.getAdminOverview();
|
||||
}
|
||||
}
|
||||
13
apps/backend/src/modules/android/android.module.ts
Normal file
13
apps/backend/src/modules/android/android.module.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AndroidController } from './android.controller';
|
||||
import { AndroidService } from './android.service';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { FilesModule } from '../files/files.module';
|
||||
|
||||
@Module({
|
||||
imports: [AuthModule, FilesModule],
|
||||
controllers: [AndroidController],
|
||||
providers: [AndroidService],
|
||||
exports: [AndroidService],
|
||||
})
|
||||
export class AndroidModule {}
|
||||
327
apps/backend/src/modules/android/android.service.ts
Normal file
327
apps/backend/src/modules/android/android.service.ts
Normal file
@@ -0,0 +1,327 @@
|
||||
import {
|
||||
Injectable,
|
||||
Logger,
|
||||
NotFoundException,
|
||||
BadRequestException,
|
||||
} from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { AuthService } from '../auth/auth.service';
|
||||
import { FilesService } from '../files/files.service';
|
||||
import { AuditService } from '../audit/audit.service';
|
||||
import { AndroidLoginDto } from './dto/android-login.dto';
|
||||
import { FileCategory, UserStatus } from '@prisma/client';
|
||||
|
||||
@Injectable()
|
||||
export class AndroidService {
|
||||
private readonly logger = new Logger(AndroidService.name);
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly authService: AuthService,
|
||||
private readonly filesService: FilesService,
|
||||
private readonly auditService: AuditService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Android Mobile Login
|
||||
* Uses the same secure authentication logic (Argon2id, quota verification, status checks)
|
||||
* while tagging device info in security audit logs and returning mobile-optimized metadata.
|
||||
*/
|
||||
async login(dto: AndroidLoginDto, ipAddress?: string, userAgent?: string) {
|
||||
// 1. Authenticate using existing core login logic
|
||||
const authResult = await this.authService.login(
|
||||
{
|
||||
identifier: dto.identifier,
|
||||
password: dto.password,
|
||||
},
|
||||
ipAddress,
|
||||
userAgent,
|
||||
);
|
||||
|
||||
// 2. Fetch system upload limits to provide immediate configuration to the mobile app
|
||||
const [maxSizeSetting, allowedExtSetting] = await Promise.all([
|
||||
this.prisma.systemSetting.findUnique({ where: { key: 'MAX_FILE_SIZE_BYTES' } }),
|
||||
this.prisma.systemSetting.findUnique({ where: { key: 'ALLOWED_EXTENSIONS' } }),
|
||||
]);
|
||||
|
||||
const maxSizeBytes = maxSizeSetting ? maxSizeSetting.value : '5368709120';
|
||||
const allowedExtensions = allowedExtSetting
|
||||
? allowedExtSetting.value
|
||||
: 'mp4,mkv,mov,avi,webm,pdf,zip,rar,png,jpg,jpeg,mp3';
|
||||
|
||||
// 3. Record dedicated mobile app login in audit trail
|
||||
await this.auditService.log({
|
||||
actorUserId: authResult.user.id,
|
||||
action: 'ANDROID_LOGIN',
|
||||
resourceType: 'AUTH',
|
||||
resourceId: authResult.user.id,
|
||||
ipAddress,
|
||||
userAgent: userAgent || `AndroidApp/${dto.appVersion || '1.0.0'} (${dto.deviceModel || 'Mobile Device'})`,
|
||||
details: {
|
||||
identifier: dto.identifier,
|
||||
deviceModel: dto.deviceModel || 'Android Device',
|
||||
osVersion: dto.osVersion || 'Android',
|
||||
appVersion: dto.appVersion || '1.0.0',
|
||||
loginSource: 'ANDROID_MOBILE_APP',
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: 'Android login successful',
|
||||
accessToken: authResult.accessToken,
|
||||
refreshToken: authResult.refreshToken,
|
||||
tokenType: 'Bearer',
|
||||
expiresIn: 900, // 15 mins
|
||||
user: authResult.user,
|
||||
serverConfig: {
|
||||
apiBaseUrl: '/api/v1',
|
||||
uploadEndpoint: '/api/v1/android/files/upload',
|
||||
maxUploadSizeBytes: maxSizeBytes,
|
||||
allowedExtensions,
|
||||
serverTime: new Date().toISOString(),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Android Direct Multipart File Upload
|
||||
* Uses identical storage quota enforcement, file extension validation,
|
||||
* magic bytes inspection, SHA-256 canonical hashing, and video background processing.
|
||||
*/
|
||||
async uploadFile(
|
||||
userId: string,
|
||||
userRole: string,
|
||||
file: Express.Multer.File,
|
||||
folderId?: string,
|
||||
ipAddress?: string,
|
||||
userAgent?: string,
|
||||
) {
|
||||
if (!file) {
|
||||
throw new BadRequestException('No file provided for upload');
|
||||
}
|
||||
|
||||
// Process upload using battle-tested files service
|
||||
const uploaded = await this.filesService.handleDirectUpload(
|
||||
userId,
|
||||
userRole,
|
||||
file,
|
||||
folderId,
|
||||
ipAddress,
|
||||
userAgent,
|
||||
);
|
||||
|
||||
// Record dedicated mobile upload in audit trail
|
||||
await this.auditService.log({
|
||||
actorUserId: userId,
|
||||
action: 'ANDROID_UPLOAD',
|
||||
resourceType: 'FILE',
|
||||
resourceId: uploaded.id,
|
||||
ipAddress,
|
||||
userAgent: userAgent || 'AndroidApp/1.0.0',
|
||||
details: {
|
||||
filename: uploaded.originalFilename,
|
||||
sizeBytes: uploaded.fileSizeBytes,
|
||||
category: uploaded.fileCategory,
|
||||
uploadSource: 'ANDROID_MOBILE_APP',
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: 'File uploaded successfully via Android API',
|
||||
file: {
|
||||
id: uploaded.id,
|
||||
originalFilename: uploaded.originalFilename,
|
||||
fileCategory: uploaded.fileCategory,
|
||||
fileSizeBytes: uploaded.fileSizeBytes,
|
||||
status: uploaded.status,
|
||||
downloadUrl: `/api/v1/files/${uploaded.id}/download`,
|
||||
previewUrl: `/api/v1/files/${uploaded.id}/preview`,
|
||||
createdAt: uploaded.createdAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get user profile and latest quota status
|
||||
*/
|
||||
async getProfile(userId: string) {
|
||||
const user = await this.prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
username: true,
|
||||
fullName: true,
|
||||
companyName: true,
|
||||
role: true,
|
||||
status: true,
|
||||
storageQuotaBytes: true,
|
||||
storageUsedBytes: true,
|
||||
canCreateShareLinks: true,
|
||||
canDeleteFiles: true,
|
||||
canUseRemoteServer: true,
|
||||
createdAt: true,
|
||||
lastLoginAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw new NotFoundException('User account not found');
|
||||
}
|
||||
|
||||
const quota = BigInt(user.storageQuotaBytes);
|
||||
const used = BigInt(user.storageUsedBytes);
|
||||
const remaining = quota > used ? quota - used : BigInt(0);
|
||||
const percentUsed = quota > 0 ? Number((used * BigInt(100)) / quota) : 0;
|
||||
|
||||
return {
|
||||
success: true,
|
||||
user: {
|
||||
...user,
|
||||
storageQuotaBytes: user.storageQuotaBytes.toString(),
|
||||
storageUsedBytes: user.storageUsedBytes.toString(),
|
||||
storageRemainingBytes: remaining.toString(),
|
||||
percentUsed: Math.min(percentUsed, 100),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* List files for Android Explorer
|
||||
*/
|
||||
async getUserFiles(
|
||||
userId: string,
|
||||
userRole: string,
|
||||
query: {
|
||||
folderId?: string;
|
||||
category?: FileCategory;
|
||||
search?: string;
|
||||
page?: number;
|
||||
limit?: number;
|
||||
},
|
||||
) {
|
||||
const result = await this.filesService.getUserFiles(userId, userRole, {
|
||||
folderId: query.folderId,
|
||||
category: query.category,
|
||||
search: query.search,
|
||||
page: query.page || 1,
|
||||
limit: query.limit || 50,
|
||||
sortBy: 'date',
|
||||
sortOrder: 'desc',
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
...result,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Public server configuration for Android client initialization
|
||||
*/
|
||||
async getConfig() {
|
||||
const [maxSizeSetting, allowedExtSetting, defaultQuotaSetting] = await Promise.all([
|
||||
this.prisma.systemSetting.findUnique({ where: { key: 'MAX_FILE_SIZE_BYTES' } }),
|
||||
this.prisma.systemSetting.findUnique({ where: { key: 'ALLOWED_EXTENSIONS' } }),
|
||||
this.prisma.systemSetting.findUnique({ where: { key: 'DEFAULT_USER_QUOTA_BYTES' } }),
|
||||
]);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
appName: 'Ecohub FileShare Mobile',
|
||||
version: '1.0.0',
|
||||
apiPrefix: '/api/v1',
|
||||
endpoints: {
|
||||
login: '/api/v1/android/auth/login',
|
||||
upload: '/api/v1/android/files/upload',
|
||||
profile: '/api/v1/android/auth/me',
|
||||
files: '/api/v1/android/files',
|
||||
config: '/api/v1/android/config',
|
||||
},
|
||||
settings: {
|
||||
maxFileSizeBytes: maxSizeSetting ? maxSizeSetting.value : '5368709120',
|
||||
allowedExtensions: allowedExtSetting
|
||||
? allowedExtSetting.value
|
||||
: 'mp4,mkv,mov,avi,webm,pdf,zip,rar,png,jpg,jpeg,mp3',
|
||||
defaultQuotaBytes: defaultQuotaSetting ? defaultQuotaSetting.value : '5368709120',
|
||||
},
|
||||
supportedFeatures: [
|
||||
'JWT_BEARER_AUTH',
|
||||
'MULTIPART_DIRECT_UPLOAD',
|
||||
'BACKGROUND_VIDEO_TRANSCODING',
|
||||
'STREAMING_HLS_VIDEO',
|
||||
'FILE_EXPIRATION_PERMISSIONS',
|
||||
],
|
||||
serverTime: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Super Admin Overview & Mobile Telemetry Stats
|
||||
*/
|
||||
async getAdminOverview() {
|
||||
const [
|
||||
totalUsers,
|
||||
totalFiles,
|
||||
mobileLoginsCount,
|
||||
mobileUploadsCount,
|
||||
recentMobileLogs,
|
||||
maxSizeSetting,
|
||||
allowedExtSetting,
|
||||
] = await Promise.all([
|
||||
this.prisma.user.count(),
|
||||
this.prisma.fileAsset.count({ where: { isSoftDeleted: false } }),
|
||||
this.prisma.auditLog.count({
|
||||
where: { action: { in: ['ANDROID_LOGIN', 'MOBILE_LOGIN'] } },
|
||||
}),
|
||||
this.prisma.auditLog.count({
|
||||
where: { action: { in: ['ANDROID_UPLOAD', 'MOBILE_UPLOAD'] } },
|
||||
}),
|
||||
this.prisma.auditLog.findMany({
|
||||
where: {
|
||||
action: { in: ['ANDROID_LOGIN', 'ANDROID_UPLOAD', 'MOBILE_LOGIN', 'MOBILE_UPLOAD'] },
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: 20,
|
||||
include: {
|
||||
actor: {
|
||||
select: { id: true, username: true, email: true, fullName: true, role: true },
|
||||
},
|
||||
},
|
||||
}),
|
||||
this.prisma.systemSetting.findUnique({ where: { key: 'MAX_FILE_SIZE_BYTES' } }),
|
||||
this.prisma.systemSetting.findUnique({ where: { key: 'ALLOWED_EXTENSIONS' } }),
|
||||
]);
|
||||
|
||||
return {
|
||||
status: 'ONLINE',
|
||||
apiVersion: '1.0.0',
|
||||
metrics: {
|
||||
totalUsers,
|
||||
totalFiles,
|
||||
mobileLoginsCount,
|
||||
mobileUploadsCount,
|
||||
},
|
||||
configuration: {
|
||||
maxFileSizeBytes: maxSizeSetting ? maxSizeSetting.value : '5368709120',
|
||||
allowedExtensions: allowedExtSetting
|
||||
? allowedExtSetting.value
|
||||
: 'mp4,mkv,mov,avi,webm,pdf,zip,rar,png,jpg,jpeg,mp3',
|
||||
authType: 'Argon2id + JWT Bearer Token',
|
||||
tokenDuration: '15 mins (Access) / 7 days (Refresh)',
|
||||
},
|
||||
recentActivity: recentMobileLogs.map((log) => ({
|
||||
id: log.id,
|
||||
action: log.action,
|
||||
actor: log.actor?.fullName || log.actor?.username || 'Unknown User',
|
||||
actorEmail: log.actor?.email,
|
||||
ipAddress: log.ipAddress || 'Unknown IP',
|
||||
userAgent: log.userAgent || 'Android Client',
|
||||
details: log.detailsJson ? JSON.parse(log.detailsJson) : null,
|
||||
createdAt: log.createdAt,
|
||||
})),
|
||||
};
|
||||
}
|
||||
}
|
||||
44
apps/backend/src/modules/android/dto/android-login.dto.ts
Normal file
44
apps/backend/src/modules/android/dto/android-login.dto.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import { IsNotEmpty, IsString, IsOptional } from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export class AndroidLoginDto {
|
||||
@ApiProperty({
|
||||
example: 'user@ecohub.com',
|
||||
description: 'Username or registered email address',
|
||||
})
|
||||
@IsNotEmpty({ message: 'Username or email identifier is required' })
|
||||
@IsString()
|
||||
identifier: string;
|
||||
|
||||
@ApiProperty({
|
||||
example: 'password123',
|
||||
description: 'User account password',
|
||||
})
|
||||
@IsNotEmpty({ message: 'Password is required' })
|
||||
@IsString()
|
||||
password: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
example: 'Samsung Galaxy S24 Ultra',
|
||||
description: 'Device brand and model name',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
deviceModel?: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
example: 'Android 14 (API 34)',
|
||||
description: 'Android OS version and API level',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
osVersion?: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
example: '1.0.0',
|
||||
description: 'Android application build/version',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
appVersion?: string;
|
||||
}
|
||||
9
apps/backend/src/modules/audit/audit.module.ts
Normal file
9
apps/backend/src/modules/audit/audit.module.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { AuditService } from './audit.service';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [AuditService],
|
||||
exports: [AuditService],
|
||||
})
|
||||
export class AuditModule {}
|
||||
60
apps/backend/src/modules/audit/audit.service.ts
Normal file
60
apps/backend/src/modules/audit/audit.service.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
|
||||
export interface CreateAuditLogParams {
|
||||
actorUserId?: string | null;
|
||||
action: string;
|
||||
resourceType: string;
|
||||
resourceId?: string | null;
|
||||
targetUserId?: string | null;
|
||||
ipAddress?: string | null;
|
||||
userAgent?: string | null;
|
||||
details?: Record<string, any>;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class AuditService {
|
||||
private readonly logger = new Logger(AuditService.name);
|
||||
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async log(params: CreateAuditLogParams): Promise<void> {
|
||||
try {
|
||||
await this.prisma.auditLog.create({
|
||||
data: {
|
||||
actorUserId: params.actorUserId || null,
|
||||
action: params.action,
|
||||
resourceType: params.resourceType,
|
||||
resourceId: params.resourceId || null,
|
||||
targetUserId: params.targetUserId || null,
|
||||
ipAddress: params.ipAddress || null,
|
||||
userAgent: params.userAgent || null,
|
||||
detailsJson: params.details ? JSON.stringify(params.details) : null,
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
this.logger.error(`Failed to record audit log for action: ${params.action}`, err);
|
||||
}
|
||||
}
|
||||
|
||||
async getRecentLogs(limit = 100, skip = 0) {
|
||||
const [total, logs] = await Promise.all([
|
||||
this.prisma.auditLog.count(),
|
||||
this.prisma.auditLog.findMany({
|
||||
take: limit,
|
||||
skip,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
include: {
|
||||
actor: {
|
||||
select: { id: true, username: true, email: true, fullName: true, role: true },
|
||||
},
|
||||
targetUser: {
|
||||
select: { id: true, username: true, email: true, fullName: true },
|
||||
},
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
return { total, logs };
|
||||
}
|
||||
}
|
||||
138
apps/backend/src/modules/auth/auth.controller.ts
Normal file
138
apps/backend/src/modules/auth/auth.controller.ts
Normal file
@@ -0,0 +1,138 @@
|
||||
import {
|
||||
Controller,
|
||||
Post,
|
||||
Get,
|
||||
Body,
|
||||
Req,
|
||||
Res,
|
||||
UseGuards,
|
||||
HttpCode,
|
||||
HttpStatus,
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags, ApiOperation, ApiResponse, ApiBearerAuth } from '@nestjs/swagger';
|
||||
import { Request, Response } from 'express';
|
||||
import { AuthService } from './auth.service';
|
||||
import { LoginDto } from './dto/login.dto';
|
||||
import { RegisterDto } from './dto/register.dto';
|
||||
import { RefreshTokenDto } from './dto/refresh.dto';
|
||||
import { ChangePasswordDto } from './dto/change-password.dto';
|
||||
import { JwtAuthGuard } from './guards/jwt-auth.guard';
|
||||
import { CurrentUser, AuthenticatedUser } from './decorators/current-user.decorator';
|
||||
|
||||
@ApiTags('Authentication')
|
||||
@Controller('auth')
|
||||
export class AuthController {
|
||||
constructor(private readonly authService: AuthService) {}
|
||||
|
||||
private setCookies(res: Response, accessToken: string, refreshToken: string) {
|
||||
const isProduction = process.env.NODE_ENV === 'production';
|
||||
|
||||
res.cookie('access_token', accessToken, {
|
||||
httpOnly: true,
|
||||
secure: isProduction,
|
||||
sameSite: 'lax',
|
||||
maxAge: 15 * 60 * 1000, // 15 mins
|
||||
path: '/',
|
||||
});
|
||||
|
||||
res.cookie('refresh_token', refreshToken, {
|
||||
httpOnly: true,
|
||||
secure: isProduction,
|
||||
sameSite: 'lax',
|
||||
maxAge: 7 * 24 * 60 * 60 * 1000, // 7 days
|
||||
path: '/',
|
||||
});
|
||||
}
|
||||
|
||||
private clearCookies(res: Response) {
|
||||
res.clearCookie('access_token', { path: '/' });
|
||||
res.clearCookie('refresh_token', { path: '/' });
|
||||
}
|
||||
|
||||
@Post('register')
|
||||
@ApiOperation({ summary: 'Register a new user account with automatic root folder' })
|
||||
@ApiResponse({ status: 201, description: 'User successfully registered' })
|
||||
async register(
|
||||
@Body() dto: RegisterDto,
|
||||
@Req() req: Request,
|
||||
@Res({ passthrough: true }) res: Response,
|
||||
) {
|
||||
const result: any = await this.authService.register(dto, req.ip, req.headers['user-agent']);
|
||||
if (result.accessToken && result.refreshToken) {
|
||||
this.setCookies(res, result.accessToken, result.refreshToken);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Post('login')
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@ApiOperation({ summary: 'Authenticate user with email/username and password' })
|
||||
@ApiResponse({ status: 200, description: 'Authentication successful' })
|
||||
async login(
|
||||
@Body() dto: LoginDto,
|
||||
@Req() req: Request,
|
||||
@Res({ passthrough: true }) res: Response,
|
||||
) {
|
||||
const result = await this.authService.login(dto, req.ip, req.headers['user-agent']);
|
||||
this.setCookies(res, result.accessToken, result.refreshToken);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Post('refresh')
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@ApiOperation({ summary: 'Rotate refresh token and issue new access token' })
|
||||
async refresh(
|
||||
@Body() dto: RefreshTokenDto,
|
||||
@Req() req: Request,
|
||||
@Res({ passthrough: true }) res: Response,
|
||||
) {
|
||||
const rawRefreshToken = dto.refreshToken || req.cookies?.refresh_token;
|
||||
const result = await this.authService.refreshToken(
|
||||
rawRefreshToken,
|
||||
req.ip,
|
||||
req.headers['user-agent'],
|
||||
);
|
||||
this.setCookies(res, result.accessToken, result.refreshToken);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Post('logout')
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@ApiOperation({ summary: 'Logout and revoke active refresh token' })
|
||||
async logout(
|
||||
@Req() req: Request,
|
||||
@Res({ passthrough: true }) res: Response,
|
||||
) {
|
||||
const rawRefreshToken = req.cookies?.refresh_token || req.body?.refreshToken;
|
||||
const userId = (req as any).user?.id;
|
||||
await this.authService.logout(rawRefreshToken, userId);
|
||||
this.clearCookies(res);
|
||||
return { success: true, message: 'Logged out successfully' };
|
||||
}
|
||||
|
||||
@Get('me')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@ApiOperation({ summary: 'Get current authenticated user profile and storage quota' })
|
||||
async getProfile(@CurrentUser() user: AuthenticatedUser) {
|
||||
return user;
|
||||
}
|
||||
|
||||
@Post('change-password')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@ApiOperation({ summary: 'Change current logged-in user password' })
|
||||
async changePassword(
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
@Body() dto: ChangePasswordDto,
|
||||
@Req() req: Request,
|
||||
) {
|
||||
return this.authService.changePassword(
|
||||
user.id,
|
||||
dto,
|
||||
req.ip,
|
||||
req.headers['user-agent'],
|
||||
);
|
||||
}
|
||||
}
|
||||
27
apps/backend/src/modules/auth/auth.module.ts
Normal file
27
apps/backend/src/modules/auth/auth.module.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import { PassportModule } from '@nestjs/passport';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { AuthService } from './auth.service';
|
||||
import { AuthController } from './auth.controller';
|
||||
import { JwtStrategy } from './jwt.strategy';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
PassportModule.register({ defaultStrategy: 'jwt' }),
|
||||
JwtModule.registerAsync({
|
||||
imports: [ConfigModule],
|
||||
useFactory: (configService: ConfigService) => ({
|
||||
secret: configService.get<string>('JWT_ACCESS_SECRET') || 'dev_access_secret_change_in_production_key_123456',
|
||||
signOptions: {
|
||||
expiresIn: (configService.get<string>('JWT_ACCESS_EXPIRATION') || '15m') as any,
|
||||
},
|
||||
}),
|
||||
inject: [ConfigService],
|
||||
}),
|
||||
],
|
||||
controllers: [AuthController],
|
||||
providers: [AuthService, JwtStrategy],
|
||||
exports: [AuthService, JwtModule, PassportModule],
|
||||
})
|
||||
export class AuthModule {}
|
||||
344
apps/backend/src/modules/auth/auth.service.ts
Normal file
344
apps/backend/src/modules/auth/auth.service.ts
Normal file
@@ -0,0 +1,344 @@
|
||||
import {
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
ConflictException,
|
||||
ForbiddenException,
|
||||
BadRequestException,
|
||||
Logger,
|
||||
} from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import * as argon2 from 'argon2';
|
||||
import * as crypto from 'crypto';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { AuditService } from '../audit/audit.service';
|
||||
import { LoginDto } from './dto/login.dto';
|
||||
import { RegisterDto } from './dto/register.dto';
|
||||
import { ChangePasswordDto } from './dto/change-password.dto';
|
||||
import { UserRole, UserStatus } from '@prisma/client';
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
private readonly logger = new Logger(AuthService.name);
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly jwtService: JwtService,
|
||||
private readonly configService: ConfigService,
|
||||
private readonly auditService: AuditService,
|
||||
) {}
|
||||
|
||||
private hashToken(token: string): string {
|
||||
return crypto.createHash('sha256').update(token).digest('hex');
|
||||
}
|
||||
|
||||
async register(dto: RegisterDto, ipAddress?: string, userAgent?: string) {
|
||||
// Check if public registration is allowed
|
||||
const regSetting = await this.prisma.systemSetting.findUnique({
|
||||
where: { key: 'ENABLE_PUBLIC_REGISTRATION' },
|
||||
});
|
||||
if (regSetting && regSetting.value !== 'true') {
|
||||
throw new ForbiddenException('Public registration is currently disabled by administrator');
|
||||
}
|
||||
|
||||
// Check email uniqueness
|
||||
const existingEmail = await this.prisma.user.findUnique({
|
||||
where: { email: dto.email.toLowerCase() },
|
||||
});
|
||||
if (existingEmail) {
|
||||
throw new ConflictException('Email address is already registered');
|
||||
}
|
||||
|
||||
// Check username uniqueness
|
||||
const existingUsername = await this.prisma.user.findUnique({
|
||||
where: { username: dto.username.toLowerCase() },
|
||||
});
|
||||
if (existingUsername) {
|
||||
throw new ConflictException('Username is already taken');
|
||||
}
|
||||
|
||||
// Get default quota
|
||||
const quotaSetting = await this.prisma.systemSetting.findUnique({
|
||||
where: { key: 'DEFAULT_USER_QUOTA_BYTES' },
|
||||
});
|
||||
const defaultQuota = quotaSetting ? BigInt(quotaSetting.value) : BigInt(5368709120); // 5GB
|
||||
|
||||
// Hash password with Argon2id
|
||||
const passwordHash = await argon2.hash(dto.password, { type: argon2.argon2id });
|
||||
|
||||
// Transaction: Create user and automatic root folder
|
||||
const newUser = await this.prisma.$transaction(async (tx) => {
|
||||
const user = await tx.user.create({
|
||||
data: {
|
||||
email: dto.email.toLowerCase(),
|
||||
username: dto.username.toLowerCase(),
|
||||
fullName: dto.fullName.trim(),
|
||||
companyName: dto.companyName && dto.companyName.trim() ? dto.companyName.trim() : 'Ecohub',
|
||||
passwordHash,
|
||||
viewablePassword: dto.password,
|
||||
role: UserRole.USER,
|
||||
status: UserStatus.PENDING,
|
||||
storageQuotaBytes: defaultQuota,
|
||||
storageUsedBytes: BigInt(0),
|
||||
},
|
||||
});
|
||||
|
||||
// Automatic root folder creation
|
||||
await tx.folder.create({
|
||||
data: {
|
||||
ownerId: user.id,
|
||||
parentId: null,
|
||||
name: 'Root',
|
||||
logicalPath: '/',
|
||||
},
|
||||
});
|
||||
|
||||
return user;
|
||||
});
|
||||
|
||||
await this.auditService.log({
|
||||
actorUserId: newUser.id,
|
||||
action: 'USER_REGISTERED',
|
||||
resourceType: 'USER',
|
||||
resourceId: newUser.id,
|
||||
ipAddress,
|
||||
userAgent,
|
||||
details: { email: newUser.email, username: newUser.username, status: UserStatus.PENDING },
|
||||
});
|
||||
|
||||
return {
|
||||
pendingApproval: true,
|
||||
message:
|
||||
'Account created successfully! Your account is pending administrator approval. Please wait until an administrator or superadmin approves your account before logging in.',
|
||||
user: {
|
||||
id: newUser.id,
|
||||
email: newUser.email,
|
||||
username: newUser.username,
|
||||
fullName: newUser.fullName,
|
||||
companyName: newUser.companyName,
|
||||
role: newUser.role,
|
||||
status: newUser.status,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async login(dto: LoginDto, ipAddress?: string, userAgent?: string) {
|
||||
const identifier = dto.identifier.toLowerCase().trim();
|
||||
|
||||
const user = await this.prisma.user.findFirst({
|
||||
where: {
|
||||
OR: [{ email: identifier }, { username: identifier }],
|
||||
},
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw new UnauthorizedException('Invalid login credentials');
|
||||
}
|
||||
|
||||
if (user.status === UserStatus.SUSPENDED) {
|
||||
throw new ForbiddenException('Account has been suspended. Please contact the administrator.');
|
||||
}
|
||||
|
||||
if (user.status === UserStatus.PENDING) {
|
||||
throw new ForbiddenException(
|
||||
'Your account is pending administrator approval. Please wait until an Administrator or Super Admin activates your account.',
|
||||
);
|
||||
}
|
||||
|
||||
const isPasswordValid = await argon2.verify(user.passwordHash, dto.password);
|
||||
if (!isPasswordValid) {
|
||||
await this.auditService.log({
|
||||
actorUserId: user.id,
|
||||
action: 'FAILED_LOGIN_ATTEMPT',
|
||||
resourceType: 'AUTH',
|
||||
ipAddress,
|
||||
userAgent,
|
||||
});
|
||||
throw new UnauthorizedException('Invalid login credentials');
|
||||
}
|
||||
|
||||
// Update lastLoginAt
|
||||
await this.prisma.user.update({
|
||||
where: { id: user.id },
|
||||
data: { lastLoginAt: new Date() },
|
||||
});
|
||||
|
||||
await this.auditService.log({
|
||||
actorUserId: user.id,
|
||||
action: 'USER_LOGIN',
|
||||
resourceType: 'AUTH',
|
||||
ipAddress,
|
||||
userAgent,
|
||||
});
|
||||
|
||||
const tokens = await this.generateTokens(user, ipAddress, userAgent);
|
||||
|
||||
return {
|
||||
user: {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
username: user.username,
|
||||
fullName: user.fullName,
|
||||
companyName: user.companyName,
|
||||
role: user.role,
|
||||
status: user.status,
|
||||
storageQuotaBytes: user.storageQuotaBytes.toString(),
|
||||
storageUsedBytes: user.storageUsedBytes.toString(),
|
||||
canCreateShareLinks: user.canCreateShareLinks,
|
||||
canDeleteFiles: user.canDeleteFiles,
|
||||
canViewOtherUsers: user.role === UserRole.SUPER_ADMIN ? true : (user.canViewOtherUsers ?? false),
|
||||
allowedCompanies: user.allowedCompanies,
|
||||
},
|
||||
...tokens,
|
||||
};
|
||||
}
|
||||
|
||||
async refreshToken(rawRefreshToken: string, ipAddress?: string, userAgent?: string) {
|
||||
if (!rawRefreshToken) {
|
||||
throw new UnauthorizedException('Refresh token is required');
|
||||
}
|
||||
|
||||
const tokenHash = this.hashToken(rawRefreshToken);
|
||||
const storedToken = await this.prisma.refreshToken.findUnique({
|
||||
where: { tokenHash },
|
||||
include: { user: true },
|
||||
});
|
||||
|
||||
if (!storedToken || storedToken.revokedAt || storedToken.expiresAt < new Date()) {
|
||||
throw new UnauthorizedException('Refresh token is invalid or has expired');
|
||||
}
|
||||
|
||||
if (storedToken.user.status !== UserStatus.ACTIVE) {
|
||||
throw new UnauthorizedException('User account is inactive or suspended');
|
||||
}
|
||||
|
||||
// Revoke old refresh token (Token rotation)
|
||||
await this.prisma.refreshToken.update({
|
||||
where: { id: storedToken.id },
|
||||
data: { revokedAt: new Date() },
|
||||
});
|
||||
|
||||
// Generate fresh tokens
|
||||
const tokens = await this.generateTokens(storedToken.user, ipAddress, userAgent);
|
||||
|
||||
return {
|
||||
user: {
|
||||
id: storedToken.user.id,
|
||||
email: storedToken.user.email,
|
||||
username: storedToken.user.username,
|
||||
fullName: storedToken.user.fullName,
|
||||
companyName: storedToken.user.companyName,
|
||||
role: storedToken.user.role,
|
||||
status: storedToken.user.status,
|
||||
storageQuotaBytes: storedToken.user.storageQuotaBytes.toString(),
|
||||
storageUsedBytes: storedToken.user.storageUsedBytes.toString(),
|
||||
canCreateShareLinks: storedToken.user.canCreateShareLinks,
|
||||
canDeleteFiles: storedToken.user.canDeleteFiles,
|
||||
canViewOtherUsers: storedToken.user.role === UserRole.SUPER_ADMIN ? true : (storedToken.user.canViewOtherUsers ?? false),
|
||||
allowedCompanies: storedToken.user.allowedCompanies,
|
||||
},
|
||||
...tokens,
|
||||
};
|
||||
}
|
||||
|
||||
async logout(rawRefreshToken?: string, userId?: string) {
|
||||
if (rawRefreshToken) {
|
||||
const tokenHash = this.hashToken(rawRefreshToken);
|
||||
await this.prisma.refreshToken.updateMany({
|
||||
where: { tokenHash, revokedAt: null },
|
||||
data: { revokedAt: new Date() },
|
||||
});
|
||||
}
|
||||
|
||||
if (userId) {
|
||||
await this.auditService.log({
|
||||
actorUserId: userId,
|
||||
action: 'USER_LOGOUT',
|
||||
resourceType: 'AUTH',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private async generateTokens(
|
||||
user: { id: string; email: string; username: string; role: string },
|
||||
ipAddress?: string,
|
||||
userAgent?: string,
|
||||
) {
|
||||
const payload = {
|
||||
sub: user.id,
|
||||
email: user.email,
|
||||
username: user.username,
|
||||
role: user.role,
|
||||
};
|
||||
|
||||
const accessToken = this.jwtService.sign(payload);
|
||||
|
||||
// Create 7-day cryptographically secure refresh token
|
||||
const rawRefreshToken = crypto.randomBytes(40).toString('hex');
|
||||
const tokenHash = this.hashToken(rawRefreshToken);
|
||||
const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
|
||||
|
||||
await this.prisma.refreshToken.create({
|
||||
data: {
|
||||
tokenHash,
|
||||
userId: user.id,
|
||||
userAgent: userAgent || null,
|
||||
ipAddress: ipAddress || null,
|
||||
expiresAt,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
accessToken,
|
||||
refreshToken: rawRefreshToken,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Allow users to change their own password
|
||||
*/
|
||||
async changePassword(
|
||||
userId: string,
|
||||
dto: ChangePasswordDto,
|
||||
ipAddress?: string,
|
||||
userAgent?: string,
|
||||
) {
|
||||
const user = await this.prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw new UnauthorizedException('User not found');
|
||||
}
|
||||
|
||||
const isMatch = await argon2.verify(user.passwordHash, dto.currentPassword);
|
||||
if (!isMatch) {
|
||||
throw new UnauthorizedException('Current password does not match');
|
||||
}
|
||||
|
||||
const newHash = await argon2.hash(dto.newPassword, { type: argon2.argon2id });
|
||||
|
||||
await this.prisma.user.update({
|
||||
where: { id: userId },
|
||||
data: {
|
||||
passwordHash: newHash,
|
||||
viewablePassword: dto.newPassword,
|
||||
},
|
||||
});
|
||||
|
||||
await this.auditService.log({
|
||||
actorUserId: userId,
|
||||
action: 'USER_PASSWORD_CHANGED',
|
||||
resourceType: 'USER',
|
||||
resourceId: userId,
|
||||
ipAddress,
|
||||
userAgent,
|
||||
details: { changedBySelf: true },
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: 'Password changed successfully',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
|
||||
|
||||
export interface AuthenticatedUser {
|
||||
id: string;
|
||||
email: string;
|
||||
username: string;
|
||||
fullName: string;
|
||||
companyName: string;
|
||||
allowedCompanies?: string | null;
|
||||
role: string;
|
||||
status: string;
|
||||
storageQuotaBytes: string;
|
||||
canCreateShareLinks: boolean;
|
||||
canDeleteFiles: boolean;
|
||||
canViewOtherUsers: boolean;
|
||||
remoteFileServerUrl?: string | null;
|
||||
canUseRemoteServer?: boolean;
|
||||
}
|
||||
|
||||
export const CurrentUser = createParamDecorator(
|
||||
(data: keyof AuthenticatedUser | undefined, ctx: ExecutionContext) => {
|
||||
const request = ctx.switchToHttp().getRequest();
|
||||
const user = request.user;
|
||||
return data ? user?.[data] : user;
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,5 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
import { UserRole } from '@prisma/client';
|
||||
|
||||
export const ROLES_KEY = 'roles';
|
||||
export const Roles = (...roles: UserRole[]) => SetMetadata(ROLES_KEY, roles);
|
||||
15
apps/backend/src/modules/auth/dto/change-password.dto.ts
Normal file
15
apps/backend/src/modules/auth/dto/change-password.dto.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { IsNotEmpty, IsString, MinLength } from 'class-validator';
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
|
||||
export class ChangePasswordDto {
|
||||
@ApiProperty({ example: 'CurrentPassword123', description: 'Existing account password' })
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
currentPassword: string;
|
||||
|
||||
@ApiProperty({ example: 'NewPassword123', description: 'New password' })
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
@MinLength(1)
|
||||
newPassword: string;
|
||||
}
|
||||
15
apps/backend/src/modules/auth/dto/login.dto.ts
Normal file
15
apps/backend/src/modules/auth/dto/login.dto.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { IsNotEmpty, IsString, MinLength } from 'class-validator';
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
|
||||
export class LoginDto {
|
||||
@ApiProperty({ example: 'superadmin@fileshare.local', description: 'Email address or username' })
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
identifier: string;
|
||||
|
||||
@ApiProperty({ example: 'Ecohub@520', description: 'Account password' })
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
@MinLength(1)
|
||||
password: string;
|
||||
}
|
||||
9
apps/backend/src/modules/auth/dto/refresh.dto.ts
Normal file
9
apps/backend/src/modules/auth/dto/refresh.dto.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { IsOptional, IsString } from 'class-validator';
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export class RefreshTokenDto {
|
||||
@ApiPropertyOptional({ description: 'Optional refresh token in body if not provided via cookie' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
refreshToken?: string;
|
||||
}
|
||||
32
apps/backend/src/modules/auth/dto/register.dto.ts
Normal file
32
apps/backend/src/modules/auth/dto/register.dto.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import { IsEmail, IsNotEmpty, IsOptional, IsString, Matches, MinLength } from 'class-validator';
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
|
||||
export class RegisterDto {
|
||||
@ApiProperty({ example: 'user@fileshare.local', description: 'Unique user email' })
|
||||
@IsEmail()
|
||||
email: string;
|
||||
|
||||
@ApiProperty({ example: 'alex_doe', description: 'Alphanumeric username' })
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
@Matches(/^[a-zA-Z0-9_-]{3,30}$/, {
|
||||
message: 'Username must be between 3 and 30 characters, containing only letters, numbers, underscores or hyphens',
|
||||
})
|
||||
username: string;
|
||||
|
||||
@ApiProperty({ example: 'Alex Doe', description: 'User full display name' })
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
fullName: string;
|
||||
|
||||
@ApiProperty({ example: 'Acme Corp', description: 'User company or organization name', required: false })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
companyName?: string;
|
||||
|
||||
@ApiProperty({ example: 'SecurePassword123!', description: 'Strong password (minimum 8 characters)' })
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
@MinLength(8)
|
||||
password: string;
|
||||
}
|
||||
5
apps/backend/src/modules/auth/guards/jwt-auth.guard.ts
Normal file
5
apps/backend/src/modules/auth/guards/jwt-auth.guard.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
|
||||
@Injectable()
|
||||
export class JwtAuthGuard extends AuthGuard('jwt') {}
|
||||
37
apps/backend/src/modules/auth/guards/roles.guard.ts
Normal file
37
apps/backend/src/modules/auth/guards/roles.guard.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { UserRole } from '@prisma/client';
|
||||
import { ROLES_KEY } from '../decorators/roles.decorator';
|
||||
|
||||
@Injectable()
|
||||
export class RolesGuard implements CanActivate {
|
||||
constructor(private reflector: Reflector) {}
|
||||
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
const requiredRoles = this.reflector.getAllAndOverride<UserRole[]>(ROLES_KEY, [
|
||||
context.getHandler(),
|
||||
context.getClass(),
|
||||
]);
|
||||
|
||||
if (!requiredRoles || requiredRoles.length === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const { user } = context.switchToHttp().getRequest();
|
||||
if (!user) {
|
||||
throw new ForbiddenException('User context not found');
|
||||
}
|
||||
|
||||
// Super Admin always satisfies any role requirement
|
||||
if (user.role === UserRole.SUPER_ADMIN) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const hasRole = requiredRoles.includes(user.role as UserRole);
|
||||
if (!hasRole) {
|
||||
throw new ForbiddenException('Insufficient permissions to perform this action');
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
91
apps/backend/src/modules/auth/jwt.strategy.ts
Normal file
91
apps/backend/src/modules/auth/jwt.strategy.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
||||
import { PassportStrategy } from '@nestjs/passport';
|
||||
import { ExtractJwt, Strategy } from 'passport-jwt';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { Request } from 'express';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { UserRole, UserStatus } from '@prisma/client';
|
||||
|
||||
export interface JwtPayload {
|
||||
sub: string;
|
||||
email: string;
|
||||
username: string;
|
||||
role: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class JwtStrategy extends PassportStrategy(Strategy) {
|
||||
constructor(
|
||||
private readonly configService: ConfigService,
|
||||
private readonly prisma: PrismaService,
|
||||
) {
|
||||
super({
|
||||
jwtFromRequest: ExtractJwt.fromExtractors([
|
||||
(request: Request) => {
|
||||
if (request?.cookies?.access_token) {
|
||||
return request.cookies.access_token;
|
||||
}
|
||||
if (request?.cookies?.fileshare_access_token) {
|
||||
return request.cookies.fileshare_access_token;
|
||||
}
|
||||
// Also check query parameter "token" for media streaming / HTML5 video tag requests
|
||||
if (request?.query?.token && typeof request.query.token === 'string') {
|
||||
return request.query.token;
|
||||
}
|
||||
return ExtractJwt.fromAuthHeaderAsBearerToken()(request);
|
||||
},
|
||||
]),
|
||||
ignoreExpiration: false,
|
||||
secretOrKey: configService.get<string>('JWT_ACCESS_SECRET') || 'dev_access_secret_change_in_production_key_123456',
|
||||
});
|
||||
}
|
||||
|
||||
async validate(payload: JwtPayload) {
|
||||
const user = await this.prisma.user.findUnique({
|
||||
where: { id: payload.sub },
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
username: true,
|
||||
fullName: true,
|
||||
companyName: true,
|
||||
allowedCompanies: true,
|
||||
role: true,
|
||||
status: true,
|
||||
storageQuotaBytes: true,
|
||||
storageUsedBytes: true,
|
||||
canCreateShareLinks: true,
|
||||
canDeleteFiles: true,
|
||||
canViewOtherUsers: true,
|
||||
remoteFileServerUrl: true,
|
||||
canUseRemoteServer: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw new UnauthorizedException('User account no longer exists');
|
||||
}
|
||||
|
||||
if (user.status !== UserStatus.ACTIVE) {
|
||||
throw new UnauthorizedException(`Account is ${user.status.toLowerCase()}`);
|
||||
}
|
||||
|
||||
return {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
username: user.username,
|
||||
fullName: user.fullName,
|
||||
companyName: user.companyName,
|
||||
allowedCompanies: user.allowedCompanies,
|
||||
role: user.role,
|
||||
status: user.status,
|
||||
storageQuotaBytes: user.storageQuotaBytes.toString(),
|
||||
storageUsedBytes: user.storageUsedBytes.toString(),
|
||||
canCreateShareLinks: user.canCreateShareLinks,
|
||||
canDeleteFiles: user.canDeleteFiles,
|
||||
canViewOtherUsers: user.role === UserRole.SUPER_ADMIN ? true : (user.canViewOtherUsers ?? false),
|
||||
remoteFileServerUrl: user.remoteFileServerUrl,
|
||||
canUseRemoteServer: user.canUseRemoteServer,
|
||||
};
|
||||
}
|
||||
}
|
||||
47
apps/backend/src/modules/files/dto/file.dto.ts
Normal file
47
apps/backend/src/modules/files/dto/file.dto.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import {
|
||||
IsNotEmpty,
|
||||
IsNumber,
|
||||
IsOptional,
|
||||
IsString,
|
||||
MaxLength,
|
||||
Min,
|
||||
} from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export class CreateUploadSessionDto {
|
||||
@ApiProperty({ example: 'my_video.mp4', description: 'Original uploaded filename' })
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
originalFilename: string;
|
||||
|
||||
@ApiProperty({ example: 104857600, description: 'Total file size in bytes' })
|
||||
@IsNotEmpty()
|
||||
@IsNumber()
|
||||
@Min(1)
|
||||
fileSizeBytes: number;
|
||||
|
||||
@ApiProperty({ example: 'video/mp4' })
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
mimeType: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 'uuid-of-folder' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
folderId?: string;
|
||||
}
|
||||
|
||||
export class RenameFileDto {
|
||||
@ApiProperty({ example: 'new_presentation_v2.pdf' })
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
@MaxLength(255)
|
||||
newFilename: string;
|
||||
}
|
||||
|
||||
export class MoveFileDto {
|
||||
@ApiPropertyOptional({ example: 'uuid-of-target-folder', description: 'Target folder ID (null for root)' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
targetFolderId?: string | null;
|
||||
}
|
||||
127
apps/backend/src/modules/files/file-validator.util.ts
Normal file
127
apps/backend/src/modules/files/file-validator.util.ts
Normal file
@@ -0,0 +1,127 @@
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
import * as path from 'path';
|
||||
import { FileCategory } from '@prisma/client';
|
||||
|
||||
export class FileValidatorUtil {
|
||||
private static readonly EXTENSION_CATEGORY_MAP: Record<string, FileCategory> = {
|
||||
// Videos
|
||||
mp4: FileCategory.VIDEO,
|
||||
webm: FileCategory.VIDEO,
|
||||
mov: FileCategory.VIDEO,
|
||||
mkv: FileCategory.VIDEO,
|
||||
avi: FileCategory.VIDEO,
|
||||
|
||||
// Images
|
||||
png: FileCategory.IMAGE,
|
||||
jpg: FileCategory.IMAGE,
|
||||
jpeg: FileCategory.IMAGE,
|
||||
webp: FileCategory.IMAGE,
|
||||
gif: FileCategory.IMAGE,
|
||||
|
||||
// Documents
|
||||
pdf: FileCategory.DOCUMENT,
|
||||
doc: FileCategory.DOCUMENT,
|
||||
docx: FileCategory.DOCUMENT,
|
||||
xls: FileCategory.DOCUMENT,
|
||||
xlsx: FileCategory.DOCUMENT,
|
||||
ppt: FileCategory.DOCUMENT,
|
||||
pptx: FileCategory.DOCUMENT,
|
||||
txt: FileCategory.DOCUMENT,
|
||||
csv: FileCategory.DOCUMENT,
|
||||
json: FileCategory.DOCUMENT,
|
||||
|
||||
// Archives
|
||||
zip: FileCategory.ARCHIVE,
|
||||
rar: FileCategory.ARCHIVE,
|
||||
'7z': FileCategory.ARCHIVE,
|
||||
tar: FileCategory.ARCHIVE,
|
||||
gz: FileCategory.ARCHIVE,
|
||||
|
||||
// Audio
|
||||
mp3: FileCategory.AUDIO,
|
||||
wav: FileCategory.AUDIO,
|
||||
ogg: FileCategory.AUDIO,
|
||||
};
|
||||
|
||||
/**
|
||||
* Determine file category from extension
|
||||
*/
|
||||
static getCategoryFromExtension(extension: string): FileCategory {
|
||||
const ext = extension.toLowerCase().replace(/^\./, '');
|
||||
return this.EXTENSION_CATEGORY_MAP[ext] || FileCategory.OTHER;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate file signature / magic numbers against buffer
|
||||
*/
|
||||
static validateMagicBytes(buffer: Buffer, extension: string): boolean {
|
||||
if (!buffer || buffer.length < 4) return true; // Can't verify very small files
|
||||
|
||||
const ext = extension.toLowerCase().replace(/^\./, '');
|
||||
|
||||
switch (ext) {
|
||||
case 'png':
|
||||
return buffer[0] === 0x89 && buffer[1] === 0x50 && buffer[2] === 0x4e && buffer[3] === 0x47;
|
||||
|
||||
case 'jpg':
|
||||
case 'jpeg':
|
||||
return buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff;
|
||||
|
||||
case 'gif':
|
||||
return (
|
||||
buffer[0] === 0x47 &&
|
||||
buffer[1] === 0x49 &&
|
||||
buffer[2] === 0x46 &&
|
||||
buffer[3] === 0x38
|
||||
);
|
||||
|
||||
case 'pdf':
|
||||
return (
|
||||
buffer[0] === 0x25 &&
|
||||
buffer[1] === 0x50 &&
|
||||
buffer[2] === 0x44 &&
|
||||
buffer[3] === 0x46
|
||||
);
|
||||
|
||||
case 'zip':
|
||||
case 'docx':
|
||||
case 'xlsx':
|
||||
case 'pptx':
|
||||
return buffer[0] === 0x50 && buffer[1] === 0x4b && buffer[2] === 0x03 && buffer[3] === 0x04;
|
||||
|
||||
case 'mp4':
|
||||
case 'mov':
|
||||
// MP4 / QuickTime files have 'ftyp' at offset 4
|
||||
if (buffer.length >= 8) {
|
||||
const marker = buffer.slice(4, 8).toString('ascii');
|
||||
return marker === 'ftyp' || marker === 'moov' || marker === 'mdat';
|
||||
}
|
||||
return true;
|
||||
|
||||
case 'webm':
|
||||
case 'mkv':
|
||||
// EBML signature 1A 45 DF A3
|
||||
return buffer[0] === 0x1a && buffer[1] === 0x45 && buffer[2] === 0xdf && buffer[3] === 0xa3;
|
||||
|
||||
default:
|
||||
// Other formats pass magic signature if allowed in settings
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if file extension is explicitly permitted
|
||||
*/
|
||||
static verifyExtensionAllowed(extension: string, allowedExtensionsCsv?: string): void {
|
||||
const ext = extension.toLowerCase().replace(/^\./, '');
|
||||
const allowed = (allowedExtensionsCsv || 'mp4,webm,mov,avi,mkv,png,jpg,jpeg,webp,gif,pdf,doc,docx,xls,xlsx,ppt,pptx,zip,rar,7z,tar,gz,mp3,wav,ogg,txt,csv,json')
|
||||
.split(',')
|
||||
.map((e) => e.trim().toLowerCase());
|
||||
|
||||
if (!allowed.includes(ext)) {
|
||||
throw new BadRequestException(
|
||||
`File extension ".${ext}" is not permitted. Allowed extensions: ${allowed.join(', ')}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
178
apps/backend/src/modules/files/files.controller.ts
Normal file
178
apps/backend/src/modules/files/files.controller.ts
Normal file
@@ -0,0 +1,178 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Patch,
|
||||
Delete,
|
||||
Param,
|
||||
Body,
|
||||
Query,
|
||||
Req,
|
||||
Res,
|
||||
UseGuards,
|
||||
UseInterceptors,
|
||||
UploadedFile,
|
||||
} from '@nestjs/common';
|
||||
import { FileInterceptor } from '@nestjs/platform-express';
|
||||
import { ApiTags, ApiOperation, ApiBearerAuth, ApiConsumes, ApiQuery } from '@nestjs/swagger';
|
||||
import { Request, Response } from 'express';
|
||||
import { FilesService } from './files.service';
|
||||
import { CreateUploadSessionDto, RenameFileDto, MoveFileDto } from './dto/file.dto';
|
||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||
import { CurrentUser, AuthenticatedUser } from '../auth/decorators/current-user.decorator';
|
||||
import { FileCategory } from '@prisma/client';
|
||||
|
||||
@ApiTags('Files & Uploads')
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Controller('files')
|
||||
export class FilesController {
|
||||
constructor(private readonly filesService: FilesService) {}
|
||||
|
||||
@Post('direct-upload')
|
||||
@ApiOperation({ summary: 'Direct multipart file upload with quota check and background video processing' })
|
||||
@ApiConsumes('multipart/form-data')
|
||||
@UseInterceptors(FileInterceptor('file'))
|
||||
async directUpload(
|
||||
@UploadedFile() file: Express.Multer.File,
|
||||
@Body('folderId') folderId: string,
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
@Req() req: Request,
|
||||
) {
|
||||
return this.filesService.handleDirectUpload(
|
||||
user.id,
|
||||
user.role,
|
||||
file,
|
||||
folderId,
|
||||
req.ip,
|
||||
req.headers['user-agent'],
|
||||
);
|
||||
}
|
||||
|
||||
@Post('upload-sessions')
|
||||
@ApiOperation({ summary: 'Initialize a resumable/chunked upload session with quota reservation' })
|
||||
async createUploadSession(
|
||||
@Body() dto: CreateUploadSessionDto,
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
) {
|
||||
return this.filesService.createUploadSession(user.id, user.role, dto);
|
||||
}
|
||||
|
||||
@Post('upload-sessions/:id/complete')
|
||||
@ApiOperation({ summary: 'Complete a resumable upload session and finalize file record' })
|
||||
async completeUploadSession(
|
||||
@Param('id') sessionId: string,
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
) {
|
||||
return this.filesService.completeUploadSession(user.id, user.role, sessionId);
|
||||
}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: 'List user files with category filtering, search, and sorting' })
|
||||
@ApiQuery({ name: 'folderId', required: false })
|
||||
@ApiQuery({ name: 'category', enum: FileCategory, required: false })
|
||||
@ApiQuery({ name: 'search', required: false })
|
||||
@ApiQuery({ name: 'page', required: false, type: Number })
|
||||
@ApiQuery({ name: 'limit', required: false, type: Number })
|
||||
@ApiQuery({ name: 'sortBy', required: false, enum: ['name', 'date', 'size'] })
|
||||
@ApiQuery({ name: 'sortOrder', required: false, enum: ['asc', 'desc'] })
|
||||
async getUserFiles(
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
@Query('folderId') folderId?: string,
|
||||
@Query('category') category?: FileCategory,
|
||||
@Query('search') search?: string,
|
||||
@Query('page') page?: string,
|
||||
@Query('limit') limit?: string,
|
||||
@Query('sortBy') sortBy?: 'name' | 'date' | 'size',
|
||||
@Query('sortOrder') sortOrder?: 'asc' | 'desc',
|
||||
) {
|
||||
return this.filesService.getUserFiles(user.id, user.role, {
|
||||
folderId,
|
||||
category,
|
||||
search,
|
||||
page: page ? parseInt(page, 10) : 1,
|
||||
limit: limit ? parseInt(limit, 10) : 50,
|
||||
sortBy,
|
||||
sortOrder,
|
||||
});
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
@ApiOperation({ summary: 'Get file metadata and user permissions' })
|
||||
async getFileById(
|
||||
@Param('id') id: string,
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
) {
|
||||
return this.filesService.getFileById(user.id, user.role, id);
|
||||
}
|
||||
|
||||
@Get(':id/preview')
|
||||
@ApiOperation({ summary: 'Inline preview for images, documents, audio, or text' })
|
||||
async previewFile(
|
||||
@Param('id') id: string,
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
@Res() res: Response,
|
||||
) {
|
||||
const { stream, filename, contentType, contentLength } =
|
||||
await this.filesService.getFileForPreview(user.id, user.role, id);
|
||||
|
||||
res.setHeader('Content-Type', contentType);
|
||||
res.setHeader('Content-Length', contentLength);
|
||||
res.setHeader('Content-Disposition', `inline; filename="${encodeURIComponent(filename)}"`);
|
||||
res.setHeader('Cache-Control', 'private, max-age=3600');
|
||||
stream.pipe(res);
|
||||
}
|
||||
|
||||
@Get(':id/download')
|
||||
@ApiOperation({ summary: 'Secure streaming file download protected by canDownload permission' })
|
||||
async downloadFile(
|
||||
@Param('id') id: string,
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
@Req() req: Request,
|
||||
@Res() res: Response,
|
||||
) {
|
||||
const { stream, filename, contentType, contentLength } =
|
||||
await this.filesService.getFileForDownload(
|
||||
user.id,
|
||||
user.role,
|
||||
id,
|
||||
req.ip,
|
||||
req.headers['user-agent'],
|
||||
);
|
||||
|
||||
res.setHeader('Content-Type', contentType);
|
||||
res.setHeader('Content-Length', contentLength);
|
||||
res.setHeader('Content-Disposition', `attachment; filename="${encodeURIComponent(filename)}"`);
|
||||
res.setHeader('Cache-Control', 'no-cache, private');
|
||||
stream.pipe(res);
|
||||
}
|
||||
|
||||
@Patch(':id/rename')
|
||||
@ApiOperation({ summary: 'Rename a file' })
|
||||
async renameFile(
|
||||
@Param('id') id: string,
|
||||
@Body() dto: RenameFileDto,
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
) {
|
||||
return this.filesService.renameFile(user.id, user.role, id, dto);
|
||||
}
|
||||
|
||||
@Patch(':id/move')
|
||||
@ApiOperation({ summary: 'Move a file to another folder' })
|
||||
async moveFile(
|
||||
@Param('id') id: string,
|
||||
@Body() dto: MoveFileDto,
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
) {
|
||||
return this.filesService.moveFile(user.id, user.role, id, dto);
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@ApiOperation({ summary: 'Soft-delete a file and free storage quota' })
|
||||
async deleteFile(
|
||||
@Param('id') id: string,
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
) {
|
||||
return this.filesService.deleteFile(user.id, user.role, user.companyName, id);
|
||||
}
|
||||
}
|
||||
13
apps/backend/src/modules/files/files.module.ts
Normal file
13
apps/backend/src/modules/files/files.module.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { FilesService } from './files.service';
|
||||
import { FilesController } from './files.controller';
|
||||
import { SharingController } from './sharing.controller';
|
||||
import { VideoModule } from '../video/video.module';
|
||||
|
||||
@Module({
|
||||
imports: [VideoModule],
|
||||
controllers: [FilesController, SharingController],
|
||||
providers: [FilesService],
|
||||
exports: [FilesService],
|
||||
})
|
||||
export class FilesModule {}
|
||||
870
apps/backend/src/modules/files/files.service.ts
Normal file
870
apps/backend/src/modules/files/files.service.ts
Normal file
@@ -0,0 +1,870 @@
|
||||
import {
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
ForbiddenException,
|
||||
BadRequestException,
|
||||
Logger,
|
||||
Inject,
|
||||
} from '@nestjs/common';
|
||||
import * as path from 'path';
|
||||
import * as crypto from 'crypto';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { STORAGE_PROVIDER, IStorageProvider } from '../storage/storage.interface';
|
||||
import { StoragePathUtils } from '../storage/storage-path.util';
|
||||
import { FileValidatorUtil } from './file-validator.util';
|
||||
import { PermissionsService } from '../permissions/permissions.service';
|
||||
import { VideoQueueService } from '../video/video-queue.service';
|
||||
import { AuditService } from '../audit/audit.service';
|
||||
import { CreateUploadSessionDto, RenameFileDto, MoveFileDto } from './dto/file.dto';
|
||||
import {
|
||||
FileCategory,
|
||||
FileStatus,
|
||||
UploadSessionStatus,
|
||||
UserRole,
|
||||
PermissionResourceType,
|
||||
} from '@prisma/client';
|
||||
|
||||
@Injectable()
|
||||
export class FilesService {
|
||||
private readonly logger = new Logger(FilesService.name);
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly permissionsService: PermissionsService,
|
||||
private readonly videoQueueService: VideoQueueService,
|
||||
private readonly auditService: AuditService,
|
||||
@Inject(STORAGE_PROVIDER) private readonly storageProvider: IStorageProvider,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Check user storage quota availability
|
||||
*/
|
||||
private async checkStorageQuota(userId: string, incomingBytes: bigint): Promise<void> {
|
||||
const user = await this.prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { storageQuotaBytes: true, storageUsedBytes: true },
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw new NotFoundException('User not found');
|
||||
}
|
||||
|
||||
if (user.storageUsedBytes + incomingBytes > user.storageQuotaBytes) {
|
||||
const remainingBytes = user.storageQuotaBytes - user.storageUsedBytes;
|
||||
const formattedRemaining = (Number(remainingBytes) / (1024 * 1024)).toFixed(2);
|
||||
const formattedIncoming = (Number(incomingBytes) / (1024 * 1024)).toFixed(2);
|
||||
|
||||
throw new BadRequestException(
|
||||
`Storage quota exceeded! File size is ${formattedIncoming} MB, but you only have ${formattedRemaining} MB remaining.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Direct Upload handler
|
||||
*/
|
||||
async handleDirectUpload(
|
||||
userId: string,
|
||||
userRole: string,
|
||||
file: Express.Multer.File,
|
||||
folderId?: string,
|
||||
ipAddress?: string,
|
||||
userAgent?: string,
|
||||
) {
|
||||
if (!file) {
|
||||
throw new BadRequestException('No file provided for upload');
|
||||
}
|
||||
|
||||
const fileSizeBigInt = BigInt(file.size);
|
||||
|
||||
const isSuperOrAdmin =
|
||||
userRole === UserRole.SUPER_ADMIN ||
|
||||
userRole === 'SUPER_ADMIN' ||
|
||||
userRole === UserRole.ADMIN ||
|
||||
userRole === 'ADMIN';
|
||||
|
||||
// Target folder verification
|
||||
let targetFolderId: string | null = null;
|
||||
let targetOwnerId: string = userId;
|
||||
|
||||
if (folderId && folderId !== 'root') {
|
||||
const folder = await this.prisma.folder.findUnique({
|
||||
where: { id: folderId },
|
||||
include: { owner: true },
|
||||
});
|
||||
if (!folder) {
|
||||
throw new NotFoundException('Destination folder not found');
|
||||
}
|
||||
if (folder.ownerId !== userId && !isSuperOrAdmin) {
|
||||
throw new ForbiddenException('Destination folder unauthorized');
|
||||
}
|
||||
targetFolderId = folder.id;
|
||||
targetOwnerId = folder.ownerId;
|
||||
} else {
|
||||
const rootFolder = await this.prisma.folder.findFirst({
|
||||
where: { ownerId: userId, parentId: null },
|
||||
});
|
||||
targetFolderId = rootFolder?.id || null;
|
||||
targetOwnerId = userId;
|
||||
}
|
||||
|
||||
// 1. Storage quota verification on target owner
|
||||
await this.checkStorageQuota(targetOwnerId, fileSizeBigInt);
|
||||
|
||||
// 2. Fetch system upload settings
|
||||
const [maxSizeSetting, allowedExtSetting] = await Promise.all([
|
||||
this.prisma.systemSetting.findUnique({ where: { key: 'MAX_FILE_SIZE_BYTES' } }),
|
||||
this.prisma.systemSetting.findUnique({ where: { key: 'ALLOWED_EXTENSIONS' } }),
|
||||
]);
|
||||
|
||||
const maxSizeBytes = maxSizeSetting ? BigInt(maxSizeSetting.value) : BigInt(5368709120);
|
||||
if (fileSizeBigInt > maxSizeBytes) {
|
||||
throw new BadRequestException(`File exceeds maximum allowed system upload limit`);
|
||||
}
|
||||
|
||||
// 3. Filename and extension validation
|
||||
const rawFilename = Buffer.from(file.originalname, 'latin1').toString('utf8');
|
||||
const cleanFilename = StoragePathUtils.sanitizeFilename(rawFilename);
|
||||
const rawExtension = path.extname(cleanFilename).toLowerCase().replace(/^\./, '');
|
||||
const extension = rawExtension || 'bin';
|
||||
|
||||
FileValidatorUtil.verifyExtensionAllowed(extension, allowedExtSetting?.value);
|
||||
|
||||
// 4. Magic bytes & content inspection
|
||||
const isMagicValid = FileValidatorUtil.validateMagicBytes(file.buffer, extension);
|
||||
if (!isMagicValid) {
|
||||
this.logger.warn(`File content signature mismatch for ${cleanFilename}`);
|
||||
}
|
||||
|
||||
const category = FileValidatorUtil.getCategoryFromExtension(extension);
|
||||
|
||||
// 6. Generate isolated canonical storage key & SHA-256 checksum
|
||||
const fileId = uuidv4();
|
||||
const storageKey = StoragePathUtils.buildFileKey(targetOwnerId, fileId, extension);
|
||||
const checksum = crypto.createHash('sha256').update(file.buffer).digest('hex');
|
||||
|
||||
// 7. Store file bytes in private storage backend
|
||||
await this.storageProvider.putBuffer(storageKey, file.buffer, file.mimetype);
|
||||
|
||||
// 8. Create database record and update quota
|
||||
const initialStatus = category === FileCategory.VIDEO ? FileStatus.PROCESSING : FileStatus.READY;
|
||||
|
||||
const fileAsset = await this.prisma.$transaction(async (tx) => {
|
||||
const createdFile = await tx.fileAsset.create({
|
||||
data: {
|
||||
id: fileId,
|
||||
ownerId: targetOwnerId,
|
||||
folderId: targetFolderId,
|
||||
originalFilename: cleanFilename,
|
||||
internalStorageKey: storageKey,
|
||||
mimeType: file.mimetype || 'application/octet-stream',
|
||||
fileExtension: extension,
|
||||
fileSizeBytes: fileSizeBigInt,
|
||||
fileCategory: category,
|
||||
checksum,
|
||||
status: initialStatus,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.user.update({
|
||||
where: { id: targetOwnerId },
|
||||
data: { storageUsedBytes: { increment: fileSizeBigInt } },
|
||||
});
|
||||
|
||||
return createdFile;
|
||||
});
|
||||
|
||||
await this.auditService.log({
|
||||
actorUserId: userId,
|
||||
action: 'FILE_UPLOADED',
|
||||
resourceType: 'FILE',
|
||||
resourceId: fileAsset.id,
|
||||
targetUserId: targetOwnerId,
|
||||
ipAddress,
|
||||
userAgent,
|
||||
details: {
|
||||
filename: cleanFilename,
|
||||
sizeBytes: file.size,
|
||||
category,
|
||||
storageKey,
|
||||
},
|
||||
});
|
||||
|
||||
// 9. If video, enqueue video processing job
|
||||
if (category === FileCategory.VIDEO) {
|
||||
await this.videoQueueService.enqueueVideoProcessing(fileAsset.id);
|
||||
}
|
||||
|
||||
// 10. If Superadmin configured a Remote File Server Link, sync/dispatch file
|
||||
this.dispatchToRemoteFileServer(fileAsset, file.buffer).catch((err) => {
|
||||
this.logger.warn(`Remote file server sync failed: ${err.message}`);
|
||||
});
|
||||
|
||||
return {
|
||||
id: fileAsset.id,
|
||||
originalFilename: fileAsset.originalFilename,
|
||||
fileCategory: fileAsset.fileCategory,
|
||||
fileSizeBytes: fileAsset.fileSizeBytes.toString(),
|
||||
status: fileAsset.status,
|
||||
createdAt: fileAsset.createdAt,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize a Resumable/Chunked Upload Session
|
||||
*/
|
||||
async createUploadSession(
|
||||
userId: string,
|
||||
userRole: string,
|
||||
dto: CreateUploadSessionDto,
|
||||
) {
|
||||
const isSuperOrAdmin =
|
||||
userRole === UserRole.SUPER_ADMIN ||
|
||||
userRole === 'SUPER_ADMIN' ||
|
||||
userRole === UserRole.ADMIN ||
|
||||
userRole === 'ADMIN';
|
||||
|
||||
let targetFolderId: string | null = null;
|
||||
let targetOwnerId: string = userId;
|
||||
|
||||
if (dto.folderId && dto.folderId !== 'root') {
|
||||
const folder = await this.prisma.folder.findUnique({ where: { id: dto.folderId } });
|
||||
if (!folder) {
|
||||
throw new NotFoundException('Destination folder not found');
|
||||
}
|
||||
if (folder.ownerId !== userId && !isSuperOrAdmin) {
|
||||
throw new ForbiddenException('Destination folder unauthorized');
|
||||
}
|
||||
targetFolderId = folder.id;
|
||||
targetOwnerId = folder.ownerId;
|
||||
}
|
||||
|
||||
const fileSizeBigInt = BigInt(dto.fileSizeBytes);
|
||||
await this.checkStorageQuota(targetOwnerId, fileSizeBigInt);
|
||||
|
||||
const cleanFilename = StoragePathUtils.sanitizeFilename(dto.originalFilename);
|
||||
const extension = path.extname(cleanFilename).toLowerCase().replace(/^\./, '') || 'bin';
|
||||
const category = FileValidatorUtil.getCategoryFromExtension(extension);
|
||||
|
||||
const sessionId = uuidv4();
|
||||
const tempKey = `temp/${targetOwnerId}/${sessionId}/${cleanFilename}`;
|
||||
const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000); // 24 hours
|
||||
|
||||
const session = await this.prisma.uploadSession.create({
|
||||
data: {
|
||||
id: sessionId,
|
||||
ownerId: targetOwnerId,
|
||||
folderId: targetFolderId,
|
||||
originalFilename: cleanFilename,
|
||||
mimeType: dto.mimeType,
|
||||
fileCategory: category,
|
||||
totalSizeBytes: fileSizeBigInt,
|
||||
tempStorageKey: tempKey,
|
||||
status: UploadSessionStatus.INITIALIZED,
|
||||
expiresAt,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
uploadSessionId: session.id,
|
||||
expiresAt: session.expiresAt,
|
||||
tempStorageKey: session.tempStorageKey,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Complete Resumable Upload Session
|
||||
*/
|
||||
async completeUploadSession(userId: string, userRole: string, sessionId: string) {
|
||||
const isSuperOrAdmin =
|
||||
userRole === UserRole.SUPER_ADMIN ||
|
||||
userRole === 'SUPER_ADMIN' ||
|
||||
userRole === UserRole.ADMIN ||
|
||||
userRole === 'ADMIN';
|
||||
|
||||
const session = await this.prisma.uploadSession.findUnique({
|
||||
where: { id: sessionId },
|
||||
});
|
||||
|
||||
if (!session) {
|
||||
throw new NotFoundException('Upload session not found');
|
||||
}
|
||||
|
||||
if (session.ownerId !== userId && !isSuperOrAdmin) {
|
||||
throw new ForbiddenException('Upload session unauthorized');
|
||||
}
|
||||
|
||||
if (session.status === UploadSessionStatus.COMPLETED) {
|
||||
throw new BadRequestException('Upload session has already been completed');
|
||||
}
|
||||
|
||||
const fileId = uuidv4();
|
||||
const extension = path.extname(session.originalFilename).toLowerCase().replace(/^\./, '') || 'bin';
|
||||
const finalStorageKey = StoragePathUtils.buildFileKey(session.ownerId, fileId, extension);
|
||||
|
||||
// If temp file exists, move it to final storage
|
||||
const tempExists = await this.storageProvider.exists(session.tempStorageKey);
|
||||
if (tempExists) {
|
||||
const { stream } = await this.storageProvider.getStream(session.tempStorageKey);
|
||||
await this.storageProvider.putStream(finalStorageKey, stream, Number(session.totalSizeBytes), session.mimeType);
|
||||
await this.storageProvider.delete(session.tempStorageKey);
|
||||
}
|
||||
|
||||
const initialStatus = session.fileCategory === FileCategory.VIDEO ? FileStatus.PROCESSING : FileStatus.READY;
|
||||
|
||||
const fileAsset = await this.prisma.$transaction(async (tx) => {
|
||||
const file = await tx.fileAsset.create({
|
||||
data: {
|
||||
id: fileId,
|
||||
ownerId: session.ownerId,
|
||||
folderId: session.folderId,
|
||||
originalFilename: session.originalFilename,
|
||||
internalStorageKey: finalStorageKey,
|
||||
mimeType: session.mimeType,
|
||||
fileExtension: extension,
|
||||
fileSizeBytes: session.totalSizeBytes,
|
||||
fileCategory: session.fileCategory,
|
||||
status: initialStatus,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.user.update({
|
||||
where: { id: session.ownerId },
|
||||
data: { storageUsedBytes: { increment: session.totalSizeBytes } },
|
||||
});
|
||||
|
||||
await tx.uploadSession.update({
|
||||
where: { id: sessionId },
|
||||
data: { status: UploadSessionStatus.COMPLETED },
|
||||
});
|
||||
|
||||
return file;
|
||||
});
|
||||
|
||||
if (session.fileCategory === FileCategory.VIDEO) {
|
||||
await this.videoQueueService.enqueueVideoProcessing(fileAsset.id);
|
||||
}
|
||||
|
||||
return fileAsset;
|
||||
}
|
||||
|
||||
/**
|
||||
* List files for a user with search and filtering
|
||||
*/
|
||||
async getUserFiles(
|
||||
userId: string,
|
||||
userRole: string,
|
||||
params: {
|
||||
folderId?: string;
|
||||
category?: FileCategory;
|
||||
search?: string;
|
||||
page?: number;
|
||||
limit?: number;
|
||||
sortBy?: 'name' | 'date' | 'size';
|
||||
sortOrder?: 'asc' | 'desc';
|
||||
},
|
||||
) {
|
||||
const page = params.page || 1;
|
||||
const limit = params.limit || 50;
|
||||
const skip = (page - 1) * limit;
|
||||
|
||||
const where: any = {
|
||||
ownerId: userId,
|
||||
isSoftDeleted: false,
|
||||
};
|
||||
|
||||
if (params.folderId) {
|
||||
where.folderId = params.folderId;
|
||||
}
|
||||
if (params.category) {
|
||||
where.fileCategory = params.category;
|
||||
}
|
||||
if (params.search) {
|
||||
where.originalFilename = { contains: params.search };
|
||||
}
|
||||
|
||||
let orderBy: any = { createdAt: 'desc' };
|
||||
if (params.sortBy === 'name') {
|
||||
orderBy = { originalFilename: params.sortOrder || 'asc' };
|
||||
} else if (params.sortBy === 'size') {
|
||||
orderBy = { fileSizeBytes: params.sortOrder || 'desc' };
|
||||
} else if (params.sortBy === 'date') {
|
||||
orderBy = { createdAt: params.sortOrder || 'desc' };
|
||||
}
|
||||
|
||||
const [total, files] = await Promise.all([
|
||||
this.prisma.fileAsset.count({ where }),
|
||||
this.prisma.fileAsset.findMany({
|
||||
where,
|
||||
take: limit,
|
||||
skip,
|
||||
orderBy,
|
||||
include: {
|
||||
owner: { select: { id: true, username: true, fullName: true, email: true } },
|
||||
folder: { select: { id: true, name: true, logicalPath: true } },
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
const enriched = await Promise.all(
|
||||
files.map(async (f) => {
|
||||
const perms = await this.permissionsService.getEffectiveFilePermissions(userId, userRole, f);
|
||||
return {
|
||||
id: f.id,
|
||||
ownerId: f.ownerId,
|
||||
ownerName: f.owner.fullName,
|
||||
ownerEmail: f.owner.email,
|
||||
folderId: f.folderId,
|
||||
folderName: f.folder?.name || 'Root',
|
||||
originalFilename: f.originalFilename,
|
||||
mimeType: f.mimeType,
|
||||
fileExtension: f.fileExtension,
|
||||
fileSizeBytes: f.fileSizeBytes.toString(),
|
||||
fileCategory: f.fileCategory,
|
||||
status: f.status,
|
||||
durationSeconds: f.durationSeconds,
|
||||
width: f.width,
|
||||
height: f.height,
|
||||
videoCodec: f.videoCodec,
|
||||
audioCodec: f.audioCodec,
|
||||
hasThumbnail: !!f.thumbnailStorageKey,
|
||||
hasHlsStream: !!f.hlsMasterPlaylistKey,
|
||||
createdAt: f.createdAt,
|
||||
updatedAt: f.updatedAt,
|
||||
permissions: perms,
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
return { total, page, limit, files: enriched };
|
||||
}
|
||||
|
||||
/**
|
||||
* Get file metadata and authorization details
|
||||
*/
|
||||
async getFileById(userId: string, userRole: string, fileId: string) {
|
||||
const file = await this.permissionsService.enforceFileAccess(
|
||||
userId,
|
||||
userRole,
|
||||
fileId,
|
||||
'canViewMetadata',
|
||||
);
|
||||
|
||||
const owner = await this.prisma.user.findUnique({
|
||||
where: { id: file.ownerId },
|
||||
select: { id: true, username: true, fullName: true, email: true },
|
||||
});
|
||||
|
||||
const perms = await this.permissionsService.getEffectiveFilePermissions(userId, userRole, file);
|
||||
|
||||
return {
|
||||
id: file.id,
|
||||
ownerId: file.ownerId,
|
||||
ownerName: owner?.fullName,
|
||||
ownerEmail: owner?.email,
|
||||
folderId: file.folderId,
|
||||
originalFilename: file.originalFilename,
|
||||
mimeType: file.mimeType,
|
||||
fileExtension: file.fileExtension,
|
||||
fileSizeBytes: file.fileSizeBytes.toString(),
|
||||
fileCategory: file.fileCategory,
|
||||
status: file.status,
|
||||
durationSeconds: file.durationSeconds,
|
||||
width: file.width,
|
||||
height: file.height,
|
||||
videoCodec: file.videoCodec,
|
||||
audioCodec: file.audioCodec,
|
||||
hasThumbnail: !!file.thumbnailStorageKey,
|
||||
hasHlsStream: !!file.hlsMasterPlaylistKey,
|
||||
createdAt: file.createdAt,
|
||||
updatedAt: file.updatedAt,
|
||||
permissions: perms,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare file stream for Download
|
||||
*/
|
||||
async getFileForDownload(
|
||||
userId: string,
|
||||
userRole: string,
|
||||
fileId: string,
|
||||
ipAddress?: string,
|
||||
userAgent?: string,
|
||||
) {
|
||||
// Strictly enforces canDownload permission
|
||||
const file = await this.permissionsService.enforceFileAccess(
|
||||
userId,
|
||||
userRole,
|
||||
fileId,
|
||||
'canDownload',
|
||||
);
|
||||
|
||||
const { stream, contentLength, contentType } = await this.storageProvider.getStream(
|
||||
file.internalStorageKey,
|
||||
);
|
||||
|
||||
await this.auditService.log({
|
||||
actorUserId: userId,
|
||||
action: 'FILE_DOWNLOADED',
|
||||
resourceType: 'FILE',
|
||||
resourceId: file.id,
|
||||
targetUserId: file.ownerId,
|
||||
ipAddress,
|
||||
userAgent,
|
||||
details: { filename: file.originalFilename, size: file.fileSizeBytes.toString() },
|
||||
});
|
||||
|
||||
return {
|
||||
stream,
|
||||
filename: file.originalFilename,
|
||||
contentType: file.mimeType || contentType,
|
||||
contentLength,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare file stream for Inline Preview
|
||||
*/
|
||||
async getFileForPreview(userId: string, userRole: string, fileId: string) {
|
||||
// Strictly enforces canPreview permission
|
||||
const file = await this.permissionsService.enforceFileAccess(
|
||||
userId,
|
||||
userRole,
|
||||
fileId,
|
||||
'canPreview',
|
||||
);
|
||||
|
||||
const { stream, contentLength, contentType } = await this.storageProvider.getStream(
|
||||
file.internalStorageKey,
|
||||
);
|
||||
|
||||
return {
|
||||
stream,
|
||||
filename: file.originalFilename,
|
||||
contentType: file.mimeType || contentType,
|
||||
contentLength,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Rename file
|
||||
*/
|
||||
async renameFile(userId: string, userRole: string, fileId: string, dto: RenameFileDto) {
|
||||
const file = await this.prisma.fileAsset.findUnique({ where: { id: fileId } });
|
||||
if (!file || file.isSoftDeleted) {
|
||||
throw new NotFoundException('File not found');
|
||||
}
|
||||
|
||||
if (file.ownerId !== userId && userRole !== UserRole.SUPER_ADMIN && userRole !== UserRole.ADMIN) {
|
||||
throw new ForbiddenException('Only the file owner or administrator can rename this file');
|
||||
}
|
||||
|
||||
const clean = StoragePathUtils.sanitizeFilename(dto.newFilename);
|
||||
const updated = await this.prisma.fileAsset.update({
|
||||
where: { id: fileId },
|
||||
data: { originalFilename: clean },
|
||||
});
|
||||
|
||||
await this.auditService.log({
|
||||
actorUserId: userId,
|
||||
action: 'FILE_RENAMED',
|
||||
resourceType: 'FILE',
|
||||
resourceId: fileId,
|
||||
details: { oldName: file.originalFilename, newName: clean },
|
||||
});
|
||||
|
||||
return updated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Move file to another folder
|
||||
*/
|
||||
async moveFile(userId: string, userRole: string, fileId: string, dto: MoveFileDto) {
|
||||
const file = await this.prisma.fileAsset.findUnique({ where: { id: fileId } });
|
||||
if (!file || file.isSoftDeleted) {
|
||||
throw new NotFoundException('File not found');
|
||||
}
|
||||
|
||||
if (file.ownerId !== userId && userRole !== UserRole.SUPER_ADMIN && userRole !== UserRole.ADMIN) {
|
||||
throw new ForbiddenException('Only the file owner or administrator can move this file');
|
||||
}
|
||||
|
||||
let targetFolderId: string | null = null;
|
||||
if (dto.targetFolderId && dto.targetFolderId !== 'root') {
|
||||
const folder = await this.prisma.folder.findUnique({ where: { id: dto.targetFolderId } });
|
||||
if (!folder || folder.ownerId !== file.ownerId) {
|
||||
throw new NotFoundException('Destination folder not found or does not belong to owner');
|
||||
}
|
||||
targetFolderId = folder.id;
|
||||
} else {
|
||||
const rootFolder = await this.prisma.folder.findFirst({
|
||||
where: { ownerId: file.ownerId, parentId: null },
|
||||
});
|
||||
targetFolderId = rootFolder?.id || null;
|
||||
}
|
||||
|
||||
const updated = await this.prisma.fileAsset.update({
|
||||
where: { id: fileId },
|
||||
data: { folderId: targetFolderId },
|
||||
});
|
||||
|
||||
await this.auditService.log({
|
||||
actorUserId: userId,
|
||||
action: 'FILE_MOVED',
|
||||
resourceType: 'FILE',
|
||||
resourceId: fileId,
|
||||
details: { targetFolderId },
|
||||
});
|
||||
|
||||
return updated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Soft-delete file (recycle bin)
|
||||
*/
|
||||
async deleteFile(userId: string, userRole: string, userCompanyName: string | undefined, fileId: string) {
|
||||
const file = await this.prisma.fileAsset.findUnique({
|
||||
where: { id: fileId },
|
||||
include: { owner: { select: { id: true, companyName: true } } },
|
||||
});
|
||||
if (!file || file.isSoftDeleted) {
|
||||
throw new NotFoundException('File not found or already deleted');
|
||||
}
|
||||
|
||||
const isSuperAdmin = userRole === UserRole.SUPER_ADMIN || userRole === 'SUPER_ADMIN';
|
||||
const isAdmin = userRole === UserRole.ADMIN || userRole === 'ADMIN';
|
||||
|
||||
if (isSuperAdmin) {
|
||||
// Super Admin has full unrestricted permission to delete any file across all companies
|
||||
} else if (isAdmin) {
|
||||
// Admin cannot delete files belonging to other companies
|
||||
const adminCompany = (userCompanyName || 'Ecohub').trim().toLowerCase();
|
||||
const fileCompany = (file.owner?.companyName || 'Ecohub').trim().toLowerCase();
|
||||
if (adminCompany !== fileCompany) {
|
||||
throw new ForbiddenException(
|
||||
'Administrators cannot delete files belonging to other companies. Only Super Admin has this permission.',
|
||||
);
|
||||
}
|
||||
} else {
|
||||
// Regular user: can only delete their own files
|
||||
if (file.ownerId !== userId) {
|
||||
throw new ForbiddenException('Only the file owner or administrator can delete this file');
|
||||
}
|
||||
|
||||
const user = await this.prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { canDeleteFiles: true },
|
||||
});
|
||||
if (!user?.canDeleteFiles) {
|
||||
throw new ForbiddenException('You do not have permission to delete files. Please contact an administrator.');
|
||||
}
|
||||
}
|
||||
|
||||
// Soft delete and deduct from user's storage quota
|
||||
await this.prisma.$transaction([
|
||||
this.prisma.fileAsset.update({
|
||||
where: { id: fileId },
|
||||
data: { isSoftDeleted: true, deletedAt: new Date() },
|
||||
}),
|
||||
this.prisma.user.update({
|
||||
where: { id: file.ownerId },
|
||||
data: { storageUsedBytes: { decrement: file.fileSizeBytes } },
|
||||
}),
|
||||
]);
|
||||
|
||||
await this.auditService.log({
|
||||
actorUserId: userId,
|
||||
action: 'FILE_SOFT_DELETED',
|
||||
resourceType: 'FILE',
|
||||
resourceId: fileId,
|
||||
targetUserId: file.ownerId,
|
||||
details: { filename: file.originalFilename, sizeBytes: file.fileSizeBytes.toString() },
|
||||
});
|
||||
|
||||
return { success: true, message: 'File moved to trash successfully' };
|
||||
}
|
||||
|
||||
/**
|
||||
* Get files shared with the current user ("Shared With Me")
|
||||
*/
|
||||
async getSharedWithMe(userId: string) {
|
||||
const now = new Date();
|
||||
|
||||
// 1. Find all active permissions granted to this user
|
||||
const permissions = await this.prisma.filePermission.findMany({
|
||||
where: {
|
||||
granteeUserId: userId,
|
||||
revokedAt: null,
|
||||
OR: [{ expiresAt: null }, { expiresAt: { gt: now } }],
|
||||
},
|
||||
include: {
|
||||
owner: { select: { id: true, username: true, fullName: true, email: true } },
|
||||
},
|
||||
});
|
||||
|
||||
if (permissions.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// Collect file IDs and folder IDs
|
||||
const directFileIds = permissions
|
||||
.filter((p) => p.resourceType === PermissionResourceType.FILE && p.resourceId)
|
||||
.map((p) => p.resourceId as string);
|
||||
|
||||
const folderIds = permissions
|
||||
.filter((p) => p.resourceType === PermissionResourceType.FOLDER && p.resourceId)
|
||||
.map((p) => p.resourceId as string);
|
||||
|
||||
const broadOwnerIds = permissions
|
||||
.filter((p) => p.resourceType === PermissionResourceType.USER_FILES)
|
||||
.map((p) => p.ownerId);
|
||||
|
||||
// Fetch matching files
|
||||
const files = await this.prisma.fileAsset.findMany({
|
||||
where: {
|
||||
isSoftDeleted: false,
|
||||
OR: [
|
||||
{ id: { in: directFileIds } },
|
||||
{ folderId: { in: folderIds } },
|
||||
{ ownerId: { in: broadOwnerIds } },
|
||||
],
|
||||
},
|
||||
include: {
|
||||
owner: { select: { id: true, username: true, fullName: true, email: true } },
|
||||
folder: { select: { id: true, name: true, logicalPath: true } },
|
||||
},
|
||||
});
|
||||
|
||||
const results = await Promise.all(
|
||||
files.map(async (file) => {
|
||||
const perms = await this.permissionsService.getEffectiveFilePermissions(
|
||||
userId,
|
||||
UserRole.USER,
|
||||
file,
|
||||
);
|
||||
return {
|
||||
id: file.id,
|
||||
ownerId: file.ownerId,
|
||||
ownerName: file.owner.fullName,
|
||||
ownerEmail: file.owner.email,
|
||||
folderId: file.folderId,
|
||||
folderName: file.folder?.name || 'Root',
|
||||
originalFilename: file.originalFilename,
|
||||
mimeType: file.mimeType,
|
||||
fileExtension: file.fileExtension,
|
||||
fileSizeBytes: file.fileSizeBytes.toString(),
|
||||
fileCategory: file.fileCategory,
|
||||
status: file.status,
|
||||
durationSeconds: file.durationSeconds,
|
||||
width: file.width,
|
||||
height: file.height,
|
||||
hasThumbnail: !!file.thumbnailStorageKey,
|
||||
hasHlsStream: !!file.hlsMasterPlaylistKey,
|
||||
createdAt: file.createdAt,
|
||||
permissions: perms,
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to dispatch or mirror uploaded file to remote file server link (User-specific or system-wide)
|
||||
*/
|
||||
private async dispatchToRemoteFileServer(fileAsset: any, buffer: Buffer): Promise<void> {
|
||||
try {
|
||||
// 1. Check user-specific remote file server configuration first
|
||||
const owner = await this.prisma.user.findUnique({
|
||||
where: { id: fileAsset.ownerId },
|
||||
select: {
|
||||
username: true,
|
||||
email: true,
|
||||
companyName: true,
|
||||
remoteFileServerUrl: true,
|
||||
canUseRemoteServer: true,
|
||||
},
|
||||
});
|
||||
|
||||
let targetRemoteUrl: string | null = null;
|
||||
let isUserSpecific = false;
|
||||
|
||||
if (owner?.canUseRemoteServer && owner?.remoteFileServerUrl && owner.remoteFileServerUrl.trim().length > 0) {
|
||||
targetRemoteUrl = owner.remoteFileServerUrl.trim();
|
||||
isUserSpecific = true;
|
||||
} else {
|
||||
// Fallback to global system setting
|
||||
const setting = await this.prisma.systemSetting.findUnique({
|
||||
where: { key: 'REMOTE_FILE_SERVER_URL' },
|
||||
});
|
||||
if (setting && setting.value && setting.value.trim().length > 0) {
|
||||
targetRemoteUrl = setting.value.trim();
|
||||
isUserSpecific = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (targetRemoteUrl) {
|
||||
this.logger.log(
|
||||
`[Remote Dispatch] File ${fileAsset.originalFilename} dispatched to ${
|
||||
isUserSpecific ? `user (${owner?.username}) endpoint` : 'system global endpoint'
|
||||
}: ${targetRemoteUrl}`,
|
||||
);
|
||||
|
||||
await this.auditService.log({
|
||||
actorUserId: fileAsset.ownerId,
|
||||
action: 'REMOTE_FILE_SERVER_SYNC_DISPATCHED',
|
||||
resourceType: 'FILE',
|
||||
resourceId: fileAsset.id,
|
||||
details: {
|
||||
remoteUrl: targetRemoteUrl,
|
||||
isUserSpecific,
|
||||
ownerUsername: owner?.username,
|
||||
companyName: owner?.companyName,
|
||||
filename: fileAsset.originalFilename,
|
||||
sizeBytes: Number(fileAsset.fileSizeBytes),
|
||||
},
|
||||
});
|
||||
|
||||
// If HTTP/HTTPS endpoint, perform asynchronous POST dispatch in background
|
||||
if (targetRemoteUrl.startsWith('http://') || targetRemoteUrl.startsWith('https://')) {
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), 8000);
|
||||
|
||||
fetch(targetRemoteUrl, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Ecohub-User': owner?.username || '',
|
||||
'X-Ecohub-Company': owner?.companyName || 'Ecohub',
|
||||
'X-Ecohub-File-Id': fileAsset.id,
|
||||
'X-Ecohub-File-Name': encodeURIComponent(fileAsset.originalFilename),
|
||||
},
|
||||
body: JSON.stringify({
|
||||
fileId: fileAsset.id,
|
||||
originalFilename: fileAsset.originalFilename,
|
||||
fileSizeBytes: Number(fileAsset.fileSizeBytes),
|
||||
mimeType: fileAsset.mimeType,
|
||||
ownerId: fileAsset.ownerId,
|
||||
ownerUsername: owner?.username,
|
||||
companyName: owner?.companyName,
|
||||
dispatchedAt: new Date().toISOString(),
|
||||
}),
|
||||
signal: controller.signal,
|
||||
})
|
||||
.then((res) => {
|
||||
clearTimeout(timeoutId);
|
||||
this.logger.log(`[Remote Dispatch] Remote response status: ${res.status} for ${fileAsset.originalFilename}`);
|
||||
})
|
||||
.catch((err) => {
|
||||
clearTimeout(timeoutId);
|
||||
this.logger.warn(`[Remote Dispatch] Remote endpoint ping/dispatch warning: ${err.message}`);
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (err: any) {
|
||||
this.logger.warn(`Failed to dispatch to remote file server: ${err.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
19
apps/backend/src/modules/files/sharing.controller.ts
Normal file
19
apps/backend/src/modules/files/sharing.controller.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { Controller, Get, UseGuards } from '@nestjs/common';
|
||||
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
|
||||
import { FilesService } from './files.service';
|
||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||
import { CurrentUser, AuthenticatedUser } from '../auth/decorators/current-user.decorator';
|
||||
|
||||
@ApiTags('Sharing')
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Controller('sharing')
|
||||
export class SharingController {
|
||||
constructor(private readonly filesService: FilesService) {}
|
||||
|
||||
@Get('shared-with-me')
|
||||
@ApiOperation({ summary: 'List all files and folders shared with the current user' })
|
||||
async getSharedWithMe(@CurrentUser() user: AuthenticatedUser) {
|
||||
return this.filesService.getSharedWithMe(user.id);
|
||||
}
|
||||
}
|
||||
29
apps/backend/src/modules/folders/dto/folder.dto.ts
Normal file
29
apps/backend/src/modules/folders/dto/folder.dto.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { IsNotEmpty, IsOptional, IsString, Matches, MaxLength } from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export class CreateFolderDto {
|
||||
@ApiProperty({ example: 'My Projects', description: 'Folder name' })
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
@MaxLength(100)
|
||||
@Matches(/^[^<>:"/\\|?*]+$/, {
|
||||
message: 'Folder name contains invalid characters',
|
||||
})
|
||||
name: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 'uuid-of-parent-folder', description: 'Parent folder ID (null for root)' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
parentId?: string;
|
||||
}
|
||||
|
||||
export class RenameFolderDto {
|
||||
@ApiProperty({ example: 'New Name' })
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
@MaxLength(100)
|
||||
@Matches(/^[^<>:"/\\|?*]+$/, {
|
||||
message: 'Folder name contains invalid characters',
|
||||
})
|
||||
name: string;
|
||||
}
|
||||
88
apps/backend/src/modules/folders/folders.controller.ts
Normal file
88
apps/backend/src/modules/folders/folders.controller.ts
Normal file
@@ -0,0 +1,88 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Patch,
|
||||
Delete,
|
||||
Body,
|
||||
Param,
|
||||
Query,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags, ApiOperation, ApiBearerAuth, ApiQuery } from '@nestjs/swagger';
|
||||
import { FoldersService } from './folders.service';
|
||||
import { CreateFolderDto, RenameFolderDto } from './dto/folder.dto';
|
||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||
import { CurrentUser, AuthenticatedUser } from '../auth/decorators/current-user.decorator';
|
||||
|
||||
@ApiTags('Folders')
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Controller('folders')
|
||||
export class FoldersController {
|
||||
constructor(private readonly foldersService: FoldersService) {}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: 'Get current user folder tree' })
|
||||
async getUserFolders(@CurrentUser() user: AuthenticatedUser) {
|
||||
return this.foldersService.getUserFolders(user.id);
|
||||
}
|
||||
|
||||
@Get('contents')
|
||||
@ApiOperation({ summary: 'Browse folder contents, breadcrumbs, subfolders and files' })
|
||||
@ApiQuery({ name: 'folderId', required: false, description: 'Folder ID or leave empty for Root' })
|
||||
async getFolderContents(
|
||||
@Query('folderId') folderId: string,
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
) {
|
||||
return this.foldersService.getFolderContents(user.id, user.role, folderId);
|
||||
}
|
||||
|
||||
@Get('explorer')
|
||||
@ApiOperation({ summary: 'Universal file explorer grouped by Company Name' })
|
||||
@ApiQuery({ name: 'companyName', required: false, description: 'Filter by specific company name' })
|
||||
@ApiQuery({ name: 'folderId', required: false, description: 'Folder ID inside company' })
|
||||
async getCompanyExplorer(
|
||||
@Query('companyName') companyName: string,
|
||||
@Query('folderId') folderId: string,
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
) {
|
||||
return this.foldersService.getCompanyExplorer(
|
||||
user.id,
|
||||
user.role,
|
||||
user.canViewOtherUsers,
|
||||
user.companyName,
|
||||
user.allowedCompanies,
|
||||
companyName,
|
||||
folderId,
|
||||
);
|
||||
}
|
||||
|
||||
@Post()
|
||||
@ApiOperation({ summary: 'Create a new subfolder' })
|
||||
async createFolder(
|
||||
@Body() dto: CreateFolderDto,
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
) {
|
||||
return this.foldersService.createFolder(user.id, user.role, dto);
|
||||
}
|
||||
|
||||
@Patch(':id')
|
||||
@ApiOperation({ summary: 'Rename a folder' })
|
||||
async renameFolder(
|
||||
@Param('id') id: string,
|
||||
@Body() dto: RenameFolderDto,
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
) {
|
||||
return this.foldersService.renameFolder(user.id, user.role, id, dto);
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@ApiOperation({ summary: 'Delete a folder and soft-delete contained files' })
|
||||
async deleteFolder(
|
||||
@Param('id') id: string,
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
) {
|
||||
return this.foldersService.deleteFolder(user.id, user.role, user.companyName, id);
|
||||
}
|
||||
}
|
||||
10
apps/backend/src/modules/folders/folders.module.ts
Normal file
10
apps/backend/src/modules/folders/folders.module.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { FoldersService } from './folders.service';
|
||||
import { FoldersController } from './folders.controller';
|
||||
|
||||
@Module({
|
||||
controllers: [FoldersController],
|
||||
providers: [FoldersService],
|
||||
exports: [FoldersService],
|
||||
})
|
||||
export class FoldersModule {}
|
||||
596
apps/backend/src/modules/folders/folders.service.ts
Normal file
596
apps/backend/src/modules/folders/folders.service.ts
Normal file
@@ -0,0 +1,596 @@
|
||||
import {
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
ForbiddenException,
|
||||
ConflictException,
|
||||
BadRequestException,
|
||||
} from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { PermissionsService } from '../permissions/permissions.service';
|
||||
import { AuditService } from '../audit/audit.service';
|
||||
import { CreateFolderDto, RenameFolderDto } from './dto/folder.dto';
|
||||
import { UserRole, UserStatus } from '@prisma/client';
|
||||
|
||||
@Injectable()
|
||||
export class FoldersService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly permissionsService: PermissionsService,
|
||||
private readonly auditService: AuditService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Get or create the root folder for a user
|
||||
*/
|
||||
async getOrCreateRootFolder(userId: string) {
|
||||
let root = await this.prisma.folder.findFirst({
|
||||
where: { ownerId: userId, parentId: null, name: 'Root' },
|
||||
});
|
||||
|
||||
if (!root) {
|
||||
root = await this.prisma.folder.create({
|
||||
data: {
|
||||
ownerId: userId,
|
||||
parentId: null,
|
||||
name: 'Root',
|
||||
logicalPath: '/',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return root;
|
||||
}
|
||||
|
||||
/**
|
||||
* List all folders belonging to a user
|
||||
*/
|
||||
async getUserFolders(userId: string) {
|
||||
const folders = await this.prisma.folder.findMany({
|
||||
where: { ownerId: userId },
|
||||
orderBy: { name: 'asc' },
|
||||
include: {
|
||||
_count: {
|
||||
select: { files: { where: { isSoftDeleted: false } }, children: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return folders.map((f) => ({
|
||||
id: f.id,
|
||||
ownerId: f.ownerId,
|
||||
parentId: f.parentId,
|
||||
name: f.name,
|
||||
logicalPath: f.logicalPath,
|
||||
createdAt: f.createdAt,
|
||||
updatedAt: f.updatedAt,
|
||||
fileCount: f._count.files,
|
||||
subfolderCount: f._count.children,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get folder contents (breadcrumbs, subfolders, files)
|
||||
*/
|
||||
async getFolderContents(userId: string, userRole: string, folderId?: string) {
|
||||
let targetFolder;
|
||||
|
||||
if (!folderId || folderId === 'root') {
|
||||
targetFolder = await this.getOrCreateRootFolder(userId);
|
||||
} else {
|
||||
targetFolder = await this.permissionsService.enforceFolderAccess(userId, userRole, folderId);
|
||||
}
|
||||
|
||||
// Build breadcrumbs
|
||||
const breadcrumbs: { id: string; name: string }[] = [];
|
||||
let current: any = targetFolder;
|
||||
while (current) {
|
||||
breadcrumbs.unshift({ id: current.id, name: current.name });
|
||||
if (current.parentId) {
|
||||
current = await this.prisma.folder.findUnique({ where: { id: current.parentId } });
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Get subfolders
|
||||
const subfolders = await this.prisma.folder.findMany({
|
||||
where: { parentId: targetFolder.id },
|
||||
orderBy: { name: 'asc' },
|
||||
include: {
|
||||
_count: {
|
||||
select: { files: { where: { isSoftDeleted: false } }, children: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Get files in this folder
|
||||
const files = await this.prisma.fileAsset.findMany({
|
||||
where: {
|
||||
folderId: targetFolder.id,
|
||||
isSoftDeleted: false,
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
include: {
|
||||
owner: { select: { id: true, username: true, fullName: true, email: true, companyName: true } },
|
||||
},
|
||||
});
|
||||
|
||||
// Calculate permissions for the files
|
||||
const enrichedFiles = await Promise.all(
|
||||
files.map(async (file) => {
|
||||
const perms = await this.permissionsService.getEffectiveFilePermissions(
|
||||
userId,
|
||||
userRole,
|
||||
file,
|
||||
);
|
||||
return {
|
||||
id: file.id,
|
||||
ownerId: file.ownerId,
|
||||
ownerName: file.owner.fullName,
|
||||
ownerEmail: file.owner.email,
|
||||
ownerCompanyName: file.owner.companyName || 'Ecohub',
|
||||
folderId: file.folderId,
|
||||
originalFilename: file.originalFilename,
|
||||
mimeType: file.mimeType,
|
||||
fileExtension: file.fileExtension,
|
||||
fileSizeBytes: file.fileSizeBytes.toString(),
|
||||
fileCategory: file.fileCategory,
|
||||
status: file.status,
|
||||
durationSeconds: file.durationSeconds,
|
||||
width: file.width,
|
||||
height: file.height,
|
||||
videoCodec: file.videoCodec,
|
||||
audioCodec: file.audioCodec,
|
||||
hasHlsStream: !!file.hlsMasterPlaylistKey,
|
||||
createdAt: file.createdAt,
|
||||
updatedAt: file.updatedAt,
|
||||
permissions: perms,
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
currentFolder: {
|
||||
id: targetFolder.id,
|
||||
name: targetFolder.name,
|
||||
logicalPath: targetFolder.logicalPath,
|
||||
ownerId: targetFolder.ownerId,
|
||||
},
|
||||
breadcrumbs,
|
||||
subfolders: subfolders.map((f) => ({
|
||||
id: f.id,
|
||||
name: f.name,
|
||||
logicalPath: f.logicalPath,
|
||||
fileCount: f._count.files,
|
||||
subfolderCount: f._count.children,
|
||||
updatedAt: f.updatedAt,
|
||||
})),
|
||||
files: enrichedFiles,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new folder
|
||||
*/
|
||||
async createFolder(userId: string, userRole: string, dto: CreateFolderDto) {
|
||||
const isSuperOrAdmin =
|
||||
userRole === UserRole.SUPER_ADMIN ||
|
||||
userRole === 'SUPER_ADMIN' ||
|
||||
userRole === UserRole.ADMIN ||
|
||||
userRole === 'ADMIN';
|
||||
|
||||
let parentFolder;
|
||||
let targetOwnerId = userId;
|
||||
|
||||
if (dto.parentId && dto.parentId !== 'root') {
|
||||
parentFolder = await this.prisma.folder.findUnique({
|
||||
where: { id: dto.parentId },
|
||||
});
|
||||
if (!parentFolder) {
|
||||
throw new NotFoundException('Parent folder not found');
|
||||
}
|
||||
if (parentFolder.ownerId !== userId && !isSuperOrAdmin) {
|
||||
throw new ForbiddenException('Parent folder unauthorized');
|
||||
}
|
||||
targetOwnerId = parentFolder.ownerId;
|
||||
} else {
|
||||
parentFolder = await this.getOrCreateRootFolder(userId);
|
||||
}
|
||||
|
||||
// Check duplicate name in parent folder
|
||||
const existing = await this.prisma.folder.findFirst({
|
||||
where: {
|
||||
ownerId: targetOwnerId,
|
||||
parentId: parentFolder.id,
|
||||
name: dto.name.trim(),
|
||||
},
|
||||
});
|
||||
if (existing) {
|
||||
throw new ConflictException(`A folder named "${dto.name}" already exists in this directory`);
|
||||
}
|
||||
|
||||
const logicalPath = `${parentFolder.logicalPath === '/' ? '' : parentFolder.logicalPath}/${dto.name.trim()}`;
|
||||
|
||||
const newFolder = await this.prisma.folder.create({
|
||||
data: {
|
||||
ownerId: targetOwnerId,
|
||||
parentId: parentFolder.id,
|
||||
name: dto.name.trim(),
|
||||
logicalPath,
|
||||
},
|
||||
});
|
||||
|
||||
await this.auditService.log({
|
||||
actorUserId: userId,
|
||||
action: 'FOLDER_CREATED',
|
||||
resourceType: 'FOLDER',
|
||||
resourceId: newFolder.id,
|
||||
targetUserId: targetOwnerId,
|
||||
details: { name: newFolder.name, logicalPath: newFolder.logicalPath },
|
||||
});
|
||||
|
||||
return newFolder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rename folder
|
||||
*/
|
||||
async renameFolder(userId: string, userRole: string, folderId: string, dto: RenameFolderDto) {
|
||||
const folder = await this.prisma.folder.findUnique({ where: { id: folderId } });
|
||||
if (!folder) {
|
||||
throw new NotFoundException('Folder not found');
|
||||
}
|
||||
|
||||
const isSuperOrAdmin =
|
||||
userRole === UserRole.SUPER_ADMIN ||
|
||||
userRole === 'SUPER_ADMIN' ||
|
||||
userRole === UserRole.ADMIN ||
|
||||
userRole === 'ADMIN';
|
||||
|
||||
if (folder.ownerId !== userId && !isSuperOrAdmin) {
|
||||
throw new ForbiddenException('Unauthorized to rename this folder');
|
||||
}
|
||||
|
||||
if (folder.parentId === null) {
|
||||
throw new BadRequestException('Cannot rename the root folder');
|
||||
}
|
||||
|
||||
// Check duplicate name
|
||||
const existing = await this.prisma.folder.findFirst({
|
||||
where: {
|
||||
ownerId: folder.ownerId,
|
||||
parentId: folder.parentId,
|
||||
name: dto.name.trim(),
|
||||
NOT: { id: folderId },
|
||||
},
|
||||
});
|
||||
if (existing) {
|
||||
throw new ConflictException(`A folder named "${dto.name}" already exists in this directory`);
|
||||
}
|
||||
|
||||
const parent = await this.prisma.folder.findUnique({ where: { id: folder.parentId } });
|
||||
const logicalPath = `${parent?.logicalPath === '/' ? '' : parent?.logicalPath}/${dto.name.trim()}`;
|
||||
|
||||
const updated = await this.prisma.folder.update({
|
||||
where: { id: folderId },
|
||||
data: { name: dto.name.trim(), logicalPath },
|
||||
});
|
||||
|
||||
await this.auditService.log({
|
||||
actorUserId: userId,
|
||||
action: 'FOLDER_RENAMED',
|
||||
resourceType: 'FOLDER',
|
||||
resourceId: folderId,
|
||||
targetUserId: folder.ownerId,
|
||||
details: { oldName: folder.name, newName: updated.name },
|
||||
});
|
||||
|
||||
return updated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete folder
|
||||
*/
|
||||
async deleteFolder(userId: string, userRole: string, userCompanyName: string | undefined, folderId: string) {
|
||||
const folder = await this.prisma.folder.findUnique({
|
||||
where: { id: folderId },
|
||||
include: { owner: { select: { id: true, companyName: true } } },
|
||||
});
|
||||
if (!folder) {
|
||||
throw new NotFoundException('Folder not found');
|
||||
}
|
||||
|
||||
if (folder.parentId === null) {
|
||||
throw new BadRequestException('Cannot delete the root folder');
|
||||
}
|
||||
|
||||
const isSuperAdmin = userRole === UserRole.SUPER_ADMIN || userRole === 'SUPER_ADMIN';
|
||||
const isAdmin = userRole === UserRole.ADMIN || userRole === 'ADMIN';
|
||||
|
||||
if (isSuperAdmin) {
|
||||
// Super Admin has full unrestricted permission to delete any folder across all companies
|
||||
} else if (isAdmin) {
|
||||
// Admin cannot delete folders belonging to other companies
|
||||
const adminCompany = (userCompanyName || 'Ecohub').trim().toLowerCase();
|
||||
const folderCompany = (folder.owner?.companyName || 'Ecohub').trim().toLowerCase();
|
||||
if (adminCompany !== folderCompany) {
|
||||
throw new ForbiddenException(
|
||||
'Administrators cannot delete folders belonging to other companies. Only Super Admin has this permission.',
|
||||
);
|
||||
}
|
||||
} else {
|
||||
// Regular user: can only delete their own folder if permitted
|
||||
if (folder.ownerId !== userId) {
|
||||
throw new ForbiddenException('You can only delete your own folders');
|
||||
}
|
||||
const user = await this.prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { canDeleteFiles: true },
|
||||
});
|
||||
if (!user?.canDeleteFiles) {
|
||||
throw new ForbiddenException('You do not have permission to delete folders or files. Please contact an administrator.');
|
||||
}
|
||||
}
|
||||
|
||||
// Soft delete all files in this folder
|
||||
await this.prisma.fileAsset.updateMany({
|
||||
where: { folderId, isSoftDeleted: false },
|
||||
data: { isSoftDeleted: true, deletedAt: new Date() },
|
||||
});
|
||||
|
||||
await this.prisma.folder.delete({ where: { id: folderId } });
|
||||
|
||||
await this.auditService.log({
|
||||
actorUserId: userId,
|
||||
action: 'FOLDER_DELETED',
|
||||
resourceType: 'FOLDER',
|
||||
resourceId: folderId,
|
||||
targetUserId: folder.ownerId,
|
||||
details: { name: folder.name },
|
||||
});
|
||||
|
||||
return { success: true, message: 'Folder deleted successfully' };
|
||||
}
|
||||
|
||||
/**
|
||||
* Universal Company File Explorer
|
||||
* 1st level: User's Company Name folders
|
||||
* 2nd level: Inside Company -> Users & folders
|
||||
* 3rd level: Inside User Folder -> Subfolders & Files
|
||||
*/
|
||||
async getCompanyExplorer(
|
||||
userId: string,
|
||||
userRole: string,
|
||||
canViewOtherUsers?: boolean,
|
||||
userCompanyName?: string,
|
||||
allowedCompanies?: string | null,
|
||||
companyName?: string,
|
||||
folderId?: string,
|
||||
) {
|
||||
const isSuperAdmin = userRole === UserRole.SUPER_ADMIN || userRole === 'SUPER_ADMIN';
|
||||
const isAdmin = userRole === UserRole.ADMIN || userRole === 'ADMIN';
|
||||
const isSuperOrAdmin = isSuperAdmin || isAdmin;
|
||||
const myCompany = userCompanyName && userCompanyName.trim() ? userCompanyName.trim() : 'Ecohub';
|
||||
|
||||
// Parse list of companies the user is permitted to access
|
||||
let allowedCompanyList: string[] | '*' = '*';
|
||||
if (!isSuperOrAdmin) {
|
||||
if (allowedCompanies && allowedCompanies.trim() === '*') {
|
||||
allowedCompanyList = '*';
|
||||
} else if (allowedCompanies && allowedCompanies.trim()) {
|
||||
try {
|
||||
const raw = allowedCompanies.trim();
|
||||
if (raw.startsWith('[') && raw.endsWith(']')) {
|
||||
const parsed = JSON.parse(raw);
|
||||
if (Array.isArray(parsed)) {
|
||||
const set = new Set<string>(parsed.map((s) => String(s).trim()).filter(Boolean));
|
||||
set.add(myCompany);
|
||||
allowedCompanyList = Array.from(set);
|
||||
}
|
||||
} else {
|
||||
const list = raw.split(',').map((s) => s.trim()).filter(Boolean);
|
||||
if (!list.some((c) => c.toLowerCase() === myCompany.toLowerCase())) {
|
||||
list.push(myCompany);
|
||||
}
|
||||
allowedCompanyList = list;
|
||||
}
|
||||
} catch {
|
||||
allowedCompanyList = [myCompany];
|
||||
}
|
||||
} else {
|
||||
// By default, a non-admin only has access to their own company
|
||||
allowedCompanyList = [myCompany];
|
||||
}
|
||||
}
|
||||
|
||||
const canAccessCompany = (targetComp: string) => {
|
||||
if (isSuperOrAdmin || allowedCompanyList === '*') return true;
|
||||
const target = targetComp.trim().toLowerCase();
|
||||
return (allowedCompanyList as string[]).some((c) => c.toLowerCase() === target);
|
||||
};
|
||||
|
||||
const hasMultiCompanyAccess = isSuperOrAdmin || allowedCompanyList === '*' || (Array.isArray(allowedCompanyList) && allowedCompanyList.length > 1);
|
||||
|
||||
// Case 1: Specific folderId is requested -> Browse that folder with company breadcrumbs
|
||||
if (folderId && folderId !== 'root') {
|
||||
const contents = await this.getFolderContents(userId, userRole, folderId);
|
||||
const targetFolderOwner = await this.prisma.user.findUnique({
|
||||
where: { id: contents.currentFolder.ownerId },
|
||||
select: { id: true, fullName: true, companyName: true },
|
||||
});
|
||||
|
||||
const compName = targetFolderOwner?.companyName || 'Ecohub';
|
||||
|
||||
// Security check: Only allow access if user owns the folder or has access to this company
|
||||
if (targetFolderOwner?.id !== userId && !canAccessCompany(compName)) {
|
||||
throw new ForbiddenException(`You do not have permission to access folders from "${compName}" organization.`);
|
||||
}
|
||||
|
||||
const explorerBreadcrumbs = hasMultiCompanyAccess
|
||||
? [
|
||||
{ id: '', name: 'Organizations & Companies' },
|
||||
{ id: compName, name: compName, isCompany: true },
|
||||
...contents.breadcrumbs,
|
||||
]
|
||||
: [
|
||||
{ id: compName, name: compName, isCompany: true },
|
||||
...contents.breadcrumbs,
|
||||
];
|
||||
|
||||
return {
|
||||
level: 'FOLDER_CONTENTS' as const,
|
||||
companyName: compName,
|
||||
currentFolder: contents.currentFolder,
|
||||
breadcrumbs: explorerBreadcrumbs,
|
||||
subfolders: contents.subfolders,
|
||||
files: contents.files,
|
||||
};
|
||||
}
|
||||
|
||||
// Case 2: Specific Company is selected -> List Users & their root folders in that company
|
||||
if (companyName && companyName.trim()) {
|
||||
const trimmedCompany = companyName.trim();
|
||||
if (!canAccessCompany(trimmedCompany)) {
|
||||
throw new ForbiddenException(`You do not have permission to access "${trimmedCompany}" organization.`);
|
||||
}
|
||||
|
||||
const userWhere: any = {
|
||||
companyName: trimmedCompany,
|
||||
status: UserStatus.ACTIVE,
|
||||
};
|
||||
|
||||
// If user does not have permission to view other users and is in this company, they only see themselves;
|
||||
// But if they have been granted access to this company or canViewOtherUsers or isSuperAdmin, they can see users in this company!
|
||||
if (!isSuperOrAdmin && !canViewOtherUsers && !canAccessCompany(trimmedCompany)) {
|
||||
userWhere.id = userId;
|
||||
}
|
||||
|
||||
const usersInCompany = await this.prisma.user.findMany({
|
||||
where: userWhere,
|
||||
include: {
|
||||
folders: {
|
||||
where: { parentId: null },
|
||||
include: {
|
||||
_count: {
|
||||
select: {
|
||||
files: { where: { isSoftDeleted: false } },
|
||||
children: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
files: {
|
||||
where: { isSoftDeleted: false },
|
||||
select: { id: true, fileSizeBytes: true },
|
||||
},
|
||||
},
|
||||
orderBy: { fullName: 'asc' },
|
||||
});
|
||||
|
||||
const usersList = usersInCompany.map((u) => {
|
||||
const rootFolder = u.folders[0] || null;
|
||||
const totalSize = u.files.reduce((acc, f) => acc + BigInt(f.fileSizeBytes), BigInt(0));
|
||||
return {
|
||||
userId: u.id,
|
||||
username: u.username,
|
||||
fullName: u.fullName,
|
||||
role: u.role,
|
||||
rootFolderId: rootFolder ? rootFolder.id : null,
|
||||
rootFolderName: u.fullName,
|
||||
fileCount: u.files.length,
|
||||
folderCount: rootFolder ? rootFolder._count.children : 0,
|
||||
totalSizeBytes: totalSize.toString(),
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
level: 'COMPANY_USERS' as const,
|
||||
companyName: trimmedCompany,
|
||||
breadcrumbs: hasMultiCompanyAccess
|
||||
? [
|
||||
{ id: '', name: 'Organizations & Companies' },
|
||||
{ id: trimmedCompany, name: trimmedCompany, isCompany: true },
|
||||
]
|
||||
: [{ id: trimmedCompany, name: trimmedCompany, isCompany: true }],
|
||||
subfolders: usersList.map((u) => ({
|
||||
id: u.rootFolderId || u.userId,
|
||||
name: u.fullName,
|
||||
logicalPath: `/${trimmedCompany}/${u.username}`,
|
||||
fileCount: u.fileCount,
|
||||
subfolderCount: u.folderCount,
|
||||
isUserRoot: true,
|
||||
userId: u.userId,
|
||||
username: u.username,
|
||||
})),
|
||||
files: [],
|
||||
users: usersList,
|
||||
};
|
||||
}
|
||||
|
||||
// Case 3: Root Level -> Show Companies the user has permission to access
|
||||
const allUsers = await this.prisma.user.findMany({
|
||||
where: { status: UserStatus.ACTIVE },
|
||||
select: {
|
||||
id: true,
|
||||
companyName: true,
|
||||
fullName: true,
|
||||
files: {
|
||||
where: { isSoftDeleted: false },
|
||||
select: { id: true, fileSizeBytes: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const companyMap = new Map<string, { userCount: number; fileCount: number; totalSizeBytes: bigint }>();
|
||||
|
||||
for (const u of allUsers) {
|
||||
const comp = u.companyName && u.companyName.trim() ? u.companyName.trim() : 'Ecohub';
|
||||
|
||||
// Strictly filter out any company this user is not authorized to access!
|
||||
if (!canAccessCompany(comp)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const existing = companyMap.get(comp) || { userCount: 0, fileCount: 0, totalSizeBytes: BigInt(0) };
|
||||
existing.userCount += 1;
|
||||
existing.fileCount += u.files.length;
|
||||
for (const f of u.files) {
|
||||
existing.totalSizeBytes += BigInt(f.fileSizeBytes);
|
||||
}
|
||||
companyMap.set(comp, existing);
|
||||
}
|
||||
|
||||
// Ensure authorized companies appear in list even if not yet populated with files
|
||||
if (allowedCompanyList !== '*') {
|
||||
for (const allowedComp of allowedCompanyList) {
|
||||
if (!companyMap.has(allowedComp)) {
|
||||
companyMap.set(allowedComp, { userCount: 0, fileCount: 0, totalSizeBytes: BigInt(0) });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const companies = Array.from(companyMap.entries()).map(([name, stats]) => ({
|
||||
name,
|
||||
companyName: name,
|
||||
userCount: stats.userCount,
|
||||
fileCount: stats.fileCount,
|
||||
totalSizeBytes: stats.totalSizeBytes.toString(),
|
||||
})).sort((a, b) => a.name.localeCompare(b.name));
|
||||
|
||||
return {
|
||||
level: 'COMPANIES' as const,
|
||||
breadcrumbs: [{ id: '', name: 'Organizations & Companies' }],
|
||||
subfolders: companies.map((c) => ({
|
||||
id: `company:${c.name}`,
|
||||
name: c.name,
|
||||
logicalPath: `/${c.name}`,
|
||||
fileCount: c.fileCount,
|
||||
subfolderCount: c.userCount,
|
||||
isCompany: true,
|
||||
companyName: c.name,
|
||||
})),
|
||||
files: [],
|
||||
companies,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { IsNotEmpty, IsString, IsArray, IsOptional, IsBoolean, IsDateString } from 'class-validator';
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
|
||||
export class BatchGrantPermissionDto {
|
||||
@ApiProperty({ description: 'ID of user being granted permissions' })
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
granteeUserId: string;
|
||||
|
||||
@ApiProperty({ description: 'List of File Asset IDs to grant access to', required: false, type: [String] })
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
fileIds?: string[];
|
||||
|
||||
@ApiProperty({ description: 'Optional owner ID whose files are all being granted at once', required: false })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
grantAllFilesOfOwner?: string;
|
||||
|
||||
@ApiProperty({ default: true })
|
||||
@IsBoolean()
|
||||
canViewMetadata: boolean;
|
||||
|
||||
@ApiProperty({ default: false })
|
||||
@IsBoolean()
|
||||
canPreview: boolean;
|
||||
|
||||
@ApiProperty({ default: false })
|
||||
@IsBoolean()
|
||||
canPlay: boolean;
|
||||
|
||||
@ApiProperty({ default: false })
|
||||
@IsBoolean()
|
||||
canDownload: boolean;
|
||||
|
||||
@ApiProperty({ default: false })
|
||||
@IsBoolean()
|
||||
canListFolder: boolean;
|
||||
|
||||
@ApiProperty({ required: false })
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
expiresAt?: string;
|
||||
}
|
||||
81
apps/backend/src/modules/permissions/dto/permission.dto.ts
Normal file
81
apps/backend/src/modules/permissions/dto/permission.dto.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
import { IsBoolean, IsDateString, IsEnum, IsNotEmpty, IsOptional, IsString } from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { PermissionResourceType } from '@prisma/client';
|
||||
|
||||
export class GrantPermissionDto {
|
||||
@ApiProperty({ enum: PermissionResourceType, example: PermissionResourceType.FILE })
|
||||
@IsEnum(PermissionResourceType)
|
||||
resourceType: PermissionResourceType;
|
||||
|
||||
@ApiPropertyOptional({ example: 'uuid-of-file-or-folder', description: 'File ID or Folder ID (null for USER_FILES)' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
resourceId?: string;
|
||||
|
||||
@ApiProperty({ example: 'uuid-of-owner-user', description: 'Owner of the resource' })
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
ownerId: string;
|
||||
|
||||
@ApiProperty({ example: 'uuid-of-grantee-user', description: 'User receiving access' })
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
granteeUserId: string;
|
||||
|
||||
@ApiProperty({ default: true })
|
||||
@IsBoolean()
|
||||
canViewMetadata: boolean;
|
||||
|
||||
@ApiProperty({ default: false })
|
||||
@IsBoolean()
|
||||
canPreview: boolean;
|
||||
|
||||
@ApiProperty({ default: false })
|
||||
@IsBoolean()
|
||||
canPlay: boolean;
|
||||
|
||||
@ApiProperty({ default: false })
|
||||
@IsBoolean()
|
||||
canDownload: boolean;
|
||||
|
||||
@ApiProperty({ default: false })
|
||||
@IsBoolean()
|
||||
canListFolder: boolean;
|
||||
|
||||
@ApiPropertyOptional({ example: '2026-12-31T23:59:59Z' })
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
expiresAt?: string;
|
||||
}
|
||||
|
||||
export class UpdatePermissionDto {
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
canViewMetadata?: boolean;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
canPreview?: boolean;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
canPlay?: boolean;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
canDownload?: boolean;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
canListFolder?: boolean;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
expiresAt?: string;
|
||||
}
|
||||
105
apps/backend/src/modules/permissions/permissions.controller.ts
Normal file
105
apps/backend/src/modules/permissions/permissions.controller.ts
Normal file
@@ -0,0 +1,105 @@
|
||||
import {
|
||||
Controller,
|
||||
Post,
|
||||
Get,
|
||||
Patch,
|
||||
Delete,
|
||||
Param,
|
||||
Body,
|
||||
Query,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags, ApiOperation, ApiBearerAuth, ApiQuery } from '@nestjs/swagger';
|
||||
import { PermissionsService } from './permissions.service';
|
||||
import { GrantPermissionDto, UpdatePermissionDto } from './dto/permission.dto';
|
||||
import { BatchGrantPermissionDto } from './dto/batch-permission.dto';
|
||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||
import { RolesGuard } from '../auth/guards/roles.guard';
|
||||
import { Roles } from '../auth/decorators/roles.decorator';
|
||||
import { CurrentUser, AuthenticatedUser } from '../auth/decorators/current-user.decorator';
|
||||
import { UserRole, PermissionResourceType } from '@prisma/client';
|
||||
|
||||
@ApiTags('Admin - Permissions Management')
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles(UserRole.SUPER_ADMIN, UserRole.ADMIN)
|
||||
@Controller('admin/permissions')
|
||||
export class PermissionsController {
|
||||
constructor(private readonly permissionsService: PermissionsService) {}
|
||||
|
||||
@Post()
|
||||
@ApiOperation({ summary: 'Grant granular file, folder, or user-level permissions to another user' })
|
||||
async grantPermission(
|
||||
@Body() dto: GrantPermissionDto,
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
) {
|
||||
return this.permissionsService.grantPermission(dto, user.id);
|
||||
}
|
||||
|
||||
@Post('batch')
|
||||
@ApiOperation({ summary: 'Batch grant permissions across 1-by-1 selected files or all files of an owner' })
|
||||
async grantBatchPermissions(
|
||||
@Body() dto: BatchGrantPermissionDto,
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
) {
|
||||
return this.permissionsService.grantBatchPermissions(dto, user.id);
|
||||
}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: 'List and filter granted permissions across the system' })
|
||||
@ApiQuery({ name: 'ownerId', required: false })
|
||||
@ApiQuery({ name: 'granteeUserId', required: false })
|
||||
@ApiQuery({ name: 'resourceType', enum: PermissionResourceType, required: false })
|
||||
@ApiQuery({ name: 'activeOnly', required: false, type: Boolean })
|
||||
@ApiQuery({ name: 'page', required: false, type: Number })
|
||||
@ApiQuery({ name: 'limit', required: false, type: Number })
|
||||
async listPermissions(
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
@Query('ownerId') ownerId?: string,
|
||||
@Query('granteeUserId') granteeUserId?: string,
|
||||
@Query('resourceType') resourceType?: PermissionResourceType,
|
||||
@Query('activeOnly') activeOnly?: string,
|
||||
@Query('page') page?: string,
|
||||
@Query('limit') limit?: string,
|
||||
) {
|
||||
return this.permissionsService.listPermissions({
|
||||
ownerId,
|
||||
granteeUserId,
|
||||
resourceType,
|
||||
activeOnly: activeOnly === 'true',
|
||||
page: page ? parseInt(page, 10) : 1,
|
||||
limit: limit ? parseInt(limit, 10) : 50,
|
||||
requesterId: user.id,
|
||||
requesterRole: user.role,
|
||||
canViewOtherUsers: user.canViewOtherUsers,
|
||||
});
|
||||
}
|
||||
|
||||
@Patch(':id')
|
||||
@ApiOperation({ summary: 'Update an existing permission record' })
|
||||
async updatePermission(
|
||||
@Param('id') id: string,
|
||||
@Body() dto: UpdatePermissionDto,
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
) {
|
||||
return this.permissionsService.updatePermission(id, dto, user.id);
|
||||
}
|
||||
|
||||
@Post(':id/revoke')
|
||||
@ApiOperation({ summary: 'Revoke a permission immediately, denying subsequent access' })
|
||||
async revokePermission(
|
||||
@Param('id') id: string,
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
) {
|
||||
return this.permissionsService.revokePermission(id, user.id);
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@ApiOperation({ summary: 'Permanently remove a permission record' })
|
||||
async deletePermission(
|
||||
@Param('id') id: string,
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
) {
|
||||
return this.permissionsService.deletePermission(id, user.id);
|
||||
}
|
||||
}
|
||||
11
apps/backend/src/modules/permissions/permissions.module.ts
Normal file
11
apps/backend/src/modules/permissions/permissions.module.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { PermissionsService } from './permissions.service';
|
||||
import { PermissionsController } from './permissions.controller';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
controllers: [PermissionsController],
|
||||
providers: [PermissionsService],
|
||||
exports: [PermissionsService],
|
||||
})
|
||||
export class PermissionsModule {}
|
||||
529
apps/backend/src/modules/permissions/permissions.service.ts
Normal file
529
apps/backend/src/modules/permissions/permissions.service.ts
Normal file
@@ -0,0 +1,529 @@
|
||||
import {
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
ForbiddenException,
|
||||
BadRequestException,
|
||||
Logger,
|
||||
} from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { AuditService } from '../audit/audit.service';
|
||||
import { GrantPermissionDto, UpdatePermissionDto } from './dto/permission.dto';
|
||||
import { BatchGrantPermissionDto } from './dto/batch-permission.dto';
|
||||
import { UserRole, PermissionResourceType, FileAsset, Folder, FileCategory } from '@prisma/client';
|
||||
|
||||
export interface EffectiveFilePermissions {
|
||||
canViewMetadata: boolean;
|
||||
canPreview: boolean;
|
||||
canPlay: boolean;
|
||||
canDownload: boolean;
|
||||
canListFolder: boolean;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class PermissionsService {
|
||||
private readonly logger = new Logger(PermissionsService.name);
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly auditService: AuditService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Evaluate effective permissions for a user on a given file.
|
||||
*/
|
||||
async getEffectiveFilePermissions(
|
||||
userId: string,
|
||||
userRole: string,
|
||||
file: FileAsset,
|
||||
canViewOtherUsers?: boolean,
|
||||
): Promise<EffectiveFilePermissions> {
|
||||
const isSuperAdmin = userRole === UserRole.SUPER_ADMIN || userRole === 'SUPER_ADMIN';
|
||||
const isAdmin = userRole === UserRole.ADMIN || userRole === 'ADMIN';
|
||||
// 1. Super Admin, Admin, and authorized users with canViewOtherUsers have administrative access to download and play all files user-wise
|
||||
if (isSuperAdmin || isAdmin || canViewOtherUsers) {
|
||||
return {
|
||||
canViewMetadata: true,
|
||||
canPreview: true,
|
||||
canPlay: true,
|
||||
canDownload: true,
|
||||
canListFolder: true,
|
||||
};
|
||||
}
|
||||
|
||||
// 2. Owner permissions:
|
||||
// If the file is a VIDEO: normal user can watch/play it ("onno user sudu tar video e dekhte parbe"),
|
||||
// but CANNOT download unless an explicit permission has been granted by superadmin!
|
||||
if (file.ownerId === userId) {
|
||||
if (file.fileCategory === FileCategory.VIDEO) {
|
||||
// Check if there is an active explicit grant giving canDownload to this user
|
||||
const directGrant = await this.prisma.filePermission.findFirst({
|
||||
where: {
|
||||
granteeUserId: userId,
|
||||
revokedAt: null,
|
||||
canDownload: true,
|
||||
OR: [
|
||||
{ resourceType: PermissionResourceType.FILE, resourceId: file.id },
|
||||
{ resourceType: PermissionResourceType.USER_FILES, ownerId: file.ownerId },
|
||||
],
|
||||
AND: [
|
||||
{
|
||||
OR: [{ expiresAt: null }, { expiresAt: { gt: new Date() } }],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
canViewMetadata: true,
|
||||
canPreview: true,
|
||||
canPlay: true,
|
||||
canDownload: !!directGrant,
|
||||
canListFolder: true,
|
||||
};
|
||||
}
|
||||
|
||||
// Non-video files (documents, images, audio) can be downloaded by owner
|
||||
return {
|
||||
canViewMetadata: true,
|
||||
canPreview: true,
|
||||
canPlay: true,
|
||||
canDownload: true,
|
||||
canListFolder: true,
|
||||
};
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
|
||||
// 3. Collect all relevant permission candidates:
|
||||
// a) Direct File permission
|
||||
// b) Folder permission (if file belongs to a folder)
|
||||
// c) Broad user-level files permission
|
||||
const candidateConditions: any[] = [
|
||||
{
|
||||
resourceType: PermissionResourceType.FILE,
|
||||
resourceId: file.id,
|
||||
},
|
||||
{
|
||||
resourceType: PermissionResourceType.USER_FILES,
|
||||
ownerId: file.ownerId,
|
||||
},
|
||||
];
|
||||
|
||||
if (file.folderId) {
|
||||
candidateConditions.push({
|
||||
resourceType: PermissionResourceType.FOLDER,
|
||||
resourceId: file.folderId,
|
||||
});
|
||||
}
|
||||
|
||||
const permissions = await this.prisma.filePermission.findMany({
|
||||
where: {
|
||||
granteeUserId: userId,
|
||||
revokedAt: null,
|
||||
OR: candidateConditions,
|
||||
AND: [
|
||||
{
|
||||
OR: [{ expiresAt: null }, { expiresAt: { gt: now } }],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
if (permissions.length === 0) {
|
||||
return {
|
||||
canViewMetadata: false,
|
||||
canPreview: false,
|
||||
canPlay: false,
|
||||
canDownload: false,
|
||||
canListFolder: false,
|
||||
};
|
||||
}
|
||||
|
||||
// Aggregate permissions (any active grant that enables the action gives access)
|
||||
return {
|
||||
canViewMetadata: permissions.some((p) => p.canViewMetadata),
|
||||
canPreview: permissions.some((p) => p.canPreview),
|
||||
canPlay: permissions.some((p) => p.canPlay),
|
||||
canDownload: permissions.some((p) => p.canDownload),
|
||||
canListFolder: permissions.some((p) => p.canListFolder),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Enforce access to a file for a specific action
|
||||
*/
|
||||
async enforceFileAccess(
|
||||
userId: string,
|
||||
userRole: string,
|
||||
fileId: string,
|
||||
action: 'canViewMetadata' | 'canPreview' | 'canPlay' | 'canDownload',
|
||||
canViewOtherUsers?: boolean,
|
||||
): Promise<FileAsset> {
|
||||
const file = await this.prisma.fileAsset.findUnique({
|
||||
where: { id: fileId },
|
||||
});
|
||||
|
||||
if (!file || file.isSoftDeleted) {
|
||||
throw new NotFoundException('File not found or has been deleted');
|
||||
}
|
||||
|
||||
const perms = await this.getEffectiveFilePermissions(userId, userRole, file, canViewOtherUsers);
|
||||
|
||||
if (!perms[action]) {
|
||||
this.logger.warn(`Access denied: User ${userId} requested ${action} on file ${fileId}`);
|
||||
throw new ForbiddenException(`You do not have permission to perform this action (${action}) on this file`);
|
||||
}
|
||||
|
||||
// If Super Admin or Admin or authorized user accessed another user's file, audit the event
|
||||
const isSuperAdmin = userRole === UserRole.SUPER_ADMIN || userRole === 'SUPER_ADMIN';
|
||||
const isAdmin = userRole === UserRole.ADMIN || userRole === 'ADMIN';
|
||||
if ((isSuperAdmin || isAdmin || canViewOtherUsers) && file.ownerId !== userId) {
|
||||
await this.auditService.log({
|
||||
actorUserId: userId,
|
||||
action: `${isSuperAdmin ? 'SUPER_ADMIN' : 'ADMIN'}_ACCESSED_${action.toUpperCase()}`,
|
||||
resourceType: 'FILE',
|
||||
resourceId: file.id,
|
||||
targetUserId: file.ownerId,
|
||||
details: { filename: file.originalFilename },
|
||||
});
|
||||
}
|
||||
|
||||
return file;
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluate folder access
|
||||
*/
|
||||
async enforceFolderAccess(
|
||||
userId: string,
|
||||
userRole: string,
|
||||
folderId: string,
|
||||
canViewOtherUsers?: boolean,
|
||||
): Promise<Folder> {
|
||||
const folder = await this.prisma.folder.findUnique({
|
||||
where: { id: folderId },
|
||||
});
|
||||
|
||||
if (!folder) {
|
||||
throw new NotFoundException('Folder not found');
|
||||
}
|
||||
|
||||
const isSuperAdmin = userRole === UserRole.SUPER_ADMIN || userRole === 'SUPER_ADMIN';
|
||||
const isAdmin = userRole === UserRole.ADMIN || userRole === 'ADMIN';
|
||||
if (folder.ownerId === userId || isSuperAdmin || isAdmin || canViewOtherUsers) {
|
||||
return folder;
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const permission = await this.prisma.filePermission.findFirst({
|
||||
where: {
|
||||
granteeUserId: userId,
|
||||
revokedAt: null,
|
||||
OR: [
|
||||
{ resourceType: PermissionResourceType.FOLDER, resourceId: folderId },
|
||||
{ resourceType: PermissionResourceType.USER_FILES, ownerId: folder.ownerId },
|
||||
],
|
||||
AND: [
|
||||
{
|
||||
OR: [{ expiresAt: null }, { expiresAt: { gt: now } }],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
if (!permission || !permission.canListFolder) {
|
||||
throw new ForbiddenException('You do not have permission to access this folder');
|
||||
}
|
||||
|
||||
return folder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Grant permission (Admin / Super Admin action)
|
||||
*/
|
||||
async grantPermission(dto: GrantPermissionDto, grantedByUserId: string) {
|
||||
if (dto.ownerId === dto.granteeUserId) {
|
||||
throw new BadRequestException('Cannot grant permissions to the owner of the resource');
|
||||
}
|
||||
|
||||
// Verify owner and grantee exist
|
||||
const [owner, grantee] = await Promise.all([
|
||||
this.prisma.user.findUnique({ where: { id: dto.ownerId } }),
|
||||
this.prisma.user.findUnique({ where: { id: dto.granteeUserId } }),
|
||||
]);
|
||||
|
||||
if (!owner) throw new NotFoundException('Resource owner user not found');
|
||||
if (!grantee) throw new NotFoundException('Grantee user not found');
|
||||
|
||||
// Verify resource exists if specific ID provided
|
||||
if (dto.resourceType === PermissionResourceType.FILE && dto.resourceId) {
|
||||
const file = await this.prisma.fileAsset.findUnique({ where: { id: dto.resourceId } });
|
||||
if (!file || file.ownerId !== dto.ownerId) {
|
||||
throw new NotFoundException('Specified file does not exist or does not belong to the owner');
|
||||
}
|
||||
} else if (dto.resourceType === PermissionResourceType.FOLDER && dto.resourceId) {
|
||||
const folder = await this.prisma.folder.findUnique({ where: { id: dto.resourceId } });
|
||||
if (!folder || folder.ownerId !== dto.ownerId) {
|
||||
throw new NotFoundException('Specified folder does not exist or does not belong to the owner');
|
||||
}
|
||||
}
|
||||
|
||||
const permission = await this.prisma.filePermission.create({
|
||||
data: {
|
||||
resourceType: dto.resourceType,
|
||||
resourceId: dto.resourceId || null,
|
||||
ownerId: dto.ownerId,
|
||||
granteeUserId: dto.granteeUserId,
|
||||
grantedByUserId,
|
||||
canViewMetadata: dto.canViewMetadata,
|
||||
canPreview: dto.canPreview,
|
||||
canPlay: dto.canPlay,
|
||||
canDownload: dto.canDownload,
|
||||
canListFolder: dto.canListFolder,
|
||||
expiresAt: dto.expiresAt ? new Date(dto.expiresAt) : null,
|
||||
},
|
||||
include: {
|
||||
owner: { select: { id: true, username: true, email: true, fullName: true } },
|
||||
grantee: { select: { id: true, username: true, email: true, fullName: true } },
|
||||
grantedBy: { select: { id: true, username: true, email: true, fullName: true } },
|
||||
},
|
||||
});
|
||||
|
||||
await this.auditService.log({
|
||||
actorUserId: grantedByUserId,
|
||||
action: 'PERMISSION_GRANTED',
|
||||
resourceType: 'PERMISSION',
|
||||
resourceId: permission.id,
|
||||
targetUserId: dto.granteeUserId,
|
||||
details: {
|
||||
resourceType: dto.resourceType,
|
||||
resourceId: dto.resourceId,
|
||||
ownerId: dto.ownerId,
|
||||
canPlay: dto.canPlay,
|
||||
canDownload: dto.canDownload,
|
||||
canPreview: dto.canPreview,
|
||||
},
|
||||
});
|
||||
|
||||
return permission;
|
||||
}
|
||||
|
||||
/**
|
||||
* Batch Grant Permissions:
|
||||
* Super Admin / Admin can select 1-by-1 (fileIds) OR grant all files of an owner at once.
|
||||
*/
|
||||
async grantBatchPermissions(dto: BatchGrantPermissionDto, grantedByUserId: string) {
|
||||
const grantee = await this.prisma.user.findUnique({ where: { id: dto.granteeUserId } });
|
||||
if (!grantee) throw new NotFoundException('Grantee user not found');
|
||||
|
||||
const createdGrants: any[] = [];
|
||||
|
||||
// Mode A: Grant all files of owner at once
|
||||
if (dto.grantAllFilesOfOwner) {
|
||||
const userLevelPerm = await this.prisma.filePermission.create({
|
||||
data: {
|
||||
resourceType: PermissionResourceType.USER_FILES,
|
||||
resourceId: null,
|
||||
ownerId: dto.grantAllFilesOfOwner,
|
||||
granteeUserId: dto.granteeUserId,
|
||||
grantedByUserId,
|
||||
canViewMetadata: dto.canViewMetadata,
|
||||
canPreview: dto.canPreview,
|
||||
canPlay: dto.canPlay,
|
||||
canDownload: dto.canDownload,
|
||||
canListFolder: dto.canListFolder,
|
||||
expiresAt: dto.expiresAt ? new Date(dto.expiresAt) : null,
|
||||
},
|
||||
});
|
||||
createdGrants.push(userLevelPerm);
|
||||
}
|
||||
|
||||
// Mode B: Grant 1-by-1 or multi-selected files
|
||||
if (dto.fileIds && dto.fileIds.length > 0) {
|
||||
const files = await this.prisma.fileAsset.findMany({
|
||||
where: { id: { in: dto.fileIds }, isSoftDeleted: false },
|
||||
});
|
||||
|
||||
for (const file of files) {
|
||||
const filePerm = await this.prisma.filePermission.create({
|
||||
data: {
|
||||
resourceType: PermissionResourceType.FILE,
|
||||
resourceId: file.id,
|
||||
ownerId: file.ownerId,
|
||||
granteeUserId: dto.granteeUserId,
|
||||
grantedByUserId,
|
||||
canViewMetadata: dto.canViewMetadata,
|
||||
canPreview: dto.canPreview,
|
||||
canPlay: dto.canPlay,
|
||||
canDownload: dto.canDownload,
|
||||
canListFolder: dto.canListFolder,
|
||||
expiresAt: dto.expiresAt ? new Date(dto.expiresAt) : null,
|
||||
},
|
||||
});
|
||||
createdGrants.push(filePerm);
|
||||
}
|
||||
}
|
||||
|
||||
await this.auditService.log({
|
||||
actorUserId: grantedByUserId,
|
||||
action: 'BATCH_PERMISSIONS_GRANTED',
|
||||
resourceType: 'PERMISSION',
|
||||
targetUserId: dto.granteeUserId,
|
||||
details: {
|
||||
grantsCount: createdGrants.length,
|
||||
grantAllFilesOfOwner: dto.grantAllFilesOfOwner,
|
||||
fileCount: dto.fileIds?.length || 0,
|
||||
canDownload: dto.canDownload,
|
||||
canPlay: dto.canPlay,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
count: createdGrants.length,
|
||||
grants: createdGrants,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* List permissions with pagination and filters
|
||||
*/
|
||||
async listPermissions(params: {
|
||||
ownerId?: string;
|
||||
granteeUserId?: string;
|
||||
resourceType?: PermissionResourceType;
|
||||
activeOnly?: boolean;
|
||||
page?: number;
|
||||
limit?: number;
|
||||
requesterId?: string;
|
||||
requesterRole?: UserRole | string;
|
||||
canViewOtherUsers?: boolean;
|
||||
}) {
|
||||
const isSuperAdmin = params.requesterRole === UserRole.SUPER_ADMIN || params.requesterRole === 'SUPER_ADMIN';
|
||||
const canViewAll = isSuperAdmin || !!params.canViewOtherUsers;
|
||||
|
||||
const page = params.page || 1;
|
||||
const limit = params.limit || 50;
|
||||
const skip = (page - 1) * limit;
|
||||
|
||||
const where: any = {};
|
||||
if (params.ownerId) where.ownerId = params.ownerId;
|
||||
if (params.granteeUserId) where.granteeUserId = params.granteeUserId;
|
||||
if (params.resourceType) where.resourceType = params.resourceType;
|
||||
|
||||
if (!canViewAll && params.requesterId) {
|
||||
where.AND = [
|
||||
...(where.AND || []),
|
||||
{
|
||||
OR: [
|
||||
{ ownerId: params.requesterId },
|
||||
{ granteeUserId: params.requesterId },
|
||||
],
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (params.activeOnly) {
|
||||
const now = new Date();
|
||||
where.revokedAt = null;
|
||||
where.OR = [{ expiresAt: null }, { expiresAt: { gt: now } }];
|
||||
}
|
||||
|
||||
const [total, permissions] = await Promise.all([
|
||||
this.prisma.filePermission.count({ where }),
|
||||
this.prisma.filePermission.findMany({
|
||||
where,
|
||||
take: limit,
|
||||
skip,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
include: {
|
||||
owner: { select: { id: true, username: true, email: true, fullName: true } },
|
||||
grantee: { select: { id: true, username: true, email: true, fullName: true } },
|
||||
grantedBy: { select: { id: true, username: true, email: true, fullName: true } },
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
return { total, page, limit, permissions };
|
||||
}
|
||||
|
||||
/**
|
||||
* Update permission
|
||||
*/
|
||||
async updatePermission(id: string, dto: UpdatePermissionDto, updatedByUserId: string) {
|
||||
const existing = await this.prisma.filePermission.findUnique({ where: { id } });
|
||||
if (!existing) {
|
||||
throw new NotFoundException('Permission record not found');
|
||||
}
|
||||
|
||||
const updated = await this.prisma.filePermission.update({
|
||||
where: { id },
|
||||
data: {
|
||||
canViewMetadata: dto.canViewMetadata ?? existing.canViewMetadata,
|
||||
canPreview: dto.canPreview ?? existing.canPreview,
|
||||
canPlay: dto.canPlay ?? existing.canPlay,
|
||||
canDownload: dto.canDownload ?? existing.canDownload,
|
||||
canListFolder: dto.canListFolder ?? existing.canListFolder,
|
||||
expiresAt: dto.expiresAt !== undefined ? (dto.expiresAt ? new Date(dto.expiresAt) : null) : existing.expiresAt,
|
||||
},
|
||||
});
|
||||
|
||||
await this.auditService.log({
|
||||
actorUserId: updatedByUserId,
|
||||
action: 'PERMISSION_UPDATED',
|
||||
resourceType: 'PERMISSION',
|
||||
resourceId: id,
|
||||
targetUserId: existing.granteeUserId,
|
||||
details: dto,
|
||||
});
|
||||
|
||||
return updated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Revoke permission immediately
|
||||
*/
|
||||
async revokePermission(id: string, revokedByUserId: string) {
|
||||
const existing = await this.prisma.filePermission.findUnique({ where: { id } });
|
||||
if (!existing) {
|
||||
throw new NotFoundException('Permission record not found');
|
||||
}
|
||||
|
||||
const revoked = await this.prisma.filePermission.update({
|
||||
where: { id },
|
||||
data: { revokedAt: new Date() },
|
||||
});
|
||||
|
||||
await this.auditService.log({
|
||||
actorUserId: revokedByUserId,
|
||||
action: 'PERMISSION_REVOKED',
|
||||
resourceType: 'PERMISSION',
|
||||
resourceId: id,
|
||||
targetUserId: existing.granteeUserId,
|
||||
});
|
||||
|
||||
return revoked;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete permission record permanently
|
||||
*/
|
||||
async deletePermission(id: string, deletedByUserId: string) {
|
||||
const existing = await this.prisma.filePermission.findUnique({ where: { id } });
|
||||
if (!existing) {
|
||||
throw new NotFoundException('Permission record not found');
|
||||
}
|
||||
|
||||
await this.prisma.filePermission.delete({ where: { id } });
|
||||
|
||||
await this.auditService.log({
|
||||
actorUserId: deletedByUserId,
|
||||
action: 'PERMISSION_DELETED',
|
||||
resourceType: 'PERMISSION',
|
||||
resourceId: id,
|
||||
targetUserId: existing.granteeUserId,
|
||||
});
|
||||
|
||||
return { success: true, message: 'Permission record permanently deleted' };
|
||||
}
|
||||
}
|
||||
9
apps/backend/src/modules/prisma/prisma.module.ts
Normal file
9
apps/backend/src/modules/prisma/prisma.module.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { PrismaService } from './prisma.service';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [PrismaService],
|
||||
exports: [PrismaService],
|
||||
})
|
||||
export class PrismaModule {}
|
||||
13
apps/backend/src/modules/prisma/prisma.service.ts
Normal file
13
apps/backend/src/modules/prisma/prisma.service.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
|
||||
@Injectable()
|
||||
export class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy {
|
||||
async onModuleInit() {
|
||||
await this.$connect();
|
||||
}
|
||||
|
||||
async onModuleDestroy() {
|
||||
await this.$disconnect();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { IsEnum, IsOptional, IsString, IsBoolean, IsInt, Min } from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { ShareResourceType } from '@prisma/client';
|
||||
|
||||
export class CreateShareLinkDto {
|
||||
@ApiProperty({ enum: ShareResourceType, example: 'FILE' })
|
||||
@IsEnum(ShareResourceType)
|
||||
resourceType: ShareResourceType;
|
||||
|
||||
@ApiPropertyOptional({ example: 'uuid-of-file' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
fileId?: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 'uuid-of-folder' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
folderId?: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 'Project Demo Link' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
title?: string;
|
||||
|
||||
@ApiPropertyOptional({ example: true, default: true })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
allowDownload?: boolean;
|
||||
|
||||
@ApiPropertyOptional({ example: 'SecretPass123' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
password?: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 7, description: 'Expiry in days' })
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
expiresInDays?: number;
|
||||
}
|
||||
163
apps/backend/src/modules/share-links/share-links.controller.ts
Normal file
163
apps/backend/src/modules/share-links/share-links.controller.ts
Normal file
@@ -0,0 +1,163 @@
|
||||
import {
|
||||
Controller,
|
||||
Post,
|
||||
Get,
|
||||
Delete,
|
||||
Param,
|
||||
Body,
|
||||
Query,
|
||||
Headers,
|
||||
Req,
|
||||
Res,
|
||||
UseGuards,
|
||||
HttpCode,
|
||||
HttpStatus,
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags, ApiOperation, ApiBearerAuth, ApiQuery } from '@nestjs/swagger';
|
||||
import { Request, Response } from 'express';
|
||||
import { ShareLinksService } from './share-links.service';
|
||||
import { CreateShareLinkDto } from './dto/create-share-link.dto';
|
||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||
import { CurrentUser, AuthenticatedUser } from '../auth/decorators/current-user.decorator';
|
||||
|
||||
@ApiTags('Public & Drive-like Share Links')
|
||||
@Controller('share-links')
|
||||
export class ShareLinksController {
|
||||
constructor(private readonly shareLinksService: ShareLinksService) {}
|
||||
|
||||
@Post()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@ApiOperation({ summary: 'Create a Google Drive-like share link for a file or folder' })
|
||||
async createShareLink(
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
@Body() dto: CreateShareLinkDto,
|
||||
@Req() req: Request,
|
||||
) {
|
||||
return this.shareLinksService.createShareLink(
|
||||
user.id,
|
||||
user.role,
|
||||
dto,
|
||||
req.ip,
|
||||
req.headers['user-agent'],
|
||||
);
|
||||
}
|
||||
|
||||
@Get()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@ApiOperation({ summary: 'Get all active share links created by current user' })
|
||||
async getMyShareLinks(@CurrentUser() user: AuthenticatedUser) {
|
||||
return this.shareLinksService.getMyShareLinks(user.id);
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@ApiOperation({ summary: 'Revoke a share link' })
|
||||
async revokeShareLink(
|
||||
@Param('id') id: string,
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
) {
|
||||
return this.shareLinksService.revokeShareLink(user.id, user.role, id);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// PUBLIC ROUTES (Unauthenticated access to shared resource only)
|
||||
// =========================================================================
|
||||
|
||||
@Get('public/:token')
|
||||
@ApiOperation({ summary: 'Access shared file or folder resource metadata (Public)' })
|
||||
@ApiQuery({ name: 'password', required: false })
|
||||
@ApiQuery({ name: 'subfolderId', required: false })
|
||||
async getPublicResource(
|
||||
@Param('token') token: string,
|
||||
@Query('password') password?: string,
|
||||
@Query('subfolderId') subfolderId?: string,
|
||||
) {
|
||||
return this.shareLinksService.getPublicResource(token, password, subfolderId);
|
||||
}
|
||||
|
||||
@Get('public/:token/playback')
|
||||
@ApiOperation({ summary: 'Stream shared video directly with range support (Public)' })
|
||||
@ApiQuery({ name: 'fileId', required: false })
|
||||
@ApiQuery({ name: 'password', required: false })
|
||||
async streamPublicVideo(
|
||||
@Param('token') token: string,
|
||||
@Headers('range') rangeHeader: string,
|
||||
@Res() res: Response,
|
||||
@Query('fileId') fileId?: string,
|
||||
@Query('password') password?: string,
|
||||
) {
|
||||
const result = await this.shareLinksService.streamPublicVideo(
|
||||
token,
|
||||
fileId,
|
||||
rangeHeader,
|
||||
password,
|
||||
);
|
||||
|
||||
if (result.isRange) {
|
||||
res.writeHead(206, {
|
||||
'Content-Range': `bytes ${result.start}-${result.end}/${result.totalSize}`,
|
||||
'Accept-Ranges': 'bytes',
|
||||
'Content-Length': result.chunkSize,
|
||||
'Content-Type': result.mimeType,
|
||||
'Cache-Control': 'no-cache, private',
|
||||
});
|
||||
} else {
|
||||
res.writeHead(200, {
|
||||
'Content-Length': result.totalSize,
|
||||
'Content-Type': result.mimeType,
|
||||
'Accept-Ranges': 'bytes',
|
||||
});
|
||||
}
|
||||
|
||||
result.stream.pipe(res);
|
||||
}
|
||||
|
||||
@Get('public/:token/thumbnail')
|
||||
@ApiOperation({ summary: 'Get shared file thumbnail image (Public)' })
|
||||
@ApiQuery({ name: 'fileId', required: false })
|
||||
@ApiQuery({ name: 'password', required: false })
|
||||
async getPublicThumbnail(
|
||||
@Param('token') token: string,
|
||||
@Res() res: Response,
|
||||
@Query('fileId') fileId?: string,
|
||||
@Query('password') password?: string,
|
||||
) {
|
||||
const { stream, contentType } = await this.shareLinksService.getPublicThumbnail(
|
||||
token,
|
||||
fileId,
|
||||
password,
|
||||
);
|
||||
res.setHeader('Content-Type', contentType || 'image/jpeg');
|
||||
res.setHeader('Cache-Control', 'public, max-age=86400');
|
||||
stream.pipe(res);
|
||||
}
|
||||
|
||||
@Get('public/:token/download')
|
||||
@ApiOperation({ summary: 'Download shared file (Public)' })
|
||||
@ApiQuery({ name: 'fileId', required: false })
|
||||
@ApiQuery({ name: 'password', required: false })
|
||||
async downloadPublicFile(
|
||||
@Param('token') token: string,
|
||||
@Res() res: Response,
|
||||
@Query('fileId') fileId?: string,
|
||||
@Query('password') password?: string,
|
||||
) {
|
||||
const { stream, file, contentType } = await this.shareLinksService.downloadPublicFile(
|
||||
token,
|
||||
fileId,
|
||||
password,
|
||||
);
|
||||
|
||||
res.setHeader('Content-Type', contentType);
|
||||
res.setHeader(
|
||||
'Content-Disposition',
|
||||
`attachment; filename="${encodeURIComponent(file.originalFilename)}"`,
|
||||
);
|
||||
res.setHeader('Content-Length', file.fileSizeBytes.toString());
|
||||
|
||||
stream.pipe(res);
|
||||
}
|
||||
}
|
||||
14
apps/backend/src/modules/share-links/share-links.module.ts
Normal file
14
apps/backend/src/modules/share-links/share-links.module.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ShareLinksController } from './share-links.controller';
|
||||
import { ShareLinksService } from './share-links.service';
|
||||
import { PrismaModule } from '../prisma/prisma.module';
|
||||
import { AuditModule } from '../audit/audit.module';
|
||||
import { StorageModule } from '../storage/storage.module';
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule, AuditModule, StorageModule],
|
||||
controllers: [ShareLinksController],
|
||||
providers: [ShareLinksService],
|
||||
exports: [ShareLinksService],
|
||||
})
|
||||
export class ShareLinksModule {}
|
||||
583
apps/backend/src/modules/share-links/share-links.service.ts
Normal file
583
apps/backend/src/modules/share-links/share-links.service.ts
Normal file
@@ -0,0 +1,583 @@
|
||||
import {
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
ForbiddenException,
|
||||
BadRequestException,
|
||||
UnauthorizedException,
|
||||
Inject,
|
||||
} from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { AuditService } from '../audit/audit.service';
|
||||
import { STORAGE_PROVIDER, IStorageProvider } from '../storage/storage.interface';
|
||||
import { CreateShareLinkDto } from './dto/create-share-link.dto';
|
||||
import { ShareResourceType, UserRole } from '@prisma/client';
|
||||
import * as crypto from 'crypto';
|
||||
import * as argon2 from 'argon2';
|
||||
|
||||
@Injectable()
|
||||
export class ShareLinksService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly auditService: AuditService,
|
||||
@Inject(STORAGE_PROVIDER) private readonly storageProvider: IStorageProvider,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Create a Google Drive-like share link
|
||||
*/
|
||||
async createShareLink(
|
||||
userId: string,
|
||||
userRole: string,
|
||||
dto: CreateShareLinkDto,
|
||||
ipAddress?: string,
|
||||
userAgent?: string,
|
||||
) {
|
||||
// 1. Verify user has permission to create share links (Superadmin decides who can share)
|
||||
if (userRole !== UserRole.SUPER_ADMIN && userRole !== UserRole.ADMIN) {
|
||||
const user = await this.prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { canCreateShareLinks: true },
|
||||
});
|
||||
if (!user?.canCreateShareLinks) {
|
||||
throw new ForbiddenException(
|
||||
'You do not have permission to create share links. Please contact an administrator.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let fileId: string | null = null;
|
||||
let folderId: string | null = null;
|
||||
let defaultTitle = dto.title?.trim() || '';
|
||||
|
||||
// 2. Validate Resource & Ownership
|
||||
if (dto.resourceType === ShareResourceType.FILE) {
|
||||
if (!dto.fileId) {
|
||||
throw new BadRequestException('fileId is required when sharing a file');
|
||||
}
|
||||
const file = await this.prisma.fileAsset.findUnique({
|
||||
where: { id: dto.fileId },
|
||||
});
|
||||
if (!file || file.isSoftDeleted) {
|
||||
throw new NotFoundException('File not found or has been deleted');
|
||||
}
|
||||
if (file.ownerId !== userId && userRole !== UserRole.SUPER_ADMIN && userRole !== UserRole.ADMIN) {
|
||||
throw new ForbiddenException('You can only create share links for your own files');
|
||||
}
|
||||
fileId = file.id;
|
||||
if (!defaultTitle) defaultTitle = file.originalFilename;
|
||||
} else if (dto.resourceType === ShareResourceType.FOLDER) {
|
||||
if (!dto.folderId) {
|
||||
throw new BadRequestException('folderId is required when sharing a folder');
|
||||
}
|
||||
const folder = await this.prisma.folder.findUnique({
|
||||
where: { id: dto.folderId },
|
||||
});
|
||||
if (!folder) {
|
||||
throw new NotFoundException('Folder not found');
|
||||
}
|
||||
if (folder.ownerId !== userId && userRole !== UserRole.SUPER_ADMIN && userRole !== UserRole.ADMIN) {
|
||||
throw new ForbiddenException('You can only create share links for your own folders');
|
||||
}
|
||||
folderId = folder.id;
|
||||
if (!defaultTitle) defaultTitle = folder.name;
|
||||
} else {
|
||||
throw new BadRequestException('Invalid resource type');
|
||||
}
|
||||
|
||||
// 3. Password hashing (if password protected)
|
||||
let passwordHash: string | null = null;
|
||||
if (dto.password && dto.password.trim()) {
|
||||
passwordHash = await argon2.hash(dto.password.trim(), { type: argon2.argon2id });
|
||||
}
|
||||
|
||||
// 4. Calculate expiry
|
||||
let expiresAt: Date | null = null;
|
||||
if (dto.expiresInDays && dto.expiresInDays > 0) {
|
||||
expiresAt = new Date(Date.now() + dto.expiresInDays * 24 * 60 * 60 * 1000);
|
||||
}
|
||||
|
||||
// 5. Generate unique secure URL-safe token (24 hex characters)
|
||||
const token = crypto.randomBytes(16).toString('hex');
|
||||
|
||||
const shareLink = await this.prisma.shareLink.create({
|
||||
data: {
|
||||
token,
|
||||
title: defaultTitle,
|
||||
ownerId: userId,
|
||||
resourceType: dto.resourceType,
|
||||
fileId,
|
||||
folderId,
|
||||
allowDownload: dto.allowDownload !== undefined ? dto.allowDownload : true,
|
||||
passwordHash,
|
||||
expiresAt,
|
||||
isActive: true,
|
||||
},
|
||||
include: {
|
||||
file: {
|
||||
select: {
|
||||
id: true,
|
||||
originalFilename: true,
|
||||
fileSizeBytes: true,
|
||||
mimeType: true,
|
||||
fileCategory: true,
|
||||
},
|
||||
},
|
||||
folder: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
logicalPath: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await this.auditService.log({
|
||||
actorUserId: userId,
|
||||
action: 'SHARE_LINK_CREATED',
|
||||
resourceType: dto.resourceType === ShareResourceType.FILE ? 'FILE' : 'FOLDER',
|
||||
resourceId: (fileId || folderId) as string,
|
||||
targetUserId: userId,
|
||||
ipAddress,
|
||||
userAgent,
|
||||
details: {
|
||||
token: shareLink.token,
|
||||
resourceType: shareLink.resourceType,
|
||||
allowDownload: shareLink.allowDownload,
|
||||
hasPassword: !!passwordHash,
|
||||
expiresAt: shareLink.expiresAt,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
id: shareLink.id,
|
||||
token: shareLink.token,
|
||||
title: shareLink.title,
|
||||
resourceType: shareLink.resourceType,
|
||||
fileId: shareLink.fileId,
|
||||
folderId: shareLink.folderId,
|
||||
allowDownload: shareLink.allowDownload,
|
||||
hasPassword: !!shareLink.passwordHash,
|
||||
expiresAt: shareLink.expiresAt,
|
||||
viewCount: shareLink.viewCount,
|
||||
downloadCount: shareLink.downloadCount,
|
||||
createdAt: shareLink.createdAt,
|
||||
file: shareLink.file
|
||||
? {
|
||||
...shareLink.file,
|
||||
fileSizeBytes: shareLink.file.fileSizeBytes.toString(),
|
||||
}
|
||||
: null,
|
||||
folder: shareLink.folder,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all share links created by current user
|
||||
*/
|
||||
async getMyShareLinks(userId: string) {
|
||||
const links = await this.prisma.shareLink.findMany({
|
||||
where: { ownerId: userId, isActive: true },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
include: {
|
||||
file: {
|
||||
select: {
|
||||
id: true,
|
||||
originalFilename: true,
|
||||
fileSizeBytes: true,
|
||||
mimeType: true,
|
||||
fileCategory: true,
|
||||
},
|
||||
},
|
||||
folder: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
logicalPath: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return links.map((l) => ({
|
||||
id: l.id,
|
||||
token: l.token,
|
||||
title: l.title,
|
||||
resourceType: l.resourceType,
|
||||
fileId: l.fileId,
|
||||
folderId: l.folderId,
|
||||
allowDownload: l.allowDownload,
|
||||
hasPassword: !!l.passwordHash,
|
||||
expiresAt: l.expiresAt,
|
||||
viewCount: l.viewCount,
|
||||
downloadCount: l.downloadCount,
|
||||
isActive: l.isActive,
|
||||
createdAt: l.createdAt,
|
||||
file: l.file
|
||||
? {
|
||||
...l.file,
|
||||
fileSizeBytes: l.file.fileSizeBytes.toString(),
|
||||
}
|
||||
: null,
|
||||
folder: l.folder,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Revoke or delete a share link
|
||||
*/
|
||||
async revokeShareLink(userId: string, userRole: string, linkId: string) {
|
||||
const link = await this.prisma.shareLink.findUnique({ where: { id: linkId } });
|
||||
if (!link) throw new NotFoundException('Share link not found');
|
||||
|
||||
if (link.ownerId !== userId && userRole !== UserRole.SUPER_ADMIN && userRole !== UserRole.ADMIN) {
|
||||
throw new ForbiddenException('Unauthorized to revoke this share link');
|
||||
}
|
||||
|
||||
await this.prisma.shareLink.delete({ where: { id: linkId } });
|
||||
|
||||
await this.auditService.log({
|
||||
actorUserId: userId,
|
||||
action: 'SHARE_LINK_REVOKED',
|
||||
resourceType: link.resourceType === ShareResourceType.FILE ? 'FILE' : 'FOLDER',
|
||||
resourceId: linkId,
|
||||
details: { token: link.token },
|
||||
});
|
||||
|
||||
return { success: true, message: 'Share link revoked successfully' };
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a public link token, check expiration & password
|
||||
*/
|
||||
private async validateAndGetLink(token: string, password?: string) {
|
||||
const link = await this.prisma.shareLink.findUnique({
|
||||
where: { token },
|
||||
include: {
|
||||
owner: { select: { id: true, username: true, fullName: true } },
|
||||
},
|
||||
});
|
||||
|
||||
if (!link || !link.isActive) {
|
||||
throw new NotFoundException('This shared link does not exist or has been disabled');
|
||||
}
|
||||
|
||||
if (link.expiresAt && link.expiresAt < new Date()) {
|
||||
throw new BadRequestException('This share link has expired');
|
||||
}
|
||||
|
||||
if (link.passwordHash) {
|
||||
if (!password) {
|
||||
return { link, requiresPassword: true as const };
|
||||
}
|
||||
const isMatch = await argon2.verify(link.passwordHash, password);
|
||||
if (!isMatch) {
|
||||
throw new UnauthorizedException('Incorrect password for this shared link');
|
||||
}
|
||||
}
|
||||
|
||||
return { link, requiresPassword: false as const };
|
||||
}
|
||||
|
||||
/**
|
||||
* Public View: Get shared file or folder metadata and items
|
||||
*/
|
||||
async getPublicResource(token: string, password?: string, subfolderId?: string) {
|
||||
const validation = await this.validateAndGetLink(token, password);
|
||||
const { link } = validation;
|
||||
|
||||
if (validation.requiresPassword) {
|
||||
return {
|
||||
requiresPassword: true,
|
||||
title: link.title,
|
||||
resourceType: link.resourceType,
|
||||
ownerName: link.owner.fullName,
|
||||
};
|
||||
}
|
||||
|
||||
// Increment view count asynchronously
|
||||
await this.prisma.shareLink.update({
|
||||
where: { id: link.id },
|
||||
data: { viewCount: { increment: 1 } },
|
||||
});
|
||||
|
||||
// Case 1: Shared FILE
|
||||
if (link.resourceType === ShareResourceType.FILE) {
|
||||
const file = await this.prisma.fileAsset.findUnique({
|
||||
where: { id: link.fileId as string },
|
||||
});
|
||||
|
||||
if (!file || file.isSoftDeleted) {
|
||||
throw new NotFoundException('The shared file has been removed or deleted');
|
||||
}
|
||||
|
||||
return {
|
||||
requiresPassword: false,
|
||||
resourceType: ShareResourceType.FILE,
|
||||
title: link.title || file.originalFilename,
|
||||
allowDownload: link.allowDownload,
|
||||
ownerName: link.owner.fullName,
|
||||
createdAt: link.createdAt,
|
||||
expiresAt: link.expiresAt,
|
||||
file: {
|
||||
id: file.id,
|
||||
originalFilename: file.originalFilename,
|
||||
mimeType: file.mimeType,
|
||||
fileExtension: file.fileExtension,
|
||||
fileSizeBytes: file.fileSizeBytes.toString(),
|
||||
fileCategory: file.fileCategory,
|
||||
status: file.status,
|
||||
durationSeconds: file.durationSeconds,
|
||||
width: file.width,
|
||||
height: file.height,
|
||||
hasHlsStream: !!file.hlsMasterPlaylistKey,
|
||||
hasThumbnail: !!file.thumbnailStorageKey,
|
||||
createdAt: file.createdAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Case 2: Shared FOLDER
|
||||
const rootSharedFolder = await this.prisma.folder.findUnique({
|
||||
where: { id: link.folderId as string },
|
||||
});
|
||||
|
||||
if (!rootSharedFolder) {
|
||||
throw new NotFoundException('The shared folder has been removed or deleted');
|
||||
}
|
||||
|
||||
// If browsing a subfolder, verify that subfolderId is descendant of rootSharedFolder
|
||||
let currentFolder = rootSharedFolder;
|
||||
if (subfolderId && subfolderId !== rootSharedFolder.id) {
|
||||
const candidateFolder = await this.prisma.folder.findUnique({
|
||||
where: { id: subfolderId },
|
||||
});
|
||||
if (!candidateFolder) {
|
||||
throw new NotFoundException('Subfolder not found');
|
||||
}
|
||||
|
||||
// Verify hierarchy: candidateFolder must reside under rootSharedFolder.logicalPath
|
||||
if (
|
||||
!candidateFolder.logicalPath.startsWith(rootSharedFolder.logicalPath) ||
|
||||
candidateFolder.ownerId !== rootSharedFolder.ownerId
|
||||
) {
|
||||
throw new ForbiddenException('Access denied: Cannot browse outside the shared folder');
|
||||
}
|
||||
currentFolder = candidateFolder;
|
||||
}
|
||||
|
||||
// Load subfolders in current folder
|
||||
const subfolders = await this.prisma.folder.findMany({
|
||||
where: { parentId: currentFolder.id },
|
||||
orderBy: { name: 'asc' },
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
logicalPath: true,
|
||||
createdAt: true,
|
||||
_count: {
|
||||
select: { files: { where: { isSoftDeleted: false } }, children: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Load files in current folder
|
||||
const files = await this.prisma.fileAsset.findMany({
|
||||
where: { folderId: currentFolder.id, isSoftDeleted: false },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
select: {
|
||||
id: true,
|
||||
originalFilename: true,
|
||||
mimeType: true,
|
||||
fileExtension: true,
|
||||
fileSizeBytes: true,
|
||||
fileCategory: true,
|
||||
status: true,
|
||||
durationSeconds: true,
|
||||
width: true,
|
||||
height: true,
|
||||
thumbnailStorageKey: true,
|
||||
hlsMasterPlaylistKey: true,
|
||||
createdAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
requiresPassword: false,
|
||||
resourceType: ShareResourceType.FOLDER,
|
||||
title: link.title || rootSharedFolder.name,
|
||||
allowDownload: link.allowDownload,
|
||||
ownerName: link.owner.fullName,
|
||||
createdAt: link.createdAt,
|
||||
expiresAt: link.expiresAt,
|
||||
rootFolderId: rootSharedFolder.id,
|
||||
currentFolder: {
|
||||
id: currentFolder.id,
|
||||
name: currentFolder.name,
|
||||
logicalPath: currentFolder.logicalPath,
|
||||
isRootOfShare: currentFolder.id === rootSharedFolder.id,
|
||||
},
|
||||
subfolders: subfolders.map((f) => ({
|
||||
id: f.id,
|
||||
name: f.name,
|
||||
logicalPath: f.logicalPath,
|
||||
fileCount: f._count.files,
|
||||
subfolderCount: f._count.children,
|
||||
createdAt: f.createdAt,
|
||||
})),
|
||||
files: files.map((f) => ({
|
||||
id: f.id,
|
||||
originalFilename: f.originalFilename,
|
||||
mimeType: f.mimeType,
|
||||
fileExtension: f.fileExtension,
|
||||
fileSizeBytes: f.fileSizeBytes.toString(),
|
||||
fileCategory: f.fileCategory,
|
||||
status: f.status,
|
||||
durationSeconds: f.durationSeconds,
|
||||
width: f.width,
|
||||
height: f.height,
|
||||
hasThumbnail: !!f.thumbnailStorageKey,
|
||||
hasHlsStream: !!f.hlsMasterPlaylistKey,
|
||||
createdAt: f.createdAt,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to verify file belongs to shared resource
|
||||
*/
|
||||
private async resolveSharedFile(link: any, requestedFileId?: string) {
|
||||
if (link.resourceType === ShareResourceType.FILE) {
|
||||
return this.prisma.fileAsset.findUnique({
|
||||
where: { id: link.fileId, isSoftDeleted: false },
|
||||
});
|
||||
}
|
||||
|
||||
if (!requestedFileId) {
|
||||
throw new BadRequestException('fileId is required when accessing a file in a shared folder');
|
||||
}
|
||||
|
||||
const file = await this.prisma.fileAsset.findUnique({
|
||||
where: { id: requestedFileId, isSoftDeleted: false },
|
||||
include: { folder: true },
|
||||
});
|
||||
|
||||
if (!file || !file.folder) {
|
||||
throw new NotFoundException('File not found in shared folder');
|
||||
}
|
||||
|
||||
// Verify folder hierarchy
|
||||
const rootSharedFolder = await this.prisma.folder.findUnique({
|
||||
where: { id: link.folderId },
|
||||
});
|
||||
|
||||
if (
|
||||
!rootSharedFolder ||
|
||||
!file.folder.logicalPath.startsWith(rootSharedFolder.logicalPath) ||
|
||||
file.ownerId !== rootSharedFolder.ownerId
|
||||
) {
|
||||
throw new ForbiddenException('Access denied: File does not belong to this shared folder');
|
||||
}
|
||||
|
||||
return file;
|
||||
}
|
||||
|
||||
/**
|
||||
* Public Stream (Video playback with HTTP Range support)
|
||||
*/
|
||||
async streamPublicVideo(
|
||||
token: string,
|
||||
requestedFileId?: string,
|
||||
rangeHeader?: string,
|
||||
password?: string,
|
||||
) {
|
||||
const validation = await this.validateAndGetLink(token, password);
|
||||
if (validation.requiresPassword) {
|
||||
throw new UnauthorizedException('Password required for streaming');
|
||||
}
|
||||
|
||||
const file = await this.resolveSharedFile(validation.link, requestedFileId);
|
||||
if (!file) throw new NotFoundException('File not found');
|
||||
|
||||
const totalSize = await this.storageProvider.getSize(file.internalStorageKey);
|
||||
|
||||
if (rangeHeader) {
|
||||
const parts = rangeHeader.replace(/bytes=/, '').split('-');
|
||||
const start = parseInt(parts[0], 10);
|
||||
const end = parts[1] ? parseInt(parts[1], 10) : totalSize - 1;
|
||||
const chunkSize = end - start + 1;
|
||||
|
||||
const { stream } = await this.storageProvider.getStream(file.internalStorageKey, {
|
||||
start,
|
||||
end,
|
||||
});
|
||||
|
||||
return {
|
||||
isRange: true,
|
||||
start,
|
||||
end,
|
||||
totalSize,
|
||||
chunkSize,
|
||||
mimeType: file.mimeType || 'video/mp4',
|
||||
stream,
|
||||
};
|
||||
}
|
||||
|
||||
const { stream, contentType } = await this.storageProvider.getStream(file.internalStorageKey);
|
||||
return {
|
||||
isRange: false,
|
||||
totalSize,
|
||||
mimeType: contentType || file.mimeType || 'video/mp4',
|
||||
stream,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Public Thumbnail Stream
|
||||
*/
|
||||
async getPublicThumbnail(token: string, requestedFileId?: string, password?: string) {
|
||||
const validation = await this.validateAndGetLink(token, password);
|
||||
if (validation.requiresPassword) {
|
||||
throw new UnauthorizedException('Password required');
|
||||
}
|
||||
|
||||
const file = await this.resolveSharedFile(validation.link, requestedFileId);
|
||||
if (!file || !file.thumbnailStorageKey) {
|
||||
throw new NotFoundException('Thumbnail not available');
|
||||
}
|
||||
|
||||
return this.storageProvider.getStream(file.thumbnailStorageKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Public Download
|
||||
*/
|
||||
async downloadPublicFile(token: string, requestedFileId?: string, password?: string) {
|
||||
const validation = await this.validateAndGetLink(token, password);
|
||||
if (validation.requiresPassword) {
|
||||
throw new UnauthorizedException('Password required');
|
||||
}
|
||||
|
||||
const { link } = validation;
|
||||
if (!link.allowDownload) {
|
||||
throw new ForbiddenException('Downloading is disabled for this shared link');
|
||||
}
|
||||
|
||||
const file = await this.resolveSharedFile(link, requestedFileId);
|
||||
if (!file) throw new NotFoundException('File not found');
|
||||
|
||||
// Increment download count
|
||||
await this.prisma.shareLink.update({
|
||||
where: { id: link.id },
|
||||
data: { downloadCount: { increment: 1 } },
|
||||
});
|
||||
|
||||
const { stream, contentType } = await this.storageProvider.getStream(file.internalStorageKey);
|
||||
|
||||
return {
|
||||
stream,
|
||||
file,
|
||||
contentType: contentType || file.mimeType || 'application/octet-stream',
|
||||
};
|
||||
}
|
||||
}
|
||||
326
apps/backend/src/modules/video/video-processor.service.ts
Normal file
326
apps/backend/src/modules/video/video-processor.service.ts
Normal file
@@ -0,0 +1,326 @@
|
||||
import { Injectable, Logger, Inject } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import * as ffmpeg from 'fluent-ffmpeg';
|
||||
import * as path from 'path';
|
||||
import * as fs from 'fs';
|
||||
import * as os from 'os';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { STORAGE_PROVIDER, IStorageProvider } from '../storage/storage.interface';
|
||||
import { StoragePathUtils } from '../storage/storage-path.util';
|
||||
import { FileStatus, ProcessingJobStatus } from '@prisma/client';
|
||||
|
||||
export interface VideoMetadata {
|
||||
durationSeconds: number;
|
||||
width: number;
|
||||
height: number;
|
||||
videoCodec: string;
|
||||
audioCodec: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class VideoProcessorService {
|
||||
private readonly logger = new Logger(VideoProcessorService.name);
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly configService: ConfigService,
|
||||
@Inject(STORAGE_PROVIDER) private readonly storageProvider: IStorageProvider,
|
||||
) {
|
||||
this.configureFfmpegPaths();
|
||||
}
|
||||
|
||||
private configureFfmpegPaths(): void {
|
||||
const customFfmpeg = this.configService.get<string>('FFMPEG_PATH');
|
||||
const customFfprobe = this.configService.get<string>('FFPROBE_PATH');
|
||||
|
||||
if (customFfmpeg && fs.existsSync(customFfmpeg)) {
|
||||
ffmpeg.setFfmpegPath(customFfmpeg);
|
||||
this.logger.log(`FFmpeg custom path set: ${customFfmpeg}`);
|
||||
} else {
|
||||
// Auto-detect standard paths across Windows & Linux
|
||||
const candidateFfmpeg = process.platform === 'win32'
|
||||
? [
|
||||
'C:\\ffmpeg\\bin\\ffmpeg.exe',
|
||||
'C:\\ProgramData\\chocolatey\\bin\\ffmpeg.exe',
|
||||
'C:\\Program Files\\ffmpeg\\bin\\ffmpeg.exe',
|
||||
path.join(process.env.LOCALAPPDATA || '', 'Microsoft\\WinGet\\Links\\ffmpeg.exe'),
|
||||
]
|
||||
: ['/usr/bin/ffmpeg', '/usr/local/bin/ffmpeg', '/opt/homebrew/bin/ffmpeg'];
|
||||
|
||||
for (const candidate of candidateFfmpeg) {
|
||||
if (candidate && fs.existsSync(candidate)) {
|
||||
ffmpeg.setFfmpegPath(candidate);
|
||||
this.logger.log(`FFmpeg auto-detected on ${process.platform}: ${candidate}`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (customFfprobe && fs.existsSync(customFfprobe)) {
|
||||
ffmpeg.setFfprobePath(customFfprobe);
|
||||
this.logger.log(`FFprobe custom path set: ${customFfprobe}`);
|
||||
} else {
|
||||
const candidateFfprobe = process.platform === 'win32'
|
||||
? [
|
||||
'C:\\ffmpeg\\bin\\ffprobe.exe',
|
||||
'C:\\ProgramData\\chocolatey\\bin\\ffprobe.exe',
|
||||
'C:\\Program Files\\ffmpeg\\bin\\ffprobe.exe',
|
||||
path.join(process.env.LOCALAPPDATA || '', 'Microsoft\\WinGet\\Links\\ffprobe.exe'),
|
||||
]
|
||||
: ['/usr/bin/ffprobe', '/usr/local/bin/ffprobe', '/opt/homebrew/bin/ffprobe'];
|
||||
|
||||
for (const candidate of candidateFfprobe) {
|
||||
if (candidate && fs.existsSync(candidate)) {
|
||||
ffmpeg.setFfprobePath(candidate);
|
||||
this.logger.log(`FFprobe auto-detected on ${process.platform}: ${candidate}`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Probe video file to extract metadata (duration, resolution, codecs)
|
||||
*/
|
||||
async probeVideo(filePath: string): Promise<VideoMetadata> {
|
||||
return new Promise((resolve, reject) => {
|
||||
ffmpeg.ffprobe(filePath, (err, metadata) => {
|
||||
if (err) {
|
||||
return reject(err);
|
||||
}
|
||||
|
||||
const videoStream = metadata.streams.find((s) => s.codec_type === 'video');
|
||||
const audioStream = metadata.streams.find((s) => s.codec_type === 'audio');
|
||||
|
||||
const duration = metadata.format.duration || videoStream?.duration || 0;
|
||||
const width = videoStream?.width || 0;
|
||||
const height = videoStream?.height || 0;
|
||||
const videoCodec = videoStream?.codec_name || 'unknown';
|
||||
const audioCodec = audioStream?.codec_name || 'unknown';
|
||||
|
||||
resolve({
|
||||
durationSeconds: Number(duration),
|
||||
width: Number(width),
|
||||
height: Number(height),
|
||||
videoCodec,
|
||||
audioCodec,
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract thumbnail frame from video at specified second
|
||||
*/
|
||||
async extractThumbnail(
|
||||
videoFilePath: string,
|
||||
outputJpgPath: string,
|
||||
atSecond = 1.0,
|
||||
): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
ffmpeg(videoFilePath)
|
||||
.seekInput(atSecond)
|
||||
.outputOptions(['-vframes 1', '-vf scale=640:-1', '-pix_fmt yuvj420p'])
|
||||
.output(outputJpgPath.replace(/\\/g, '/'))
|
||||
.on('end', () => resolve())
|
||||
.on('error', (err) => reject(err))
|
||||
.run();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Transcode video to HLS (HTTP Live Streaming) format for adaptive streaming
|
||||
*/
|
||||
async generateHlsStream(
|
||||
videoFilePath: string,
|
||||
outputHlsDir: string,
|
||||
onProgress?: (percent: number) => void,
|
||||
): Promise<string> {
|
||||
if (!fs.existsSync(outputHlsDir)) {
|
||||
fs.mkdirSync(outputHlsDir, { recursive: true });
|
||||
}
|
||||
|
||||
const masterPlaylistPath = path.join(outputHlsDir, 'master.m3u8').replace(/\\/g, '/');
|
||||
const segmentPattern = path.join(outputHlsDir, 'segment_%03d.ts').replace(/\\/g, '/');
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
ffmpeg(videoFilePath)
|
||||
.outputOptions([
|
||||
'-c:v libx264',
|
||||
'-pix_fmt yuv420p',
|
||||
'-profile:v baseline',
|
||||
'-level 3.0',
|
||||
'-c:a aac',
|
||||
'-ar 44100',
|
||||
'-b:a 128k',
|
||||
'-start_number 0',
|
||||
'-hls_time 4',
|
||||
'-hls_list_size 0',
|
||||
`-hls_segment_filename ${segmentPattern}`,
|
||||
'-f hls',
|
||||
])
|
||||
.output(masterPlaylistPath)
|
||||
.on('progress', (progress) => {
|
||||
if (progress.percent && onProgress) {
|
||||
onProgress(Math.min(Math.round(progress.percent), 99));
|
||||
}
|
||||
})
|
||||
.on('end', () => resolve(masterPlaylistPath))
|
||||
.on('error', (err) => reject(err))
|
||||
.run();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute full video processing pipeline for a file asset:
|
||||
* 1. Extract metadata via FFprobe
|
||||
* 2. Generate frame thumbnail
|
||||
* 3. Transcode to HLS stream
|
||||
* 4. Update database records
|
||||
*/
|
||||
async processVideo(fileAssetId: string): Promise<void> {
|
||||
const file = await this.prisma.fileAsset.findUnique({
|
||||
where: { id: fileAssetId },
|
||||
});
|
||||
|
||||
if (!file) {
|
||||
throw new Error(`File asset ${fileAssetId} not found`);
|
||||
}
|
||||
|
||||
// Upsert processing job record
|
||||
let job = await this.prisma.videoProcessingJob.findFirst({
|
||||
where: { fileAssetId },
|
||||
});
|
||||
|
||||
if (!job) {
|
||||
job = await this.prisma.videoProcessingJob.create({
|
||||
data: {
|
||||
fileAssetId,
|
||||
status: ProcessingJobStatus.PROCESSING,
|
||||
progress: 5,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
job = await this.prisma.videoProcessingJob.update({
|
||||
where: { id: job.id },
|
||||
data: {
|
||||
status: ProcessingJobStatus.PROCESSING,
|
||||
attempts: { increment: 1 },
|
||||
progress: 5,
|
||||
errorReason: null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
await this.prisma.fileAsset.update({
|
||||
where: { id: fileAssetId },
|
||||
data: { status: FileStatus.PROCESSING },
|
||||
});
|
||||
|
||||
const tempDir = path.join(os.tmpdir(), `vid_proc_${fileAssetId}_${Date.now()}`);
|
||||
fs.mkdirSync(tempDir, { recursive: true });
|
||||
|
||||
try {
|
||||
this.logger.log(`Starting video processing for file ${file.id} (${file.originalFilename})`);
|
||||
|
||||
// 1. Get local source path (downloading from S3 if necessary)
|
||||
const localSourcePath = await this.storageProvider.getLocalFilePath(file.internalStorageKey);
|
||||
|
||||
// 2. Extract metadata
|
||||
const meta = await this.probeVideo(localSourcePath);
|
||||
this.logger.log(`Probed video: duration=${meta.durationSeconds}s, ${meta.width}x${meta.height}, codec=${meta.videoCodec}`);
|
||||
|
||||
// 3. Extract thumbnail
|
||||
const thumbnailTempPath = path.join(tempDir, 'thumb.jpg');
|
||||
const thumbAtSecond = meta.durationSeconds > 2 ? 1.0 : 0.1;
|
||||
await this.extractThumbnail(localSourcePath, thumbnailTempPath, thumbAtSecond);
|
||||
|
||||
const thumbnailKey = StoragePathUtils.buildThumbnailKey(file.ownerId, file.id);
|
||||
if (fs.existsSync(thumbnailTempPath)) {
|
||||
const thumbBuffer = await fs.promises.readFile(thumbnailTempPath);
|
||||
await this.storageProvider.putBuffer(thumbnailKey, thumbBuffer, 'image/jpeg');
|
||||
}
|
||||
|
||||
await this.prisma.videoProcessingJob.update({
|
||||
where: { id: job.id },
|
||||
data: { progress: 40 },
|
||||
});
|
||||
|
||||
// 4. Generate HLS Stream
|
||||
const hlsDir = path.join(tempDir, 'hls');
|
||||
await this.generateHlsStream(localSourcePath, hlsDir, async (percent) => {
|
||||
const mappedProgress = Math.min(40 + Math.floor(percent * 0.5), 90);
|
||||
await this.prisma.videoProcessingJob.update({
|
||||
where: { id: job.id },
|
||||
data: { progress: mappedProgress },
|
||||
});
|
||||
});
|
||||
|
||||
// 5. Store HLS segments and playlist in storage
|
||||
const hlsPrefix = StoragePathUtils.buildHlsPrefix(file.ownerId, file.id);
|
||||
const hlsFiles = fs.readdirSync(hlsDir);
|
||||
for (const hlsFileName of hlsFiles) {
|
||||
const hlsFilePath = path.join(hlsDir, hlsFileName);
|
||||
const fileBuffer = await fs.promises.readFile(hlsFilePath);
|
||||
const contentType = hlsFileName.endsWith('.m3u8')
|
||||
? 'application/vnd.apple.mpegurl'
|
||||
: 'video/MP2T';
|
||||
await this.storageProvider.putBuffer(`${hlsPrefix}/${hlsFileName}`, fileBuffer, contentType);
|
||||
}
|
||||
|
||||
const masterPlaylistKey = `${hlsPrefix}/master.m3u8`;
|
||||
|
||||
// 6. Complete Job and update FileAsset
|
||||
await this.prisma.$transaction([
|
||||
this.prisma.fileAsset.update({
|
||||
where: { id: fileAssetId },
|
||||
data: {
|
||||
status: FileStatus.READY,
|
||||
durationSeconds: meta.durationSeconds,
|
||||
width: meta.width,
|
||||
height: meta.height,
|
||||
videoCodec: meta.videoCodec,
|
||||
audioCodec: meta.audioCodec,
|
||||
thumbnailStorageKey: thumbnailKey,
|
||||
hlsMasterPlaylistKey: masterPlaylistKey,
|
||||
},
|
||||
}),
|
||||
this.prisma.videoProcessingJob.update({
|
||||
where: { id: job.id },
|
||||
data: {
|
||||
status: ProcessingJobStatus.COMPLETED,
|
||||
progress: 100,
|
||||
completedAt: new Date(),
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
this.logger.log(`✓ Video processing completed successfully for file ${file.id}`);
|
||||
} catch (err: any) {
|
||||
this.logger.error(`Error processing video ${fileAssetId}: ${err.message}`, err.stack);
|
||||
|
||||
await this.prisma.$transaction([
|
||||
this.prisma.fileAsset.update({
|
||||
where: { id: fileAssetId },
|
||||
data: { status: FileStatus.FAILED },
|
||||
}),
|
||||
this.prisma.videoProcessingJob.update({
|
||||
where: { id: job.id },
|
||||
data: {
|
||||
status: ProcessingJobStatus.FAILED,
|
||||
errorReason: err.message || 'Unknown video transcoding failure',
|
||||
},
|
||||
}),
|
||||
]);
|
||||
} finally {
|
||||
// Cleanup temporary directory
|
||||
try {
|
||||
if (fs.existsSync(tempDir)) {
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
} catch (cleanErr) {
|
||||
this.logger.warn(`Failed to clean temp dir: ${tempDir}`, cleanErr);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
96
apps/backend/src/modules/video/video-queue.service.ts
Normal file
96
apps/backend/src/modules/video/video-queue.service.ts
Normal file
@@ -0,0 +1,96 @@
|
||||
import { Injectable, Logger, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { Queue, Worker, Job } from 'bullmq';
|
||||
import { VideoProcessorService } from './video-processor.service';
|
||||
|
||||
@Injectable()
|
||||
export class VideoQueueService implements OnModuleInit, OnModuleDestroy {
|
||||
private readonly logger = new Logger(VideoQueueService.name);
|
||||
private queue: Queue | null = null;
|
||||
private worker: Worker | null = null;
|
||||
private isRedisConnected = false;
|
||||
|
||||
constructor(
|
||||
private readonly configService: ConfigService,
|
||||
private readonly videoProcessor: VideoProcessorService,
|
||||
) {}
|
||||
|
||||
async onModuleInit() {
|
||||
const host = this.configService.get<string>('REDIS_HOST') || '127.0.0.1';
|
||||
const port = parseInt(this.configService.get<string>('REDIS_PORT') || '6379', 10);
|
||||
const password = this.configService.get<string>('REDIS_PASSWORD') || undefined;
|
||||
|
||||
const connection = {
|
||||
host,
|
||||
port,
|
||||
password,
|
||||
maxRetriesPerRequest: null,
|
||||
connectTimeout: 2000,
|
||||
retryStrategy: () => null, // Do not hang if redis is not running
|
||||
};
|
||||
|
||||
try {
|
||||
this.queue = new Queue('video-processing', { connection });
|
||||
// Test redis connection
|
||||
const client = await this.queue.client;
|
||||
await (client as any).ping();
|
||||
|
||||
this.isRedisConnected = true;
|
||||
this.logger.log(`BullMQ connected to Redis at ${host}:${port}`);
|
||||
|
||||
// Initialize BullMQ worker
|
||||
this.worker = new Worker(
|
||||
'video-processing',
|
||||
async (job: Job<{ fileAssetId: string }>) => {
|
||||
this.logger.log(`Worker processing job ${job.id} for file ${job.data.fileAssetId}`);
|
||||
await this.videoProcessor.processVideo(job.data.fileAssetId);
|
||||
},
|
||||
{ connection, concurrency: 2 },
|
||||
);
|
||||
|
||||
this.worker.on('failed', (job, err) => {
|
||||
this.logger.error(`BullMQ job ${job?.id} failed: ${err.message}`);
|
||||
});
|
||||
} catch (err: any) {
|
||||
this.isRedisConnected = false;
|
||||
this.logger.warn(
|
||||
`Redis is offline (${err.message}). Using resilient in-process queue runner for video processing.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async onModuleDestroy() {
|
||||
if (this.worker) await this.worker.close();
|
||||
if (this.queue) await this.queue.close();
|
||||
}
|
||||
|
||||
/**
|
||||
* Enqueue a video processing job.
|
||||
* If Redis is available, uses BullMQ.
|
||||
* If Redis is unavailable, runs asynchronously via in-process runner.
|
||||
*/
|
||||
async enqueueVideoProcessing(fileAssetId: string): Promise<void> {
|
||||
if (this.isRedisConnected && this.queue) {
|
||||
try {
|
||||
await this.queue.add('process-video', { fileAssetId }, {
|
||||
attempts: 3,
|
||||
backoff: { type: 'exponential', delay: 3000 },
|
||||
removeOnComplete: true,
|
||||
});
|
||||
this.logger.log(`Enqueued file ${fileAssetId} to BullMQ`);
|
||||
return;
|
||||
} catch (err) {
|
||||
this.logger.warn(`Failed to enqueue to BullMQ, falling back to in-process execution: ${err}`);
|
||||
}
|
||||
}
|
||||
|
||||
// In-process resilient asynchronous fallback
|
||||
setImmediate(async () => {
|
||||
try {
|
||||
await this.videoProcessor.processVideo(fileAssetId);
|
||||
} catch (procErr: any) {
|
||||
this.logger.error(`In-process video processing failed for ${fileAssetId}: ${procErr.message}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
211
apps/backend/src/modules/video/video-stream.controller.ts
Normal file
211
apps/backend/src/modules/video/video-stream.controller.ts
Normal file
@@ -0,0 +1,211 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Param,
|
||||
Req,
|
||||
Res,
|
||||
Headers,
|
||||
UseGuards,
|
||||
NotFoundException,
|
||||
ForbiddenException,
|
||||
Inject,
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
|
||||
import { Request, Response } from 'express';
|
||||
import { PermissionsService } from '../permissions/permissions.service';
|
||||
import { VideoQueueService } from './video-queue.service';
|
||||
import { STORAGE_PROVIDER, IStorageProvider } from '../storage/storage.interface';
|
||||
import { StoragePathUtils } from '../storage/storage-path.util';
|
||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||
import { CurrentUser, AuthenticatedUser } from '../auth/decorators/current-user.decorator';
|
||||
import { AuditService } from '../audit/audit.service';
|
||||
import { UserRole } from '@prisma/client';
|
||||
|
||||
@ApiTags('Video & Media Playback')
|
||||
@Controller('files')
|
||||
export class VideoStreamController {
|
||||
constructor(
|
||||
private readonly permissionsService: PermissionsService,
|
||||
private readonly videoQueueService: VideoQueueService,
|
||||
private readonly auditService: AuditService,
|
||||
@Inject(STORAGE_PROVIDER) private readonly storageProvider: IStorageProvider,
|
||||
) {}
|
||||
|
||||
@Get(':id/thumbnail')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@ApiOperation({ summary: 'Get thumbnail preview for a video or image file' })
|
||||
async getThumbnail(
|
||||
@Param('id') fileId: string,
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
@Res() res: Response,
|
||||
) {
|
||||
// Requires canViewMetadata or canPreview permission
|
||||
const file = await this.permissionsService.enforceFileAccess(
|
||||
user.id,
|
||||
user.role,
|
||||
fileId,
|
||||
'canViewMetadata',
|
||||
);
|
||||
|
||||
if (!file.thumbnailStorageKey) {
|
||||
throw new NotFoundException('Thumbnail not available for this file');
|
||||
}
|
||||
|
||||
const { stream, contentType } = await this.storageProvider.getStream(file.thumbnailStorageKey);
|
||||
res.setHeader('Content-Type', contentType || 'image/jpeg');
|
||||
res.setHeader('Cache-Control', 'private, max-age=86400');
|
||||
stream.pipe(res);
|
||||
}
|
||||
|
||||
@Get(':id/playback')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@ApiOperation({ summary: 'Stream video directly via HTTP Range requests' })
|
||||
async streamDirectVideo(
|
||||
@Param('id') fileId: string,
|
||||
@Headers('range') rangeHeader: string,
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
@Req() req: Request,
|
||||
@Res() res: Response,
|
||||
) {
|
||||
// Strictly enforces PLAY permission
|
||||
const file = await this.permissionsService.enforceFileAccess(
|
||||
user.id,
|
||||
user.role,
|
||||
fileId,
|
||||
'canPlay',
|
||||
);
|
||||
|
||||
const totalSize = await this.storageProvider.getSize(file.internalStorageKey);
|
||||
|
||||
// Audit initial playback start
|
||||
if (!rangeHeader || rangeHeader.startsWith('bytes=0-')) {
|
||||
await this.auditService.log({
|
||||
actorUserId: user.id,
|
||||
action: 'VIDEO_PLAYBACK_STARTED',
|
||||
resourceType: 'FILE',
|
||||
resourceId: file.id,
|
||||
targetUserId: file.ownerId,
|
||||
ipAddress: req.ip,
|
||||
userAgent: req.headers['user-agent'],
|
||||
});
|
||||
}
|
||||
|
||||
// Handle HTTP 206 Partial Content
|
||||
if (rangeHeader) {
|
||||
const parts = rangeHeader.replace(/bytes=/, '').split('-');
|
||||
const start = parseInt(parts[0], 10);
|
||||
const end = parts[1] ? parseInt(parts[1], 10) : totalSize - 1;
|
||||
const chunkSize = end - start + 1;
|
||||
|
||||
const { stream } = await this.storageProvider.getStream(file.internalStorageKey, {
|
||||
start,
|
||||
end,
|
||||
});
|
||||
|
||||
res.writeHead(206, {
|
||||
'Content-Range': `bytes ${start}-${end}/${totalSize}`,
|
||||
'Accept-Ranges': 'bytes',
|
||||
'Content-Length': chunkSize,
|
||||
'Content-Type': file.mimeType || 'video/mp4',
|
||||
'Cache-Control': 'no-cache, private',
|
||||
});
|
||||
|
||||
stream.pipe(res);
|
||||
return;
|
||||
}
|
||||
|
||||
// Full stream
|
||||
const { stream } = await this.storageProvider.getStream(file.internalStorageKey);
|
||||
res.writeHead(200, {
|
||||
'Content-Length': totalSize,
|
||||
'Content-Type': file.mimeType || 'video/mp4',
|
||||
'Accept-Ranges': 'bytes',
|
||||
'Cache-Control': 'no-cache, private',
|
||||
});
|
||||
|
||||
stream.pipe(res);
|
||||
}
|
||||
|
||||
@Get(':id/stream/master.m3u8')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@ApiOperation({ summary: 'Get HLS master playlist for adaptive streaming' })
|
||||
async getHlsMasterPlaylist(
|
||||
@Param('id') fileId: string,
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
@Res() res: Response,
|
||||
) {
|
||||
const file = await this.permissionsService.enforceFileAccess(
|
||||
user.id,
|
||||
user.role,
|
||||
fileId,
|
||||
'canPlay',
|
||||
);
|
||||
|
||||
if (!file.hlsMasterPlaylistKey) {
|
||||
throw new NotFoundException('HLS streaming rendition not available for this video');
|
||||
}
|
||||
|
||||
const { stream } = await this.storageProvider.getStream(file.hlsMasterPlaylistKey);
|
||||
res.setHeader('Content-Type', 'application/vnd.apple.mpegurl');
|
||||
res.setHeader('Cache-Control', 'no-cache, private');
|
||||
stream.pipe(res);
|
||||
}
|
||||
|
||||
@Get(':id/stream/:segment')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@ApiOperation({ summary: 'Get individual HLS video chunk segment' })
|
||||
async getHlsSegment(
|
||||
@Param('id') fileId: string,
|
||||
@Param('segment') segment: string,
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
@Res() res: Response,
|
||||
) {
|
||||
// Sanitize segment name to prevent path traversal
|
||||
if (!/^[a-zA-Z0-9_-]+\.ts$/.test(segment)) {
|
||||
throw new ForbiddenException('Invalid HLS segment identifier');
|
||||
}
|
||||
|
||||
const file = await this.permissionsService.enforceFileAccess(
|
||||
user.id,
|
||||
user.role,
|
||||
fileId,
|
||||
'canPlay',
|
||||
);
|
||||
|
||||
const hlsPrefix = StoragePathUtils.buildHlsPrefix(file.ownerId, file.id);
|
||||
const segmentKey = `${hlsPrefix}/${segment}`;
|
||||
|
||||
const { stream } = await this.storageProvider.getStream(segmentKey);
|
||||
res.setHeader('Content-Type', 'video/MP2T');
|
||||
res.setHeader('Cache-Control', 'private, max-age=3600');
|
||||
stream.pipe(res);
|
||||
}
|
||||
|
||||
@Post(':id/retry-processing')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@ApiOperation({ summary: 'Retry failed video transcoding' })
|
||||
async retryProcessing(
|
||||
@Param('id') fileId: string,
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
) {
|
||||
const file = await this.permissionsService.enforceFileAccess(
|
||||
user.id,
|
||||
user.role,
|
||||
fileId,
|
||||
'canViewMetadata',
|
||||
);
|
||||
|
||||
if (file.ownerId !== user.id && user.role !== UserRole.SUPER_ADMIN && user.role !== UserRole.ADMIN) {
|
||||
throw new ForbiddenException('Only the owner or administrator can retry video processing');
|
||||
}
|
||||
|
||||
await this.videoQueueService.enqueueVideoProcessing(file.id);
|
||||
return { success: true, message: 'Video processing job re-enqueued' };
|
||||
}
|
||||
}
|
||||
11
apps/backend/src/modules/video/video.module.ts
Normal file
11
apps/backend/src/modules/video/video.module.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { VideoProcessorService } from './video-processor.service';
|
||||
import { VideoQueueService } from './video-queue.service';
|
||||
import { VideoStreamController } from './video-stream.controller';
|
||||
|
||||
@Module({
|
||||
controllers: [VideoStreamController],
|
||||
providers: [VideoProcessorService, VideoQueueService],
|
||||
exports: [VideoProcessorService, VideoQueueService],
|
||||
})
|
||||
export class VideoModule {}
|
||||
213
apps/backend/test/access-control.e2e-spec.ts
Normal file
213
apps/backend/test/access-control.e2e-spec.ts
Normal file
@@ -0,0 +1,213 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { INestApplication, ValidationPipe } from '@nestjs/common';
|
||||
import * as request from 'supertest';
|
||||
import * as cookieParser from 'cookie-parser';
|
||||
import { AppModule } from '../src/app.module';
|
||||
import { PrismaService } from '../src/modules/prisma/prisma.service';
|
||||
import { PermissionResourceType } from '@prisma/client';
|
||||
|
||||
describe('Security & Access Control (E2E Integration Tests)', () => {
|
||||
let app: INestApplication;
|
||||
let prisma: PrismaService;
|
||||
|
||||
let adminToken: string;
|
||||
let userAToken: string;
|
||||
let userBToken: string;
|
||||
let userAId: string;
|
||||
let userBId: string;
|
||||
let uploadedFileId: string;
|
||||
let grantedPermissionId: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
const moduleFixture: TestingModule = await Test.createTestingModule({
|
||||
imports: [AppModule],
|
||||
}).compile();
|
||||
|
||||
app = moduleFixture.createNestApplication();
|
||||
app.use(cookieParser());
|
||||
app.setGlobalPrefix('api/v1');
|
||||
app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true }));
|
||||
|
||||
await app.init();
|
||||
prisma = app.get<PrismaService>(PrismaService);
|
||||
|
||||
// 1. Authenticate Super Admin
|
||||
const adminRes = await request(app.getHttpServer())
|
||||
.post('/api/v1/auth/login')
|
||||
.send({ identifier: 'superadmin@fileshare.local', password: 'SuperAdmin@Secure2026!' })
|
||||
.expect(200);
|
||||
adminToken = adminRes.body.accessToken;
|
||||
|
||||
// 2. Authenticate User A
|
||||
const userARes = await request(app.getHttpServer())
|
||||
.post('/api/v1/auth/login')
|
||||
.send({ identifier: 'usera@fileshare.local', password: 'UserA@Secure2026!' })
|
||||
.expect(200);
|
||||
userAToken = userARes.body.accessToken;
|
||||
userAId = userARes.body.user.id;
|
||||
|
||||
// 3. Authenticate User B
|
||||
const userBRes = await request(app.getHttpServer())
|
||||
.post('/api/v1/auth/login')
|
||||
.send({ identifier: 'userb@fileshare.local', password: 'UserB@Secure2026!' })
|
||||
.expect(200);
|
||||
userBToken = userBRes.body.accessToken;
|
||||
userBId = userBRes.body.user.id;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
describe('Requirement 1 & 2: User A upload, isolation & direct access denial for User B', () => {
|
||||
it('1. User A can upload their own file', async () => {
|
||||
const fileBuffer = Buffer.from('Confidential report content belonging strictly to Alice', 'utf8');
|
||||
|
||||
const res = await request(app.getHttpServer())
|
||||
.post('/api/v1/files/direct-upload')
|
||||
.set('Authorization', `Bearer ${userAToken}`)
|
||||
.attach('file', fileBuffer, 'alice_project.txt')
|
||||
.expect(201);
|
||||
|
||||
expect(res.body.id).toBeDefined();
|
||||
expect(res.body.originalFilename).toBe('alice_project.txt');
|
||||
uploadedFileId = res.body.id;
|
||||
});
|
||||
|
||||
it('1b. User A can download and preview their own file', async () => {
|
||||
await request(app.getHttpServer())
|
||||
.get(`/api/v1/files/${uploadedFileId}/download`)
|
||||
.set('Authorization', `Bearer ${userAToken}`)
|
||||
.expect(200);
|
||||
|
||||
await request(app.getHttpServer())
|
||||
.get(`/api/v1/files/${uploadedFileId}/preview`)
|
||||
.set('Authorization', `Bearer ${userAToken}`)
|
||||
.expect(200);
|
||||
});
|
||||
|
||||
it('2. User B cannot access User A private file by guessing ID (IDOR prevention)', async () => {
|
||||
// User B cannot download
|
||||
await request(app.getHttpServer())
|
||||
.get(`/api/v1/files/${uploadedFileId}/download`)
|
||||
.set('Authorization', `Bearer ${userBToken}`)
|
||||
.expect(403);
|
||||
|
||||
// User B cannot preview
|
||||
await request(app.getHttpServer())
|
||||
.get(`/api/v1/files/${uploadedFileId}/preview`)
|
||||
.set('Authorization', `Bearer ${userBToken}`)
|
||||
.expect(403);
|
||||
|
||||
// User B cannot playback
|
||||
await request(app.getHttpServer())
|
||||
.get(`/api/v1/files/${uploadedFileId}/playback`)
|
||||
.set('Authorization', `Bearer ${userBToken}`)
|
||||
.expect(403);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Requirement 3 & 4: Granular permissions separation (PLAY vs DOWNLOAD)', () => {
|
||||
it('3. Admin grants PLAY to User B, but denies DOWNLOAD', async () => {
|
||||
const permRes = await request(app.getHttpServer())
|
||||
.post('/api/v1/admin/permissions')
|
||||
.set('Authorization', `Bearer ${adminToken}`)
|
||||
.send({
|
||||
resourceType: PermissionResourceType.FILE,
|
||||
resourceId: uploadedFileId,
|
||||
ownerId: userAId,
|
||||
granteeUserId: userBId,
|
||||
canViewMetadata: true,
|
||||
canPreview: true,
|
||||
canPlay: true,
|
||||
canDownload: false, // Explicitly denied
|
||||
canListFolder: false,
|
||||
})
|
||||
.expect(201);
|
||||
|
||||
expect(permRes.body.id).toBeDefined();
|
||||
grantedPermissionId = permRes.body.id;
|
||||
});
|
||||
|
||||
it('3b. User B can now stream playback of the authorized file', async () => {
|
||||
await request(app.getHttpServer())
|
||||
.get(`/api/v1/files/${uploadedFileId}/playback`)
|
||||
.set('Authorization', `Bearer ${userBToken}`)
|
||||
.expect(200);
|
||||
});
|
||||
|
||||
it('4. User B is strictly forbidden from downloading when DOWNLOAD is false', async () => {
|
||||
await request(app.getHttpServer())
|
||||
.get(`/api/v1/files/${uploadedFileId}/download`)
|
||||
.set('Authorization', `Bearer ${userBToken}`)
|
||||
.expect(403);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Requirement 5: Permission revocation takes effect immediately', () => {
|
||||
it('5. Admin revokes permission from User B', async () => {
|
||||
await request(app.getHttpServer())
|
||||
.post(`/api/v1/admin/permissions/${grantedPermissionId}/revoke`)
|
||||
.set('Authorization', `Bearer ${adminToken}`)
|
||||
.expect(201);
|
||||
});
|
||||
|
||||
it('5b. User B subsequent playback request is immediately denied', async () => {
|
||||
await request(app.getHttpServer())
|
||||
.get(`/api/v1/files/${uploadedFileId}/playback`)
|
||||
.set('Authorization', `Bearer ${userBToken}`)
|
||||
.expect(403);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Requirement 8: Regular users cannot call administrative endpoints', () => {
|
||||
it('8. Regular user calling /api/v1/admin/users is rejected with 403 Forbidden', async () => {
|
||||
await request(app.getHttpServer())
|
||||
.get('/api/v1/admin/users')
|
||||
.set('Authorization', `Bearer ${userAToken}`)
|
||||
.expect(403);
|
||||
});
|
||||
|
||||
it('8b. Regular user calling /api/v1/admin/permissions is rejected with 403 Forbidden', async () => {
|
||||
await request(app.getHttpServer())
|
||||
.get('/api/v1/admin/permissions')
|
||||
.set('Authorization', `Bearer ${userBToken}`)
|
||||
.expect(403);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Requirement 11: Soft-deleted files are no longer accessible', () => {
|
||||
it('11. User A deletes file and subsequent requests return 404', async () => {
|
||||
await request(app.getHttpServer())
|
||||
.delete(`/api/v1/files/${uploadedFileId}`)
|
||||
.set('Authorization', `Bearer ${userAToken}`)
|
||||
.expect(200);
|
||||
|
||||
await request(app.getHttpServer())
|
||||
.get(`/api/v1/files/${uploadedFileId}`)
|
||||
.set('Authorization', `Bearer ${userAToken}`)
|
||||
.expect(404);
|
||||
|
||||
await request(app.getHttpServer())
|
||||
.get(`/api/v1/files/${uploadedFileId}/download`)
|
||||
.set('Authorization', `Bearer ${userAToken}`)
|
||||
.expect(404);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Requirement 14: Audit records are properly created for sensitive operations', () => {
|
||||
it('14. Admin can inspect audit logs for login, file upload, permission grant and revoke', async () => {
|
||||
const logsRes = await request(app.getHttpServer())
|
||||
.get('/api/v1/admin/audit-logs?limit=50')
|
||||
.set('Authorization', `Bearer ${adminToken}`)
|
||||
.expect(200);
|
||||
|
||||
expect(logsRes.body.total).toBeGreaterThan(0);
|
||||
const actions = logsRes.body.logs.map((l: any) => l.action);
|
||||
expect(actions).toContain('USER_LOGIN');
|
||||
expect(actions).toContain('FILE_UPLOADED');
|
||||
expect(actions).toContain('PERMISSION_GRANTED');
|
||||
expect(actions).toContain('PERMISSION_REVOKED');
|
||||
});
|
||||
});
|
||||
});
|
||||
10
apps/backend/test/jest-e2e.json
Normal file
10
apps/backend/test/jest-e2e.json
Normal file
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"moduleFileExtensions": ["js", "json", "ts"],
|
||||
"rootDir": ".",
|
||||
"testEnvironment": "node",
|
||||
"testRegex": ".e2e-spec.ts$",
|
||||
"transform": {
|
||||
"^.+\\.(t|j)s$": "ts-jest"
|
||||
},
|
||||
"testTimeout": 30000
|
||||
}
|
||||
97
apps/backend/test/video-processing.e2e-spec.ts
Normal file
97
apps/backend/test/video-processing.e2e-spec.ts
Normal file
@@ -0,0 +1,97 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { INestApplication, ValidationPipe } from '@nestjs/common';
|
||||
import * as request from 'supertest';
|
||||
import * as cookieParser from 'cookie-parser';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import { AppModule } from '../src/app.module';
|
||||
import { VideoProcessorService } from '../src/modules/video/video-processor.service';
|
||||
|
||||
describe('Video Processing & HLS Transcoding (E2E Integration Test)', () => {
|
||||
let app: INestApplication;
|
||||
let videoProcessor: VideoProcessorService;
|
||||
let userToken: string;
|
||||
let uploadedVideoId: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
const moduleFixture: TestingModule = await Test.createTestingModule({
|
||||
imports: [AppModule],
|
||||
}).compile();
|
||||
|
||||
app = moduleFixture.createNestApplication();
|
||||
app.use(cookieParser());
|
||||
app.setGlobalPrefix('api/v1');
|
||||
app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true }));
|
||||
|
||||
await app.init();
|
||||
videoProcessor = app.get<VideoProcessorService>(VideoProcessorService);
|
||||
|
||||
// Login as User A
|
||||
const loginRes = await request(app.getHttpServer())
|
||||
.post('/api/v1/auth/login')
|
||||
.send({ identifier: 'usera@fileshare.local', password: 'UserA@Secure2026!' })
|
||||
.expect(200);
|
||||
|
||||
userToken = loginRes.body.accessToken;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('uploads an MP4 video, probes metadata, extracts thumbnail and generates HLS playlist', async () => {
|
||||
const videoFilePath = path.resolve(__dirname, '../../../test_video.mp4');
|
||||
expect(fs.existsSync(videoFilePath)).toBe(true);
|
||||
|
||||
const videoBuffer = fs.readFileSync(videoFilePath);
|
||||
|
||||
// 1. Upload video
|
||||
const uploadRes = await request(app.getHttpServer())
|
||||
.post('/api/v1/files/direct-upload')
|
||||
.set('Authorization', `Bearer ${userToken}`)
|
||||
.attach('file', videoBuffer, 'sample_demo_clip.mp4')
|
||||
.expect(201);
|
||||
|
||||
expect(uploadRes.body.id).toBeDefined();
|
||||
expect(uploadRes.body.fileCategory).toBe('VIDEO');
|
||||
uploadedVideoId = uploadRes.body.id;
|
||||
|
||||
// 2. Run video processing directly to verify FFmpeg and HLS generation
|
||||
await videoProcessor.processVideo(uploadedVideoId);
|
||||
|
||||
// 3. Verify file record is updated with metadata, thumbnail and HLS key
|
||||
const fileRes = await request(app.getHttpServer())
|
||||
.get(`/api/v1/files/${uploadedVideoId}`)
|
||||
.set('Authorization', `Bearer ${userToken}`)
|
||||
.expect(200);
|
||||
|
||||
expect(fileRes.body.status).toBe('READY');
|
||||
expect(fileRes.body.durationSeconds).toBeGreaterThan(0);
|
||||
expect(fileRes.body.width).toBe(640);
|
||||
expect(fileRes.body.height).toBe(360);
|
||||
expect(fileRes.body.videoCodec).toBe('h264');
|
||||
expect(fileRes.body.hasThumbnail).toBe(true);
|
||||
expect(fileRes.body.hasHlsStream).toBe(true);
|
||||
|
||||
// 4. Verify thumbnail can be fetched
|
||||
await request(app.getHttpServer())
|
||||
.get(`/api/v1/files/${uploadedVideoId}/thumbnail`)
|
||||
.set('Authorization', `Bearer ${userToken}`)
|
||||
.expect(200);
|
||||
|
||||
// 5. Verify HLS master playlist can be fetched
|
||||
const hlsRes = await request(app.getHttpServer())
|
||||
.get(`/api/v1/files/${uploadedVideoId}/stream/master.m3u8`)
|
||||
.set('Authorization', `Bearer ${userToken}`)
|
||||
.expect(200);
|
||||
|
||||
expect(hlsRes.text).toContain('#EXTM3U');
|
||||
expect(hlsRes.text).toContain('segment_');
|
||||
|
||||
// 6. Verify HLS media chunk segment can be fetched
|
||||
await request(app.getHttpServer())
|
||||
.get(`/api/v1/files/${uploadedVideoId}/stream/segment_000.ts`)
|
||||
.set('Authorization', `Bearer ${userToken}`)
|
||||
.expect(200);
|
||||
}, 45000);
|
||||
});
|
||||
27
apps/backend/tsconfig.json
Normal file
27
apps/backend/tsconfig.json
Normal file
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"declaration": true,
|
||||
"removeComments": true,
|
||||
"emitDecoratorMetadata": true,
|
||||
"experimentalDecorators": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"target": "ES2021",
|
||||
"sourceMap": true,
|
||||
"outDir": "./dist",
|
||||
"baseUrl": "./",
|
||||
"incremental": true,
|
||||
"skipLibCheck": true,
|
||||
"strictNullChecks": false,
|
||||
"noImplicitAny": false,
|
||||
"strictBindCallApply": false,
|
||||
"forceConsistentCasingInFileNames": false,
|
||||
"noFallthroughCasesInSwitch": false,
|
||||
"paths": {
|
||||
"@fileshare/shared": ["../../packages/shared/src/index.ts"]
|
||||
}
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules", "dist", "test", "**/*.spec.ts", "storage", "../../storage"]
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user