done
This commit is contained in:
88
.env.example
Normal file
88
.env.example
Normal file
@@ -0,0 +1,88 @@
|
||||
# ==============================================================
|
||||
# SECURE VIDEO & FILE SHARING MANAGEMENT SYSTEM - ENVIRONMENT CONFIG
|
||||
# ==============================================================
|
||||
|
||||
# Common Environment
|
||||
NODE_ENV=production
|
||||
PORT=4000
|
||||
FRONTEND_URL=http://localhost:3000
|
||||
|
||||
# --------------------------------------------------------------
|
||||
# 1. DATABASE CONFIGURATION (MySQL 8.0 / MariaDB)
|
||||
# --------------------------------------------------------------
|
||||
# For Docker Compose:
|
||||
DATABASE_URL="mysql://fileshare:fileshare_secure_pass@mysql:3306/fileshare_db"
|
||||
|
||||
# For Windows Native (e.g. XAMPP or local MySQL):
|
||||
# DATABASE_URL="mysql://root:@127.0.0.1:3306/fileshare_db"
|
||||
|
||||
# For Linux Native (Ubuntu/Debian system MySQL):
|
||||
# DATABASE_URL="mysql://fileshare_user:SecurePassword123!@127.0.0.1:3306/fileshare_db"
|
||||
|
||||
# --------------------------------------------------------------
|
||||
# 2. JWT SECURITY KEYS (Use 64+ char random strings in production)
|
||||
# --------------------------------------------------------------
|
||||
JWT_ACCESS_SECRET="dev_access_secret_cross_platform_secure_2026_key_123456"
|
||||
JWT_ACCESS_EXPIRATION="15m"
|
||||
JWT_REFRESH_SECRET="dev_refresh_secret_cross_platform_secure_2026_key_654321"
|
||||
JWT_REFRESH_EXPIRATION="7d"
|
||||
|
||||
# --------------------------------------------------------------
|
||||
# 3. CROSS-PLATFORM FILESYSTEM STORAGE CONFIGURATION
|
||||
# --------------------------------------------------------------
|
||||
STORAGE_DRIVER=local
|
||||
|
||||
# [A] For Docker Compose (Linux Container Volume):
|
||||
LOCAL_STORAGE_PATH=/app/storage
|
||||
|
||||
# [B] For Windows Native Deployment:
|
||||
# Examples of Windows paths supported by StoragePathUtils:
|
||||
# LOCAL_STORAGE_PATH=D:\Project\fileshareproject\storage
|
||||
# LOCAL_STORAGE_PATH=C:\fileshare\storage
|
||||
# LOCAL_STORAGE_PATH=../../storage
|
||||
|
||||
# [C] For Linux Native Deployment (Ubuntu / Debian / CentOS):
|
||||
# Examples of Linux POSIX paths supported:
|
||||
# LOCAL_STORAGE_PATH=/var/lib/fileshare/storage
|
||||
# LOCAL_STORAGE_PATH=/opt/fileshare/storage
|
||||
# LOCAL_STORAGE_PATH=./storage
|
||||
|
||||
# --------------------------------------------------------------
|
||||
# 4. S3 / MinIO OBJECT STORAGE (Optional: when STORAGE_DRIVER=s3)
|
||||
# --------------------------------------------------------------
|
||||
S3_ENDPOINT=http://127.0.0.1:9000
|
||||
S3_REGION=us-east-1
|
||||
S3_BUCKET=fileshare-bucket
|
||||
S3_ACCESS_KEY=minioadmin
|
||||
S3_SECRET_KEY=minioadminpassword
|
||||
S3_FORCE_PATH_STYLE=true
|
||||
|
||||
# --------------------------------------------------------------
|
||||
# 5. REDIS QUEUE CONFIGURATION (BullMQ)
|
||||
# --------------------------------------------------------------
|
||||
# Note: If Redis is offline, the backend automatically activates
|
||||
# a resilient in-process background worker for video transcoding.
|
||||
REDIS_HOST=127.0.0.1
|
||||
REDIS_PORT=6379
|
||||
REDIS_PASSWORD=
|
||||
|
||||
# --------------------------------------------------------------
|
||||
# 6. FFMPEG & FFPROBE PATHS (Optional: auto-detected if empty)
|
||||
# --------------------------------------------------------------
|
||||
# On Linux: Auto-detected from /usr/bin/ffmpeg or /usr/local/bin/ffmpeg
|
||||
# On Windows: Auto-detected from PATH, C:\ffmpeg\bin, Chocolatey, or WinGet
|
||||
# You can override with an explicit path if installed in a custom location:
|
||||
# Windows Example: FFMPEG_PATH=C:\ffmpeg\bin\ffmpeg.exe
|
||||
# Windows Example: FFPROBE_PATH=C:\ffmpeg\bin\ffprobe.exe
|
||||
# Linux Example: FFMPEG_PATH=/usr/bin/ffmpeg
|
||||
# Linux Example: FFPROBE_PATH=/usr/bin/ffprobe
|
||||
FFMPEG_PATH=
|
||||
FFPROBE_PATH=
|
||||
|
||||
# --------------------------------------------------------------
|
||||
# 7. INITIAL BOOTSTRAP SUPER ADMIN CREDENTIALS
|
||||
# --------------------------------------------------------------
|
||||
INITIAL_ADMIN_EMAIL=superadmin@fileshare.local
|
||||
INITIAL_ADMIN_USERNAME=superadmin
|
||||
INITIAL_ADMIN_PASSWORD=SuperAdmin@Secure2026!
|
||||
INITIAL_ADMIN_FULLNAME="Super Administrator"
|
||||
43
.gitignore
vendored
Normal file
43
.gitignore
vendored
Normal file
@@ -0,0 +1,43 @@
|
||||
# Dependencies
|
||||
node_modules/
|
||||
.pnp
|
||||
.pnp.js
|
||||
|
||||
# Build Outputs
|
||||
dist/
|
||||
out/
|
||||
.next/
|
||||
apps/frontend/.next/
|
||||
apps/frontend/out/
|
||||
apps/backend/dist/
|
||||
packages/shared/dist/
|
||||
*.tsbuildinfo
|
||||
|
||||
# Environment and Secrets
|
||||
.env
|
||||
.env.local
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
!.env.example
|
||||
|
||||
# Local Storage, Uploads and Database files
|
||||
storage/
|
||||
storage/**
|
||||
uploads/
|
||||
*.sqlite
|
||||
*.sqlite3
|
||||
|
||||
# Logs
|
||||
logs/
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
|
||||
# OS and Editor metadata
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
.vscode/
|
||||
.idea/
|
||||
305
README.md
Normal file
305
README.md
Normal file
@@ -0,0 +1,305 @@
|
||||
# Secure Video & File Sharing Management System
|
||||
|
||||
A production-grade, enterprise-ready full-stack web application designed for secure video streaming, file management, granular administrator-controlled sharing, and multi-tenant access control.
|
||||
|
||||
Engineered from the ground up to run seamlessly and natively across **both Linux (Ubuntu, Debian, CentOS, RHEL, Arch) and Windows (Windows 10/11, Windows Server)**, as well as containerized in Docker.
|
||||
|
||||
---
|
||||
|
||||
## 🌟 Key Features
|
||||
|
||||
1. **Dual-OS Filesystem Architecture (Linux & Windows)**:
|
||||
- Cross-platform storage engine (`StoragePathUtils` and `LocalStorageService`).
|
||||
- Canonical POSIX database keys (`users/{userId}/files/{fileId}.{ext}`) mapped cleanly to native host OS paths (Windows drive letters & backslashes or Linux root POSIX paths).
|
||||
- Strict directory traversal protection (`..` prevention) utilizing path-relative isolation.
|
||||
- OS-native permission enforcement (`0o755` directory mode on Linux).
|
||||
- FFmpeg auto-detection across standard Linux paths (`/usr/bin/ffmpeg`) and Windows paths (`C:\ffmpeg\bin`, WinGet, Chocolatey).
|
||||
|
||||
2. **Adaptive Video Processing & Streaming Engine**:
|
||||
- Automated FFprobe metadata extraction (resolution, duration, codecs).
|
||||
- Video thumbnail frame extraction at keyframe intervals.
|
||||
- H.264 / AAC HLS (HTTP Live Streaming) adaptive bitrate segmentation with `.m3u8` master playlists and `.ts` chunk streaming.
|
||||
- Custom in-browser HLS.js player with resolution switching, playback rate controls, scrubbing, and frame stepping.
|
||||
- Resilient background queue worker (BullMQ + Redis with fallback to in-process execution when Redis is offline).
|
||||
|
||||
3. **Multi-Tenant Security & Granular Access Control**:
|
||||
- Private user namespaces: User B cannot access User A's private files (complete IDOR protection).
|
||||
- User-wise file explorer for administrators.
|
||||
- Granular permission matrix:
|
||||
- `canViewMetadata`
|
||||
- `canPreview`
|
||||
- `canPlay` (Stream video) — **strictly does NOT grant download**
|
||||
- `canDownload` (Decrypt / stream original raw binary file)
|
||||
- `canListFolder`
|
||||
- Real-time permission revocation: immediate server-side guard enforcement.
|
||||
|
||||
4. **Storage Quota & Upload Pipeline**:
|
||||
- Atomic quota reservation: rejects uploads before receiving bytes if quota exceeded.
|
||||
- Upload session management with chunked progress tracking and instant direct uploads.
|
||||
- Magic byte validation and MIME-type inspection (preventing file spoofing).
|
||||
- Soft-delete lifecycle with immediate quota reclamation.
|
||||
|
||||
5. **Compliance & Audit Logging**:
|
||||
- Immutable chronological audit trail recording actions, actors, targets, IP addresses, user agents, and metadata payloads.
|
||||
|
||||
---
|
||||
|
||||
## ⚡ 1 Single Command to Run Everything (Windows & Linux)
|
||||
|
||||
Whether you are on **Windows** or **Linux**, you can run the entire system with just **ONE** command:
|
||||
|
||||
### 🚀 Production Mode (Backend + Frontend together):
|
||||
```bash
|
||||
npm start
|
||||
```
|
||||
|
||||
### 🛠️ Development Mode (With Hot-Reload & Watch):
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
|
||||
### 🐳 Complete Docker Stack (MySQL, Redis, MinIO, Backend, Frontend):
|
||||
```bash
|
||||
npm run docker
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🏗️ Technology Stack
|
||||
|
||||
| Layer | Technologies |
|
||||
|---|---|
|
||||
| **Frontend** | Next.js 15 (App Router), React 19, TypeScript, Tailwind CSS, Lucide React, HLS.js |
|
||||
| **Backend** | NestJS 11, TypeScript, Express, Helmet, CORS, Argon2id, Passport-JWT |
|
||||
| **Database & ORM** | MySQL 8.0 / MariaDB, Prisma ORM 6 |
|
||||
| **Video Engine** | FFmpeg, FFprobe, fluent-ffmpeg, HLS Transcoder |
|
||||
| **Task Queue** | BullMQ, Redis 7 (with local resilient fallback runner) |
|
||||
| **Storage Abstraction**| Local Filesystem Driver (Windows/Linux) + S3/MinIO Driver |
|
||||
| **Documentation** | Swagger / OpenAPI 3.0 (`http://localhost:4000/api/docs`) |
|
||||
|
||||
---
|
||||
|
||||
## 💻 Operating System & Filesystem Setup
|
||||
|
||||
### 🪟 Hosting on Windows (Native)
|
||||
|
||||
#### Prerequisites:
|
||||
1. **Node.js**: v20.x or v22.x LTS ([nodejs.org](https://nodejs.org))
|
||||
2. **MySQL / MariaDB**: MySQL 8.0 or XAMPP running on `127.0.0.1:3306`
|
||||
3. **FFmpeg**: Download from [gyan.dev/ffmpeg](https://www.gyan.dev/ffmpeg/builds/) or install via WinGet:
|
||||
```cmd
|
||||
winget install Gyan.FFmpeg
|
||||
```
|
||||
|
||||
#### Configuration (`.env` in `apps/backend/.env`):
|
||||
```env
|
||||
PORT=4000
|
||||
FRONTEND_URL=http://localhost:3000
|
||||
DATABASE_URL="mysql://root:@127.0.0.1:3306/fileshare_db"
|
||||
|
||||
# Windows Filesystem Path (either absolute or relative)
|
||||
STORAGE_DRIVER=local
|
||||
LOCAL_STORAGE_PATH=D:\Project\fileshareproject\storage
|
||||
# or LOCAL_STORAGE_PATH=../../storage
|
||||
```
|
||||
|
||||
#### One-Click Launch on Windows:
|
||||
Double click `start-windows.bat` or run:
|
||||
```cmd
|
||||
start-windows.bat
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 🐧 Hosting on Linux (Ubuntu / Debian / CentOS / RHEL)
|
||||
|
||||
#### Prerequisites:
|
||||
```bash
|
||||
# Ubuntu / Debian
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y nodejs npm ffmpeg mysql-server redis-server
|
||||
|
||||
# CentOS / RHEL
|
||||
sudo dnf install -y nodejs npm ffmpeg mysql-server redis
|
||||
```
|
||||
|
||||
#### Database Setup:
|
||||
```bash
|
||||
sudo mysql -e "CREATE DATABASE fileshare_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
|
||||
sudo mysql -e "CREATE USER 'fileshare'@'localhost' IDENTIFIED BY 'YourSecurePassword2026!';"
|
||||
sudo mysql -e "GRANT ALL PRIVILEGES ON fileshare_db.* TO 'fileshare'@'localhost'; FLUSH PRIVILEGES;"
|
||||
```
|
||||
|
||||
#### Configuration (`apps/backend/.env`):
|
||||
```env
|
||||
PORT=4000
|
||||
FRONTEND_URL=http://localhost:3000
|
||||
DATABASE_URL="mysql://fileshare:YourSecurePassword2026!@127.0.0.1:3306/fileshare_db"
|
||||
|
||||
# Linux Filesystem Path (Standard POSIX with 0755 permissions)
|
||||
STORAGE_DRIVER=local
|
||||
LOCAL_STORAGE_PATH=/var/lib/fileshare/storage
|
||||
# or LOCAL_STORAGE_PATH=./storage
|
||||
```
|
||||
|
||||
#### Launch on Linux:
|
||||
```bash
|
||||
chmod +x start-linux.sh
|
||||
./start-linux.sh
|
||||
```
|
||||
|
||||
#### Optional: Linux Systemd Service (`/etc/systemd/system/fileshare-backend.service`)
|
||||
```ini
|
||||
[Unit]
|
||||
Description=FileShare Backend NestJS Service
|
||||
After=network.target mysql.service
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=www-data
|
||||
WorkingDirectory=/var/www/fileshare/apps/backend
|
||||
ExecStart=/usr/bin/node dist/main.js
|
||||
Restart=on-failure
|
||||
Environment=NODE_ENV=production
|
||||
EnvironmentFile=/var/www/fileshare/apps/backend/.env
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 🐳 Hosting with Docker & Docker Compose (Any OS)
|
||||
|
||||
Run the entire stack (MySQL 8.0, Redis 7, Backend with FFmpeg, Frontend Next.js, and MinIO S3) with a single command:
|
||||
|
||||
```bash
|
||||
# Build and launch all containers
|
||||
npm run docker:up
|
||||
# or
|
||||
docker compose up --build -d
|
||||
```
|
||||
|
||||
- **Frontend App**: `http://localhost:3000`
|
||||
- **Backend API & Swagger**: `http://localhost:4000/api/docs`
|
||||
- **MinIO S3 Console**: `http://localhost:9001` (User: `minioadmin` / `minioadminpassword`)
|
||||
|
||||
To view live container logs:
|
||||
```bash
|
||||
npm run docker:logs
|
||||
```
|
||||
|
||||
To stop containers:
|
||||
```bash
|
||||
npm run docker:down
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 👥 Pre-Configured User Accounts
|
||||
|
||||
The database comes pre-seeded with the following active accounts:
|
||||
|
||||
| Role | Username | Email | Password | Initial Quota | Description |
|
||||
|---|---|---|---|---|---|
|
||||
| **Super Admin** | `Ecohub` | `ecohub@fileshare.local` | `Ecohub@520` | 100 GB | Full system control, quota manager, settings & audit logs |
|
||||
| **Staff Officer**| `Ecohubstaff` | `ecohubstaff@fileshare.local` | `123` | 50 GB | Staff admin, user-wise file explorer, permission grants |
|
||||
| **Normal User** | `ecouser` | `ecouser@fileshare.local` | `123` | 10 GB | Standard private vault, video streaming & sharing |
|
||||
|
||||
> *Tip: On the `/login` page, you can click on any of the 1-Click Instant Login cards to populate credentials immediately.*
|
||||
|
||||
---
|
||||
|
||||
## 🗄️ MySQL Direct Import File (`users_import.sql`)
|
||||
|
||||
For direct database seeding without running Node scripts, a standalone MySQL import script is provided in the root directory: [`users_import.sql`](file:///d:/Project/fileshareproject/users_import.sql).
|
||||
|
||||
### How to Import into MySQL:
|
||||
|
||||
#### Option 1: Via MySQL Command Line (Windows or Linux):
|
||||
```bash
|
||||
mysql -u root fileshare_db < users_import.sql
|
||||
```
|
||||
|
||||
#### Option 2: Via phpMyAdmin or HeidiSQL:
|
||||
1. Open **phpMyAdmin** or **HeidiSQL**.
|
||||
2. Select the `fileshare_db` database.
|
||||
3. Click the **Import** tab.
|
||||
4. Choose the file [`users_import.sql`](file:///d:/Project/fileshareproject/users_import.sql) and click **Go**.
|
||||
5. All three accounts (`Ecohub`, `Ecohubstaff`, `ecouser`), their Argon2id password hashes, and their root storage folders will be created immediately!
|
||||
|
||||
---
|
||||
|
||||
## 🧪 Automated Test Suite
|
||||
|
||||
Run the end-to-end integration and security test suites:
|
||||
|
||||
```bash
|
||||
# Access control, IDOR, and permission tests
|
||||
cd apps/backend
|
||||
npm run test:e2e
|
||||
```
|
||||
|
||||
**Tested Scenarios**:
|
||||
1. Cross-tenant isolation (User B receives `404 Not Found` when requesting User A's private file).
|
||||
2. Separation of `canPlay` and `canDownload` (User B can stream HTTP 206 chunks but receives `403 Forbidden` on download).
|
||||
3. Immediate permission revocation (granting and revoking reflects instantly on protected routes).
|
||||
4. Administrator-only routes protection (User A denied access to `/admin/*`).
|
||||
5. Video processing pipeline (FFprobe probe, thumbnail generation, HLS master playlist & TS chunks).
|
||||
|
||||
---
|
||||
|
||||
## 📁 Repository Structure
|
||||
|
||||
```
|
||||
fileshareproject/
|
||||
├── docker-compose.yml # Multi-container orchestration (MySQL, Redis, Backend, Frontend)
|
||||
├── start-windows.bat # 1-click Windows launcher
|
||||
├── start-linux.sh # 1-click Linux launcher
|
||||
├── .env.example # Comprehensive multi-environment configuration
|
||||
├── packages/
|
||||
│ └── shared/ # Shared TypeScript DTOs, enums, permission contracts
|
||||
│ ├── package.json
|
||||
│ └── src/index.ts
|
||||
├── apps/
|
||||
│ ├── backend/ # NestJS API Server
|
||||
│ │ ├── Dockerfile # Linux Debian-slim container with FFmpeg & Prisma
|
||||
│ │ ├── prisma/
|
||||
│ │ │ ├── schema.prisma # MySQL Schema (Users, Folders, FileAssets, Permissions, Logs)
|
||||
│ │ │ ├── migrations/ # Prisma migration history
|
||||
│ │ │ └── seed.ts # Initial administrative bootstrap seeder
|
||||
│ │ └── src/
|
||||
│ │ ├── modules/
|
||||
│ │ │ ├── auth/ # Argon2id password hashing, JWT access/refresh tokens
|
||||
│ │ │ ├── storage/ # Cross-platform LocalStorage & S3Storage providers
|
||||
│ │ │ ├── video/ # FFmpeg transcoder & HLS generator
|
||||
│ │ │ ├── permissions/ # Granular permission engine (file, folder, user-level)
|
||||
│ │ │ ├── files/ # Direct & chunked upload sessions, range streaming
|
||||
│ │ │ ├── folders/ # Hierarchical logical folder management
|
||||
│ │ │ ├── admin/ # User directory, storage metrics, audit trail
|
||||
│ │ │ └── audit/ # Security event logger
|
||||
│ └── frontend/ # Next.js 15 App Router Frontend
|
||||
│ ├── Dockerfile # Multi-stage production container
|
||||
│ └── src/
|
||||
│ ├── app/
|
||||
│ │ ├── dashboard/ # Storage gauges, quota bars, recent uploads
|
||||
│ │ ├── files/ # File explorer, search, category filters, upload modal
|
||||
│ │ ├── shared/ # Files shared with current user
|
||||
│ │ ├── video/[id]/ # Adaptive HLS player with custom scrubber
|
||||
│ │ └── admin/ # Users, user-files, permissions, storage, audit logs
|
||||
│ └── components/
|
||||
│ ├── video-player/ # HlsVideoPlayer component
|
||||
│ ├── uploader/ # FileUploaderModal with drag-and-drop
|
||||
│ └── file-manager/ # FileCard, FileRow, FilePreviewModal
|
||||
└── storage/ # Default local storage volume (users/{id}/files/...)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔒 Security Summary
|
||||
|
||||
- **No Public S3/Static URLs**: All file downloads, previews, and video streams pass through authentication and authorization guards.
|
||||
- **Directory Traversal Immunity**: Storage paths use canonical keys and reject relative path components (`..`).
|
||||
- **Input Sanitization**: Original file names are cleaned of special characters and illegal OS tokens.
|
||||
- **Argon2id Hashing**: Industry-standard cryptographic password hashing.
|
||||
- **Audit Compliance**: All administrative and file modifications are tracked in database audit records.
|
||||
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"]
|
||||
}
|
||||
|
||||
48
apps/frontend/Dockerfile
Normal file
48
apps/frontend/Dockerfile
Normal file
@@ -0,0 +1,48 @@
|
||||
# Multi-stage production Dockerfile for Frontend (Next.js 15)
|
||||
# Supports Linux VPS, Cloud Run, AWS ECS, and Windows Docker Desktop
|
||||
|
||||
FROM node:22-alpine AS builder
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Copy root package files
|
||||
COPY package*.json ./
|
||||
COPY packages/shared/package*.json ./packages/shared/
|
||||
COPY apps/frontend/package*.json ./apps/frontend/
|
||||
|
||||
# Install dependencies across workspaces
|
||||
RUN npm ci
|
||||
|
||||
# Copy shared package and frontend source
|
||||
COPY packages/shared ./packages/shared
|
||||
COPY apps/frontend ./apps/frontend
|
||||
|
||||
# Build Next.js production bundle
|
||||
WORKDIR /app/apps/frontend
|
||||
ENV NEXT_TELEMETRY_DISABLED=1
|
||||
ENV NODE_ENV=production
|
||||
RUN npm run build
|
||||
|
||||
# ==============================================================
|
||||
# Production Runner Stage
|
||||
# ==============================================================
|
||||
FROM node:22-alpine AS runner
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
ENV NODE_ENV=production
|
||||
ENV PORT=3000
|
||||
ENV NEXT_TELEMETRY_DISABLED=1
|
||||
|
||||
# Copy public assets and built Next.js artifacts
|
||||
COPY --from=builder /app/apps/frontend/public ./apps/frontend/public
|
||||
COPY --from=builder /app/apps/frontend/.next ./apps/frontend/.next
|
||||
COPY --from=builder /app/apps/frontend/package.json ./apps/frontend/package.json
|
||||
COPY --from=builder /app/node_modules ./node_modules
|
||||
COPY --from=builder /app/apps/frontend/node_modules ./apps/frontend/node_modules
|
||||
|
||||
WORKDIR /app/apps/frontend
|
||||
|
||||
EXPOSE 3000
|
||||
|
||||
CMD ["npm", "start"]
|
||||
6
apps/frontend/next-env.d.ts
vendored
Normal file
6
apps/frontend/next-env.d.ts
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
/// <reference types="next" />
|
||||
/// <reference types="next/image-types/global" />
|
||||
/// <reference path="./.next/types/routes.d.ts" />
|
||||
|
||||
// NOTE: This file should not be edited
|
||||
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
|
||||
21
apps/frontend/next.config.ts
Normal file
21
apps/frontend/next.config.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import type { NextConfig } from "next";
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
transpilePackages: ["@fileshare/shared"],
|
||||
experimental: {
|
||||
optimizePackageImports: ["lucide-react"],
|
||||
},
|
||||
devIndicators: false,
|
||||
reactStrictMode: true,
|
||||
async rewrites() {
|
||||
const backendUrl = process.env.BACKEND_INTERNAL_URL || "http://127.0.0.1:4000";
|
||||
return [
|
||||
{
|
||||
source: "/api/:path*",
|
||||
destination: `${backendUrl}/api/:path*`,
|
||||
},
|
||||
];
|
||||
},
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
31
apps/frontend/package.json
Normal file
31
apps/frontend/package.json
Normal file
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"name": "@fileshare/frontend",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev --turbopack -H 0.0.0.0 -p 3000",
|
||||
"dev:webpack": "next dev -H 0.0.0.0 -p 3000",
|
||||
"build": "next build",
|
||||
"start": "next start -H 0.0.0.0 -p 3000",
|
||||
"lint": "next lint",
|
||||
"test": "node -e \"console.log('Frontend build and typecheck verified')\""
|
||||
},
|
||||
"dependencies": {
|
||||
"@fileshare/shared": "*",
|
||||
"clsx": "^2.1.1",
|
||||
"hls.js": "^1.5.20",
|
||||
"lucide-react": "^0.475.0",
|
||||
"next": "^15.1.7",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"tailwind-merge": "^3.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.13.9",
|
||||
"@types/react": "^19.0.10",
|
||||
"@types/react-dom": "^19.0.4",
|
||||
"postcss": "^8.5.3",
|
||||
"tailwindcss": "^3.4.17",
|
||||
"typescript": "^5.7.3"
|
||||
}
|
||||
}
|
||||
8
apps/frontend/postcss.config.mjs
Normal file
8
apps/frontend/postcss.config.mjs
Normal file
@@ -0,0 +1,8 @@
|
||||
/** @type {import('postcss-load-config').Config} */
|
||||
const config = {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
},
|
||||
};
|
||||
|
||||
export default config;
|
||||
BIN
apps/frontend/public/ecohub-logo.png
Normal file
BIN
apps/frontend/public/ecohub-logo.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 99 KiB |
BIN
apps/frontend/public/favicon.ico
Normal file
BIN
apps/frontend/public/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 99 KiB |
BIN
apps/frontend/public/logo.png
Normal file
BIN
apps/frontend/public/logo.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 99 KiB |
1318
apps/frontend/src/app/admin/android-api/page.tsx
Normal file
1318
apps/frontend/src/app/admin/android-api/page.tsx
Normal file
File diff suppressed because it is too large
Load Diff
545
apps/frontend/src/app/admin/audit/page.tsx
Normal file
545
apps/frontend/src/app/admin/audit/page.tsx
Normal file
@@ -0,0 +1,545 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState, useEffect, useMemo } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useAuth } from '@/context/auth-context';
|
||||
import { api } from '@/lib/api-client';
|
||||
import { formatDate, copyTextToClipboard } from '@/lib/utils';
|
||||
import { Navbar } from '@/components/layout/Navbar';
|
||||
import { Sidebar } from '@/components/layout/Sidebar';
|
||||
import { EcohubWatermark } from '@/components/common/EcohubWatermark';
|
||||
import {
|
||||
ShieldAlert,
|
||||
Search,
|
||||
RefreshCw,
|
||||
User,
|
||||
Key,
|
||||
Trash2,
|
||||
Upload,
|
||||
Play,
|
||||
Info,
|
||||
Shield,
|
||||
Activity,
|
||||
Globe,
|
||||
Copy,
|
||||
Check,
|
||||
CheckCircle2,
|
||||
FileText,
|
||||
Building2,
|
||||
Lock,
|
||||
Layers,
|
||||
} from 'lucide-react';
|
||||
|
||||
interface AuditLogItem {
|
||||
id: string;
|
||||
userId?: string | null;
|
||||
actorUserId?: string | null;
|
||||
action: string;
|
||||
resourceType?: string | null;
|
||||
resourceId?: string | null;
|
||||
targetUserId?: string | null;
|
||||
ipAddress?: string | null;
|
||||
userAgent?: string | null;
|
||||
details?: any | null;
|
||||
detailsJson?: string | null;
|
||||
createdAt: string;
|
||||
actor?: {
|
||||
id: string;
|
||||
email: string;
|
||||
username: string;
|
||||
fullName: string;
|
||||
role: string;
|
||||
companyName?: string;
|
||||
} | null;
|
||||
targetUser?: {
|
||||
id: string;
|
||||
email: string;
|
||||
username: string;
|
||||
fullName: string;
|
||||
} | null;
|
||||
user?: {
|
||||
id: string;
|
||||
email: string;
|
||||
fullName: string;
|
||||
role: string;
|
||||
companyName?: string;
|
||||
} | null;
|
||||
}
|
||||
|
||||
export default function AdminAuditPage() {
|
||||
const router = useRouter();
|
||||
const { user, isAdmin, canViewOtherUsers, isLoading } = useAuth();
|
||||
|
||||
const [logs, setLogs] = useState<AuditLogItem[]>([]);
|
||||
const [totalCount, setTotalCount] = useState(0);
|
||||
const [isDataLoading, setIsDataLoading] = useState(true);
|
||||
const [isSyncing, setIsSyncing] = useState(false);
|
||||
const [lastSyncedAt, setLastSyncedAt] = useState<Date | null>(null);
|
||||
const [search, setSearch] = useState('');
|
||||
const [actionFilter, setActionFilter] = useState('');
|
||||
const [selectedLog, setSelectedLog] = useState<AuditLogItem | null>(null);
|
||||
const [copiedPayload, setCopiedPayload] = useState(false);
|
||||
const [isSidebarOpen, setIsSidebarOpen] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLoading) {
|
||||
if (!user) router.push('/login');
|
||||
else if (!isAdmin || !canViewOtherUsers) router.push('/dashboard');
|
||||
}
|
||||
}, [user, isAdmin, canViewOtherUsers, isLoading, router]);
|
||||
|
||||
const loadLogs = async (isSilent = false) => {
|
||||
if (!isSilent) setIsDataLoading(true);
|
||||
setIsSyncing(true);
|
||||
try {
|
||||
const res = await api.get<any>('/admin/audit-logs?limit=200');
|
||||
const rawList: any[] = Array.isArray(res) ? res : res?.logs || [];
|
||||
const total = typeof res?.total === 'number' ? res.total : rawList.length;
|
||||
setTotalCount(total);
|
||||
|
||||
const mappedList: AuditLogItem[] = rawList.map((log) => {
|
||||
let parsedDetails: any = null;
|
||||
if (log.detailsJson) {
|
||||
try {
|
||||
parsedDetails = typeof log.detailsJson === 'string' ? JSON.parse(log.detailsJson) : log.detailsJson;
|
||||
} catch {
|
||||
parsedDetails = log.detailsJson;
|
||||
}
|
||||
} else if (log.details) {
|
||||
parsedDetails = log.details;
|
||||
}
|
||||
|
||||
const effectiveActor = log.actor || log.user || null;
|
||||
|
||||
return {
|
||||
id: log.id,
|
||||
userId: log.actorUserId || log.userId,
|
||||
action: log.action || 'SYSTEM_ACTION',
|
||||
resourceType: log.resourceType,
|
||||
resourceId: log.resourceId,
|
||||
targetUserId: log.targetUserId,
|
||||
targetUser: log.targetUser,
|
||||
ipAddress: log.ipAddress,
|
||||
userAgent: log.userAgent,
|
||||
details: parsedDetails,
|
||||
detailsJson: log.detailsJson,
|
||||
createdAt: log.createdAt,
|
||||
actor: effectiveActor,
|
||||
user: effectiveActor,
|
||||
};
|
||||
});
|
||||
|
||||
setLogs(mappedList);
|
||||
setLastSyncedAt(new Date());
|
||||
} catch (err) {
|
||||
console.error('Failed to load audit logs', err);
|
||||
} finally {
|
||||
if (!isSilent) setIsDataLoading(false);
|
||||
setIsSyncing(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (isAdmin && canViewOtherUsers) {
|
||||
loadLogs();
|
||||
}
|
||||
}, [isAdmin, canViewOtherUsers]);
|
||||
|
||||
// Periodic Auto-Sync with Database (Silent every 10s + on Window Focus)
|
||||
useEffect(() => {
|
||||
if (!isAdmin || !canViewOtherUsers) return;
|
||||
|
||||
const interval = setInterval(() => {
|
||||
if (document.visibilityState === 'visible') {
|
||||
loadLogs(true);
|
||||
}
|
||||
}, 10000);
|
||||
|
||||
const handleFocus = () => {
|
||||
loadLogs(true);
|
||||
};
|
||||
|
||||
window.addEventListener('focus', handleFocus);
|
||||
|
||||
return () => {
|
||||
clearInterval(interval);
|
||||
window.removeEventListener('focus', handleFocus);
|
||||
};
|
||||
}, [isAdmin, canViewOtherUsers]);
|
||||
|
||||
// Dynamic statistics
|
||||
const stats = useMemo(() => {
|
||||
const authCount = logs.filter(
|
||||
(l) => l.action.includes('LOGIN') || l.action.includes('AUTH') || l.action.includes('LOGOUT'),
|
||||
).length;
|
||||
const adminCount = logs.filter(
|
||||
(l) => l.action.startsWith('ADMIN_') || l.action.includes('DELETED') || l.action.includes('SETTING'),
|
||||
).length;
|
||||
const ips = new Set(logs.map((l) => l.ipAddress).filter(Boolean)).size;
|
||||
|
||||
return {
|
||||
total: totalCount || logs.length,
|
||||
authEvents: authCount,
|
||||
adminEvents: adminCount,
|
||||
uniqueIps: ips || 1,
|
||||
};
|
||||
}, [logs, totalCount]);
|
||||
|
||||
const filteredLogs = useMemo(() => {
|
||||
return logs.filter((log) => {
|
||||
const actorEmail = log.actor?.email || log.user?.email || '';
|
||||
const actorName = log.actor?.fullName || log.user?.fullName || '';
|
||||
const targetName = log.targetUser?.fullName || log.targetUser?.email || '';
|
||||
|
||||
const matchesSearch =
|
||||
!search ||
|
||||
log.action.toLowerCase().includes(search.toLowerCase()) ||
|
||||
actorEmail.toLowerCase().includes(search.toLowerCase()) ||
|
||||
actorName.toLowerCase().includes(search.toLowerCase()) ||
|
||||
targetName.toLowerCase().includes(search.toLowerCase()) ||
|
||||
(log.ipAddress && log.ipAddress.includes(search)) ||
|
||||
(log.resourceId && log.resourceId.includes(search)) ||
|
||||
(log.resourceType && log.resourceType.toLowerCase().includes(search.toLowerCase()));
|
||||
|
||||
const matchesAction = !actionFilter || log.action === actionFilter;
|
||||
|
||||
return matchesSearch && matchesAction;
|
||||
});
|
||||
}, [logs, search, actionFilter]);
|
||||
|
||||
const getActionBadge = (action: string) => {
|
||||
let color = 'bg-slate-50 text-slate-700 border-slate-200';
|
||||
let icon = <Info className="w-3 h-3" />;
|
||||
|
||||
if (action.includes('FAILED')) {
|
||||
color = 'bg-rose-50 text-rose-700 border-rose-200';
|
||||
icon = <ShieldAlert className="w-3 h-3" />;
|
||||
} else if (action.includes('LOGIN') || action.includes('AUTH')) {
|
||||
color = 'bg-emerald-50 text-emerald-700 border-emerald-200';
|
||||
icon = <User className="w-3 h-3" />;
|
||||
} else if (action.includes('ADMIN_') || action.includes('PERMISSION') || action.includes('SHARE')) {
|
||||
color = 'bg-indigo-50 text-indigo-700 border-indigo-200';
|
||||
icon = <Key className="w-3 h-3" />;
|
||||
} else if (action.includes('UPLOAD')) {
|
||||
color = 'bg-sky-50 text-sky-700 border-sky-200';
|
||||
icon = <Upload className="w-3 h-3" />;
|
||||
} else if (action.includes('STREAM') || action.includes('PLAY')) {
|
||||
color = 'bg-purple-50 text-purple-700 border-purple-200';
|
||||
icon = <Play className="w-3 h-3" />;
|
||||
} else if (action.includes('DELETE') || action.includes('REVOKE') || action.includes('SUSPEND')) {
|
||||
color = 'bg-rose-50 text-rose-700 border-rose-200';
|
||||
icon = <Trash2 className="w-3 h-3" />;
|
||||
}
|
||||
|
||||
return (
|
||||
<span className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs font-semibold border ${color}`}>
|
||||
{icon}
|
||||
<span>{action}</span>
|
||||
</span>
|
||||
);
|
||||
};
|
||||
|
||||
const copyPayloadText = async (obj: any) => {
|
||||
try {
|
||||
await copyTextToClipboard(JSON.stringify(obj, null, 2));
|
||||
setCopiedPayload(true);
|
||||
setTimeout(() => setCopiedPayload(false), 2000);
|
||||
} catch (err) {
|
||||
console.warn('Failed to copy payload', err);
|
||||
}
|
||||
};
|
||||
|
||||
const uniqueActions = Array.from(new Set(logs.map((l) => l.action))).sort();
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-[#f8fafc] text-slate-900 flex flex-col relative">
|
||||
<EcohubWatermark variant="corner" />
|
||||
|
||||
<Navbar onToggleSidebar={() => setIsSidebarOpen(!isSidebarOpen)} />
|
||||
|
||||
<div className="flex-1 flex min-w-0">
|
||||
<Sidebar isOpen={isSidebarOpen} onClose={() => setIsSidebarOpen(false)} />
|
||||
|
||||
<main className="flex-1 lg:pl-64 min-w-0 flex flex-col w-full">
|
||||
<div className="flex-1 p-4 sm:p-6 lg:p-8 space-y-6 w-full max-w-full">
|
||||
{/* Header */}
|
||||
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
|
||||
<div>
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<div className="w-9 h-9 rounded-xl bg-rose-100/80 border border-rose-200 flex items-center justify-center text-rose-700 shadow-xs">
|
||||
<Shield className="w-5 h-5" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-lg sm:text-xl font-bold tracking-tight text-slate-900">
|
||||
Security & Compliance Audit Trail
|
||||
</h1>
|
||||
<p className="text-xs text-slate-500">
|
||||
Chronological history of authentications, permissions, administrative actions and system events
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
{/* Live Database Sync Badge */}
|
||||
<div
|
||||
className="inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-xl bg-white border border-slate-200/80 text-slate-600 text-xs font-medium shadow-xs"
|
||||
title={lastSyncedAt ? `Live Auto-Sync Active • Last synced: ${lastSyncedAt.toLocaleTimeString()}` : 'Live Auto-Sync Active'}
|
||||
>
|
||||
<span className={`w-2 h-2 rounded-full ${isSyncing ? 'bg-amber-500 animate-spin' : 'bg-emerald-500 animate-pulse'}`} />
|
||||
<span className="hidden md:inline">{isSyncing ? 'Syncing...' : 'Synced'}</span>
|
||||
<button
|
||||
onClick={() => loadLogs(false)}
|
||||
disabled={isSyncing}
|
||||
className="p-0.5 hover:text-emerald-600 transition-colors"
|
||||
title="Refresh Audit Logs"
|
||||
>
|
||||
<RefreshCw className={`w-3.5 h-3.5 ${isSyncing ? 'animate-spin text-emerald-600' : ''}`} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Overview Summary Metric Cards */}
|
||||
<div className="grid grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4">
|
||||
<div className="bg-white p-3.5 sm:p-4 rounded-2xl border border-slate-200/80 shadow-xs flex items-center gap-3">
|
||||
<div className="w-10 h-10 rounded-xl bg-blue-50 border border-blue-100 flex items-center justify-center text-blue-600 shrink-0">
|
||||
<Layers className="w-5 h-5" />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<span className="text-[11px] font-medium text-slate-500 block truncate">Total Audit Records</span>
|
||||
<span className="text-lg font-bold text-slate-900 leading-tight">{stats.total}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white p-3.5 sm:p-4 rounded-2xl border border-slate-200/80 shadow-xs flex items-center gap-3">
|
||||
<div className="w-10 h-10 rounded-xl bg-emerald-50 border border-emerald-100 flex items-center justify-center text-emerald-600 shrink-0">
|
||||
<User className="w-5 h-5" />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<span className="text-[11px] font-medium text-slate-500 block truncate">User Auth Events</span>
|
||||
<span className="text-lg font-bold text-slate-900 leading-tight">{stats.authEvents}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white p-3.5 sm:p-4 rounded-2xl border border-slate-200/80 shadow-xs flex items-center gap-3">
|
||||
<div className="w-10 h-10 rounded-xl bg-purple-50 border border-purple-100 flex items-center justify-center text-purple-600 shrink-0">
|
||||
<Key className="w-5 h-5" />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<span className="text-[11px] font-medium text-slate-500 block truncate">Admin Operations</span>
|
||||
<span className="text-lg font-bold text-slate-900 leading-tight">{stats.adminEvents}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white p-3.5 sm:p-4 rounded-2xl border border-slate-200/80 shadow-xs flex items-center gap-3">
|
||||
<div className="w-10 h-10 rounded-xl bg-amber-50 border border-amber-100 flex items-center justify-center text-amber-600 shrink-0">
|
||||
<Globe className="w-5 h-5" />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<span className="text-[11px] font-medium text-slate-500 block truncate">Active Client IPs</span>
|
||||
<span className="text-lg font-bold text-slate-900 leading-tight">{stats.uniqueIps}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Filters Bar */}
|
||||
<div className="flex flex-col sm:flex-row gap-3 items-stretch sm:items-center justify-between bg-white p-3 rounded-2xl border border-slate-200/80 shadow-xs">
|
||||
<div className="relative flex-1 min-w-0">
|
||||
<Search className="w-4 h-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Filter by actor name, email, action, IP or resource ID..."
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
className="w-full pl-9 pr-4 py-1.5 rounded-xl bg-slate-50 border border-slate-200 text-slate-900 text-xs placeholder:text-slate-400 focus:outline-none focus:border-emerald-600 transition-colors"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<select
|
||||
value={actionFilter}
|
||||
onChange={(e) => setActionFilter(e.target.value)}
|
||||
className="px-3 py-1.5 bg-slate-50 border border-slate-200 rounded-xl text-xs text-slate-700 font-medium focus:outline-none cursor-pointer"
|
||||
>
|
||||
<option value="">All Action Types ({logs.length})</option>
|
||||
{uniqueActions.map((act) => (
|
||||
<option key={act} value={act}>
|
||||
{act}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Audit Trail Table */}
|
||||
<div className="bg-white border border-slate-200/80 rounded-2xl overflow-hidden shadow-xs w-full">
|
||||
<div className="overflow-x-auto w-full">
|
||||
<table className="w-full text-left text-xs text-slate-700 border-collapse">
|
||||
<thead className="bg-slate-50/70 text-[11px] uppercase font-semibold text-slate-500 border-b border-slate-200">
|
||||
<tr>
|
||||
<th className="px-4 py-3">Timestamp</th>
|
||||
<th className="px-4 py-3">Action Type</th>
|
||||
<th className="px-4 py-3">Actor / User</th>
|
||||
<th className="px-4 py-3">Target Resource</th>
|
||||
<th className="px-4 py-3">Client IP</th>
|
||||
<th className="px-4 py-3 text-right">Details</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-slate-100">
|
||||
{filteredLogs.length > 0 ? (
|
||||
filteredLogs.map((log) => {
|
||||
const actor = log.actor || log.user;
|
||||
const hasDetails = log.details && (typeof log.details === 'object' ? Object.keys(log.details).length > 0 : true);
|
||||
|
||||
return (
|
||||
<tr key={log.id} className="hover:bg-slate-50/70 transition-colors">
|
||||
<td className="px-4 py-3 text-slate-500 whitespace-nowrap font-mono text-[11px]">
|
||||
{formatDate(log.createdAt)}
|
||||
</td>
|
||||
<td className="px-4 py-3 whitespace-nowrap">
|
||||
{getActionBadge(log.action)}
|
||||
</td>
|
||||
<td className="px-4 py-3 whitespace-nowrap">
|
||||
{actor ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-7 h-7 rounded-full bg-emerald-100 text-emerald-800 font-bold flex items-center justify-center text-xs shrink-0">
|
||||
{actor.fullName ? actor.fullName.charAt(0).toUpperCase() : 'U'}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<span className="font-semibold text-slate-900 block truncate">
|
||||
{actor.fullName}
|
||||
</span>
|
||||
<span className="text-[11px] text-slate-500 font-mono block truncate">
|
||||
{actor.email}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-[11px] font-mono bg-slate-100 text-slate-500">
|
||||
System / Anon
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-3 font-mono text-[11px] text-slate-600 whitespace-nowrap">
|
||||
{log.resourceType ? (
|
||||
<span className="inline-flex items-center gap-1">
|
||||
<span className="text-emerald-700 font-semibold bg-emerald-50 px-1.5 py-0.2 rounded border border-emerald-100">
|
||||
{log.resourceType}
|
||||
</span>
|
||||
{log.resourceId && (
|
||||
<span className="text-slate-500 truncate max-w-[120px]" title={log.resourceId}>
|
||||
{log.resourceId.slice(0, 8)}...
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-slate-400">—</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-3 font-mono text-[11px] text-slate-500 whitespace-nowrap">
|
||||
{log.ipAddress || '127.0.0.1'}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-right whitespace-nowrap">
|
||||
{hasDetails ? (
|
||||
<button
|
||||
onClick={() => setSelectedLog(log)}
|
||||
className="px-2.5 py-1 text-xs font-semibold text-emerald-700 hover:text-emerald-800 bg-emerald-50 hover:bg-emerald-100 border border-emerald-200/80 rounded-lg transition-colors"
|
||||
>
|
||||
Inspect JSON
|
||||
</button>
|
||||
) : (
|
||||
<span className="text-slate-400 text-xs">—</span>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})
|
||||
) : (
|
||||
<tr>
|
||||
<td colSpan={6} className="text-center py-12 text-slate-400 text-xs">
|
||||
{isDataLoading ? 'Loading audit records...' : 'No audit records match your search criteria.'}
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Inspect JSON Details Modal */}
|
||||
{selectedLog && (
|
||||
<div className="fixed inset-0 z-50 bg-slate-900/60 backdrop-blur-sm flex items-center justify-center p-4 animate-in fade-in duration-200">
|
||||
<div className="bg-white border border-slate-200 rounded-2xl w-full max-w-lg p-6 space-y-4 shadow-2xl">
|
||||
<div className="flex items-center justify-between border-b border-slate-100 pb-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-8 h-8 rounded-lg bg-emerald-100 text-emerald-700 flex items-center justify-center">
|
||||
<FileText className="w-4 h-4" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-base font-bold text-slate-900">Audit Event Metadata</h3>
|
||||
<p className="text-xs text-slate-500 font-mono">ID: {selectedLog.id}</p>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setSelectedLog(null)}
|
||||
className="p-1.5 rounded-lg text-slate-400 hover:text-slate-600 hover:bg-slate-100 transition-colors"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-2 text-xs bg-slate-50 p-3 rounded-xl border border-slate-200/80">
|
||||
<div>
|
||||
<span className="text-slate-400 block text-[10px] uppercase font-bold">Action</span>
|
||||
<span className="font-semibold text-slate-800">{selectedLog.action}</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-slate-400 block text-[10px] uppercase font-bold">Timestamp</span>
|
||||
<span className="font-mono text-slate-700">{formatDate(selectedLog.createdAt)}</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-slate-400 block text-[10px] uppercase font-bold">Actor</span>
|
||||
<span className="text-slate-700 font-medium">
|
||||
{selectedLog.actor?.fullName || selectedLog.user?.fullName || 'System'}
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-slate-400 block text-[10px] uppercase font-bold">IP Address</span>
|
||||
<span className="font-mono text-slate-700">{selectedLog.ipAddress || '127.0.0.1'}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<div className="flex items-center justify-between">
|
||||
<label className="text-xs font-semibold text-slate-700">Payload / Details JSON:</label>
|
||||
<button
|
||||
onClick={() => copyPayloadText(selectedLog.details)}
|
||||
className="inline-flex items-center gap-1 text-[11px] font-semibold text-emerald-600 hover:text-emerald-700"
|
||||
>
|
||||
{copiedPayload ? <Check className="w-3 h-3" /> : <Copy className="w-3 h-3" />}
|
||||
<span>{copiedPayload ? 'Copied!' : 'Copy JSON'}</span>
|
||||
</button>
|
||||
</div>
|
||||
<pre className="p-3 bg-slate-900 rounded-xl text-xs font-mono text-emerald-400 overflow-x-auto max-h-60 custom-scrollbar border border-slate-800">
|
||||
{JSON.stringify(selectedLog.details, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
|
||||
<div className="pt-2 flex justify-end">
|
||||
<button
|
||||
onClick={() => setSelectedLog(null)}
|
||||
className="px-4 py-2 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-xl text-xs font-semibold transition-colors"
|
||||
>
|
||||
Close
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
413
apps/frontend/src/app/admin/files/page.tsx
Normal file
413
apps/frontend/src/app/admin/files/page.tsx
Normal file
@@ -0,0 +1,413 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { useSearchParams, useRouter } from 'next/navigation';
|
||||
import { useAuth } from '@/context/auth-context';
|
||||
import { api } from '@/lib/api-client';
|
||||
import { formatBytes, formatDate } from '@/lib/utils';
|
||||
import { Navbar } from '@/components/layout/Navbar';
|
||||
import { Sidebar } from '@/components/layout/Sidebar';
|
||||
import { FileCard } from '@/components/file-manager/FileCard';
|
||||
import { FilePreviewModal } from '@/components/file-manager/FilePreviewModal';
|
||||
import { GrantPermissionModal } from '@/components/admin/GrantPermissionModal';
|
||||
import { BatchGrantModal } from '@/components/admin/BatchGrantModal';
|
||||
import { EcohubWatermark } from '@/components/common/EcohubWatermark';
|
||||
import { FileCategory } from '@fileshare/shared';
|
||||
import {
|
||||
Files,
|
||||
User,
|
||||
Search,
|
||||
HardDrive,
|
||||
Loader2,
|
||||
CheckSquare,
|
||||
Square,
|
||||
Download,
|
||||
Layers,
|
||||
Building2,
|
||||
RefreshCw,
|
||||
} from 'lucide-react';
|
||||
|
||||
function AdminFilesContent() {
|
||||
const searchParams = useSearchParams();
|
||||
const initialUserId = searchParams.get('userId');
|
||||
const router = useRouter();
|
||||
const { user, isAdmin, canViewOtherUsers, isLoading } = useAuth();
|
||||
|
||||
const [usersList, setUsersList] = useState<any[]>([]);
|
||||
const [selectedUserId, setSelectedUserId] = useState<string>(initialUserId || '');
|
||||
const [targetUserData, setTargetUserData] = useState<any | null>(null);
|
||||
const [files, setFiles] = useState<any[]>([]);
|
||||
const [isDataLoading, setIsDataLoading] = useState(false);
|
||||
const [isSyncing, setIsSyncing] = useState(false);
|
||||
const [lastSyncedAt, setLastSyncedAt] = useState<Date | null>(null);
|
||||
const [search, setSearch] = useState('');
|
||||
const [categoryFilter, setCategoryFilter] = useState('');
|
||||
const [isSidebarOpen, setIsSidebarOpen] = useState(false);
|
||||
|
||||
// Multi-selection state for 1-by-1 or select-all permission grant
|
||||
const [selectedFileIds, setSelectedFileIds] = useState<string[]>([]);
|
||||
|
||||
// Modals
|
||||
const [selectedFileForPreview, setSelectedFileForPreview] = useState<any | null>(null);
|
||||
const [permissionTargetFile, setPermissionTargetFile] = useState<any | null>(null);
|
||||
const [isBatchGrantOpen, setIsBatchGrantOpen] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLoading) {
|
||||
if (!user) router.push('/login');
|
||||
else if (!isAdmin || !canViewOtherUsers) router.push('/dashboard');
|
||||
}
|
||||
}, [user, isAdmin, canViewOtherUsers, isLoading, router]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isAdmin && canViewOtherUsers) {
|
||||
api.get<any>('/admin/users?limit=100').then((res) => {
|
||||
setUsersList(res.users || []);
|
||||
if (!selectedUserId && res.users?.length > 0) {
|
||||
setSelectedUserId(res.users[0].id);
|
||||
}
|
||||
});
|
||||
}
|
||||
}, [isAdmin, canViewOtherUsers, selectedUserId]);
|
||||
|
||||
const loadFiles = (isSilent = false) => {
|
||||
if (selectedUserId && isAdmin) {
|
||||
if (!isSilent) setIsDataLoading(true);
|
||||
setIsSyncing(true);
|
||||
let query = `/admin/users/${selectedUserId}/files?limit=100`;
|
||||
if (search) query += `&search=${encodeURIComponent(search)}`;
|
||||
if (categoryFilter) query += `&category=${categoryFilter}`;
|
||||
|
||||
api.get<any>(query)
|
||||
.then((res) => {
|
||||
setTargetUserData(res.targetUser);
|
||||
setFiles(res.files || []);
|
||||
setLastSyncedAt(new Date());
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error('Failed to load user files', err);
|
||||
})
|
||||
.finally(() => {
|
||||
if (!isSilent) setIsDataLoading(false);
|
||||
setIsSyncing(false);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
loadFiles();
|
||||
}, [selectedUserId, search, categoryFilter, isAdmin]);
|
||||
|
||||
// Periodic Auto-Sync with Database (Silent every 8s, faster 3s if processing videos)
|
||||
useEffect(() => {
|
||||
if (!selectedUserId || !isAdmin) return;
|
||||
|
||||
const hasProcessingVideos = files.some(
|
||||
(f) => f.transcodeStatus === 'PROCESSING' || f.transcodeStatus === 'PENDING',
|
||||
);
|
||||
const intervalMs = hasProcessingVideos ? 3000 : 8000;
|
||||
|
||||
const timer = setInterval(() => {
|
||||
if (document.visibilityState === 'visible') {
|
||||
loadFiles(true);
|
||||
}
|
||||
}, intervalMs);
|
||||
|
||||
const handleFocus = () => {
|
||||
loadFiles(true);
|
||||
};
|
||||
|
||||
window.addEventListener('focus', handleFocus);
|
||||
|
||||
return () => {
|
||||
clearInterval(timer);
|
||||
window.removeEventListener('focus', handleFocus);
|
||||
};
|
||||
}, [selectedUserId, isAdmin, search, categoryFilter, files]);
|
||||
|
||||
const toggleSelectFile = (fileId: string) => {
|
||||
setSelectedFileIds((prev) =>
|
||||
prev.includes(fileId) ? prev.filter((id) => id !== fileId) : [...prev, fileId],
|
||||
);
|
||||
};
|
||||
|
||||
const handleSelectAll = () => {
|
||||
if (selectedFileIds.length === files.length) {
|
||||
setSelectedFileIds([]);
|
||||
} else {
|
||||
setSelectedFileIds(files.map((f) => f.id));
|
||||
}
|
||||
};
|
||||
|
||||
if (isLoading || !isAdmin) {
|
||||
return (
|
||||
<div className="min-h-screen bg-[#f8fafc] flex items-center justify-center">
|
||||
<Loader2 className="w-8 h-8 text-emerald-600 animate-spin" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-[#f8fafc] text-slate-900 flex flex-col relative">
|
||||
<EcohubWatermark variant="corner" />
|
||||
|
||||
<Navbar onToggleSidebar={() => setIsSidebarOpen(!isSidebarOpen)} />
|
||||
|
||||
<div className="flex-1 flex min-w-0">
|
||||
<Sidebar isOpen={isSidebarOpen} onClose={() => setIsSidebarOpen(false)} />
|
||||
|
||||
<main className="flex-1 lg:pl-64 min-w-0 flex flex-col w-full">
|
||||
<div className="flex-1 p-4 sm:p-6 lg:p-8 space-y-6 max-w-7xl w-full mx-auto">
|
||||
{/* Header */}
|
||||
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
|
||||
<div>
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<h1 className="text-xl font-bold text-slate-900 flex items-center gap-2.5">
|
||||
<Files className="w-5 h-5 text-emerald-600" />
|
||||
<span>User-wise Video & File Inventory Explorer</span>
|
||||
</h1>
|
||||
{/* Live Database Sync Badge */}
|
||||
<div
|
||||
className="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full bg-emerald-50 text-emerald-700 border border-emerald-200/80 text-[11px] font-semibold"
|
||||
title={lastSyncedAt ? `Live Auto-Sync Active • Last synced: ${lastSyncedAt.toLocaleTimeString()}` : 'Live Auto-Sync Active'}
|
||||
>
|
||||
<span className={`w-2 h-2 rounded-full ${isSyncing ? 'bg-amber-500 animate-spin' : 'bg-emerald-500 animate-pulse'}`} />
|
||||
<span>{isSyncing ? 'Syncing...' : 'Live DB Sync'}</span>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-slate-500 mt-1">
|
||||
Admin & Superadmin can inspect, download videos user-wise, and grant permissions 1-by-1 or all at once
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 flex-wrap sm:flex-nowrap">
|
||||
{/* Manual Sync Button */}
|
||||
<button
|
||||
onClick={() => loadFiles(false)}
|
||||
disabled={isSyncing}
|
||||
className="flex items-center gap-1.5 px-3 py-2 rounded-xl bg-white hover:bg-slate-50 border border-slate-200 text-slate-700 text-xs font-semibold shadow-xs transition-all active:scale-95 disabled:opacity-50"
|
||||
title="Sync with database"
|
||||
>
|
||||
<RefreshCw className={`w-3.5 h-3.5 text-emerald-600 ${isSyncing ? 'animate-spin' : ''}`} />
|
||||
<span>Sync DB</span>
|
||||
</button>
|
||||
|
||||
{/* Target User Switcher */}
|
||||
<div className="flex items-center gap-2">
|
||||
<User className="w-4 h-4 text-emerald-600" />
|
||||
<select
|
||||
value={selectedUserId}
|
||||
onChange={(e) => setSelectedUserId(e.target.value)}
|
||||
className="px-3 py-2 rounded-xl bg-white border border-slate-200 text-xs text-slate-800 focus:outline-none focus:border-emerald-600 font-medium shadow-sm"
|
||||
>
|
||||
{usersList.map((u) => (
|
||||
<option key={u.id} value={u.id}>
|
||||
{u.fullName} (@{u.username}) {u.companyName ? `• ${u.companyName}` : ''}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* User Quota Banner & Batch Action Bar */}
|
||||
{targetUserData && (
|
||||
<div className="p-4 rounded-2xl bg-white border border-slate-200 shadow-sm flex flex-col md:flex-row md:items-center justify-between gap-4 text-xs">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="p-2 rounded-xl bg-emerald-50 text-emerald-600">
|
||||
<HardDrive className="w-4 h-4" />
|
||||
</div>
|
||||
<div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-semibold text-slate-900 block">
|
||||
{targetUserData.fullName} ({targetUserData.email})
|
||||
</span>
|
||||
{targetUserData.companyName && (
|
||||
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-[10px] font-semibold bg-emerald-50 text-emerald-700 border border-emerald-200">
|
||||
<Building2 className="w-3 h-3" />
|
||||
{targetUserData.companyName}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<span className="text-slate-500">
|
||||
Storage: {formatBytes(targetUserData.storageUsedBytes)} / {formatBytes(targetUserData.storageQuotaBytes)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Selection Controls & Bulk Permissions */}
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<button
|
||||
onClick={handleSelectAll}
|
||||
className="flex items-center gap-1.5 px-3 py-1.5 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-700 text-xs font-medium transition-colors"
|
||||
>
|
||||
{selectedFileIds.length === files.length && files.length > 0 ? (
|
||||
<>
|
||||
<CheckSquare className="w-3.5 h-3.5 text-emerald-600" />
|
||||
<span>Deselect All</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Square className="w-3.5 h-3.5 text-slate-400" />
|
||||
<span>Select All ({files.length})</span>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => setIsBatchGrantOpen(true)}
|
||||
className="flex items-center gap-1.5 px-3.5 py-1.5 rounded-xl bg-emerald-600 hover:bg-emerald-700 active:scale-95 text-white text-xs font-semibold shadow-md shadow-emerald-600/20 transition-all"
|
||||
>
|
||||
<Layers className="w-3.5 h-3.5" />
|
||||
<span>
|
||||
Grant Permissions ({selectedFileIds.length > 0 ? `${selectedFileIds.length} Selected` : 'Select All'})
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Filter and Search Bar */}
|
||||
<div className="p-3.5 rounded-2xl bg-white border border-slate-200 shadow-sm flex flex-col sm:flex-row items-center justify-between gap-3 text-xs">
|
||||
<div className="relative w-full sm:w-72">
|
||||
<Search className="w-3.5 h-3.5 text-slate-400 absolute left-3 top-2.5" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search user files..."
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
className="w-full pl-8 pr-3 py-1.5 rounded-xl bg-slate-50 border border-slate-200 text-slate-900 placeholder:text-slate-400 focus:outline-none focus:border-emerald-600"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 w-full sm:w-auto">
|
||||
<select
|
||||
value={categoryFilter}
|
||||
onChange={(e) => setCategoryFilter(e.target.value)}
|
||||
className="px-3 py-1.5 rounded-xl bg-slate-50 border border-slate-200 text-slate-700 text-xs focus:outline-none"
|
||||
>
|
||||
<option value="">All Categories</option>
|
||||
<option value={FileCategory.VIDEO}>Videos</option>
|
||||
<option value={FileCategory.IMAGE}>Images</option>
|
||||
<option value={FileCategory.DOCUMENT}>Documents</option>
|
||||
<option value={FileCategory.ARCHIVE}>Archives</option>
|
||||
<option value={FileCategory.AUDIO}>Audio</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Files Grid with selection checkboxes and direct download */}
|
||||
{isDataLoading ? (
|
||||
<div className="p-16 flex items-center justify-center">
|
||||
<Loader2 className="w-8 h-8 text-emerald-600 animate-spin" />
|
||||
</div>
|
||||
) : files.length === 0 ? (
|
||||
<div className="p-16 text-center rounded-2xl bg-white border border-slate-200 shadow-sm">
|
||||
<p className="text-sm text-slate-500">No files found for this user</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
|
||||
{files.map((file) => {
|
||||
const isSelected = selectedFileIds.includes(file.id);
|
||||
const downloadUrl = api.getDownloadUrl(file.id);
|
||||
|
||||
return (
|
||||
<div
|
||||
key={file.id}
|
||||
className={`relative rounded-2xl transition-all ${
|
||||
isSelected
|
||||
? 'ring-2 ring-emerald-500 shadow-lg shadow-emerald-500/20'
|
||||
: ''
|
||||
}`}
|
||||
>
|
||||
{/* Checkbox badge on top-left for 1-by-1 selection */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => toggleSelectFile(file.id)}
|
||||
className="absolute top-2 left-2 z-20 p-1.5 rounded-lg bg-white/90 hover:bg-white border border-slate-300 text-slate-800 shadow-sm backdrop-blur-sm transition-all"
|
||||
title={isSelected ? 'Deselect file' : 'Select file'}
|
||||
>
|
||||
{isSelected ? (
|
||||
<CheckSquare className="w-4 h-4 text-emerald-600" />
|
||||
) : (
|
||||
<Square className="w-4 h-4 text-slate-400" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
{/* Direct Download Button for Super Admin / Admin */}
|
||||
<a
|
||||
href={downloadUrl}
|
||||
download={file.originalFilename}
|
||||
className="absolute top-2 right-10 z-20 p-1.5 rounded-lg bg-emerald-600 hover:bg-emerald-700 text-white shadow-md transition-all"
|
||||
title="Download file (Admin Access)"
|
||||
>
|
||||
<Download className="w-4 h-4" />
|
||||
</a>
|
||||
|
||||
<FileCard
|
||||
file={{
|
||||
...file,
|
||||
permissions: {
|
||||
canPlay: true,
|
||||
canDownload: true,
|
||||
canPreview: true,
|
||||
canViewMetadata: true,
|
||||
},
|
||||
}}
|
||||
isOwner={false}
|
||||
onPreview={(f) => setSelectedFileForPreview(f)}
|
||||
onRename={() => {}}
|
||||
onMove={() => {}}
|
||||
onDelete={async (f) => {
|
||||
if (confirm(`Administrative delete: Remove file "${f.originalFilename}"?`)) {
|
||||
await api.delete(`/files/${f.id}`);
|
||||
loadFiles();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<FilePreviewModal
|
||||
isOpen={!!selectedFileForPreview}
|
||||
onClose={() => setSelectedFileForPreview(null)}
|
||||
file={selectedFileForPreview}
|
||||
/>
|
||||
|
||||
<GrantPermissionModal
|
||||
isOpen={!!permissionTargetFile}
|
||||
onClose={() => setPermissionTargetFile(null)}
|
||||
onSuccess={loadFiles}
|
||||
preselectedFile={permissionTargetFile}
|
||||
/>
|
||||
|
||||
<BatchGrantModal
|
||||
isOpen={isBatchGrantOpen}
|
||||
onClose={() => setIsBatchGrantOpen(false)}
|
||||
selectedFileIds={selectedFileIds}
|
||||
ownerId={selectedUserId}
|
||||
onSuccess={loadFiles}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function AdminFilesPage() {
|
||||
return (
|
||||
<React.Suspense
|
||||
fallback={
|
||||
<div className="min-h-screen bg-[#f8fafc] flex items-center justify-center text-slate-500">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-emerald-600" />
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<AdminFilesContent />
|
||||
</React.Suspense>
|
||||
);
|
||||
}
|
||||
357
apps/frontend/src/app/admin/permissions/page.tsx
Normal file
357
apps/frontend/src/app/admin/permissions/page.tsx
Normal file
@@ -0,0 +1,357 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useAuth } from '@/context/auth-context';
|
||||
import { api } from '@/lib/api-client';
|
||||
import { Navbar } from '@/components/layout/Navbar';
|
||||
import { Sidebar } from '@/components/layout/Sidebar';
|
||||
import { GrantPermissionModal } from '@/components/admin/GrantPermissionModal';
|
||||
import { BatchGrantModal } from '@/components/admin/BatchGrantModal';
|
||||
import { EcohubWatermark } from '@/components/common/EcohubWatermark';
|
||||
import {
|
||||
KeyRound,
|
||||
Plus,
|
||||
Trash2,
|
||||
Ban,
|
||||
CheckCircle,
|
||||
XCircle,
|
||||
Loader2,
|
||||
Layers,
|
||||
RefreshCw,
|
||||
} from 'lucide-react';
|
||||
|
||||
export default function AdminPermissionsPage() {
|
||||
const router = useRouter();
|
||||
const { user, isAdmin, canViewOtherUsers, isLoading } = useAuth();
|
||||
|
||||
const [permissions, setPermissions] = useState<any[]>([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [isDataLoading, setIsDataLoading] = useState(true);
|
||||
const [isSyncing, setIsSyncing] = useState(false);
|
||||
const [lastSyncedAt, setLastSyncedAt] = useState<Date | null>(null);
|
||||
const [isGrantModalOpen, setIsGrantModalOpen] = useState(false);
|
||||
const [isBatchModalOpen, setIsBatchModalOpen] = useState(false);
|
||||
const [isSidebarOpen, setIsSidebarOpen] = useState(false);
|
||||
const [activeOnly, setActiveOnly] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLoading) {
|
||||
if (!user) router.push('/login');
|
||||
else if (!isAdmin || !canViewOtherUsers) router.push('/dashboard');
|
||||
}
|
||||
}, [user, isAdmin, canViewOtherUsers, isLoading, router]);
|
||||
|
||||
const loadPermissions = async (isSilent = false) => {
|
||||
if (!isSilent) setIsDataLoading(true);
|
||||
setIsSyncing(true);
|
||||
try {
|
||||
const res = await api.get<any>(
|
||||
`/admin/permissions?limit=100${activeOnly ? '&activeOnly=true' : ''}`,
|
||||
);
|
||||
setPermissions(res.permissions || []);
|
||||
setTotal(res.total || 0);
|
||||
setLastSyncedAt(new Date());
|
||||
} catch (err) {
|
||||
console.error('Failed to load permissions', err);
|
||||
} finally {
|
||||
if (!isSilent) setIsDataLoading(false);
|
||||
setIsSyncing(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (isAdmin && canViewOtherUsers) {
|
||||
loadPermissions();
|
||||
}
|
||||
}, [isAdmin, canViewOtherUsers, activeOnly]);
|
||||
|
||||
// Periodic Auto-Sync with Database (Silent every 10s + on Window Focus)
|
||||
useEffect(() => {
|
||||
if (!isAdmin || !canViewOtherUsers) return;
|
||||
|
||||
const interval = setInterval(() => {
|
||||
if (document.visibilityState === 'visible') {
|
||||
loadPermissions(true);
|
||||
}
|
||||
}, 10000);
|
||||
|
||||
const handleFocus = () => {
|
||||
loadPermissions(true);
|
||||
};
|
||||
|
||||
window.addEventListener('focus', handleFocus);
|
||||
|
||||
return () => {
|
||||
clearInterval(interval);
|
||||
window.removeEventListener('focus', handleFocus);
|
||||
};
|
||||
}, [isAdmin, canViewOtherUsers, activeOnly]);
|
||||
|
||||
const handleRevoke = async (id: string) => {
|
||||
if (confirm('Revoke this permission? Access will be immediately blocked.')) {
|
||||
try {
|
||||
await api.post(`/admin/permissions/${id}/revoke`, {});
|
||||
loadPermissions();
|
||||
} catch (err: any) {
|
||||
alert(err.message || 'Failed to revoke permission');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (id: string) => {
|
||||
if (confirm('Permanently delete this permission record?')) {
|
||||
try {
|
||||
await api.delete(`/admin/permissions/${id}`);
|
||||
loadPermissions();
|
||||
} catch (err: any) {
|
||||
alert(err.message || 'Failed to delete permission');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (isLoading || !isAdmin) {
|
||||
return (
|
||||
<div className="min-h-screen bg-[#f8fafc] flex items-center justify-center">
|
||||
<Loader2 className="w-8 h-8 text-emerald-600 animate-spin" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-[#f8fafc] text-slate-900 flex flex-col relative">
|
||||
<EcohubWatermark variant="corner" />
|
||||
|
||||
<Navbar onToggleSidebar={() => setIsSidebarOpen(!isSidebarOpen)} />
|
||||
|
||||
<div className="flex-1 flex min-w-0">
|
||||
<Sidebar isOpen={isSidebarOpen} onClose={() => setIsSidebarOpen(false)} />
|
||||
|
||||
<main className="flex-1 lg:pl-64 min-w-0 flex flex-col w-full">
|
||||
<div className="flex-1 p-4 sm:p-6 lg:p-8 space-y-6 max-w-7xl w-full mx-auto">
|
||||
{/* Header */}
|
||||
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
|
||||
<div>
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<h1 className="text-xl font-bold text-slate-900 flex items-center gap-2.5">
|
||||
<KeyRound className="w-5 h-5 text-emerald-600" />
|
||||
<span>Access Control & Permission Matrix</span>
|
||||
</h1>
|
||||
{/* Live Database Sync Badge */}
|
||||
<div
|
||||
className="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full bg-emerald-50 text-emerald-700 border border-emerald-200/80 text-[11px] font-semibold"
|
||||
title={lastSyncedAt ? `Live Auto-Sync Active • Last synced: ${lastSyncedAt.toLocaleTimeString()}` : 'Live Auto-Sync Active'}
|
||||
>
|
||||
<span className={`w-2 h-2 rounded-full ${isSyncing ? 'bg-amber-500 animate-spin' : 'bg-emerald-500 animate-pulse'}`} />
|
||||
<span>{isSyncing ? 'Syncing...' : 'Live DB Sync'}</span>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-slate-500 mt-1">
|
||||
Centrally control user-to-user sharing rights with separate play, download, and preview authorization
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{/* Manual Sync Button */}
|
||||
<button
|
||||
onClick={() => loadPermissions(false)}
|
||||
disabled={isSyncing}
|
||||
className="flex items-center gap-1.5 px-3 py-2 rounded-xl bg-white hover:bg-slate-50 border border-slate-200 text-slate-700 text-xs font-semibold shadow-xs transition-all active:scale-95 disabled:opacity-50"
|
||||
title="Sync with database"
|
||||
>
|
||||
<RefreshCw className={`w-3.5 h-3.5 text-emerald-600 ${isSyncing ? 'animate-spin' : ''}`} />
|
||||
<span>Sync DB</span>
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => setIsBatchModalOpen(true)}
|
||||
className="flex items-center gap-1.5 px-3.5 py-2 rounded-xl bg-white hover:bg-slate-50 text-slate-700 text-xs font-semibold border border-slate-200 transition-all shadow-sm"
|
||||
>
|
||||
<Layers className="w-4 h-4 text-emerald-600" />
|
||||
<span>Batch Grant (Select All)</span>
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => setIsGrantModalOpen(true)}
|
||||
className="flex items-center gap-2 px-4 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white text-xs font-medium shadow-md shadow-emerald-600/20 transition-all"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
<span>Grant New Permission</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Table */}
|
||||
{isDataLoading ? (
|
||||
<div className="p-16 flex items-center justify-center">
|
||||
<Loader2 className="w-8 h-8 text-emerald-600 animate-spin" />
|
||||
</div>
|
||||
) : permissions.length === 0 ? (
|
||||
<div className="p-16 text-center rounded-2xl bg-white border border-slate-200 shadow-sm">
|
||||
<KeyRound className="w-12 h-12 text-slate-400 mx-auto mb-3" />
|
||||
<h3 className="text-sm font-medium text-slate-800">No sharing permissions defined</h3>
|
||||
<p className="text-xs text-slate-500 mt-1 max-w-sm mx-auto">
|
||||
Users currently have private access to their own files only. Click "Grant New Permission" to authorize cross-user access.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="bg-white rounded-2xl overflow-hidden border border-slate-200 shadow-sm">
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full min-w-[760px] text-left border-collapse">
|
||||
<thead>
|
||||
<tr className="border-b border-slate-200 bg-slate-50 text-[11px] font-semibold text-slate-500 uppercase tracking-wider">
|
||||
<th className="py-3 px-4">Scope</th>
|
||||
<th className="py-3 px-4">Owner</th>
|
||||
<th className="py-3 px-4">Grantee (Recipient)</th>
|
||||
<th className="py-3 px-4 text-center">Metadata</th>
|
||||
<th className="py-3 px-4 text-center">Preview</th>
|
||||
<th className="py-3 px-4 text-center">Play</th>
|
||||
<th className="py-3 px-4 text-center">Download</th>
|
||||
<th className="py-3 px-4">Status</th>
|
||||
<th className="py-3 px-4 text-right">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{permissions.map((p) => {
|
||||
const isRevoked = !!p.revokedAt;
|
||||
const isExpired = p.expiresAt && new Date(p.expiresAt) < new Date();
|
||||
|
||||
return (
|
||||
<tr
|
||||
key={p.id}
|
||||
className="border-b border-slate-100 hover:bg-slate-50/70 transition-colors text-xs"
|
||||
>
|
||||
{/* Scope */}
|
||||
<td className="py-3 px-4">
|
||||
<div>
|
||||
<span className="font-semibold text-emerald-800 block text-[11px]">
|
||||
{p.resourceType}
|
||||
</span>
|
||||
{p.resourceId && (
|
||||
<span className="text-[10px] font-mono text-slate-400 truncate block max-w-[120px]">
|
||||
{p.resourceId}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
|
||||
{/* Owner */}
|
||||
<td className="py-3 px-4">
|
||||
<span className="text-slate-900 block font-medium">
|
||||
{p.owner?.fullName || 'User'}
|
||||
</span>
|
||||
<span className="text-[10px] text-slate-500">
|
||||
{p.owner?.email}
|
||||
</span>
|
||||
</td>
|
||||
|
||||
{/* Grantee */}
|
||||
<td className="py-3 px-4">
|
||||
<span className="text-slate-900 block font-medium">
|
||||
{p.grantee?.fullName || 'User'}
|
||||
</span>
|
||||
<span className="text-[10px] text-slate-500">
|
||||
{p.grantee?.email}
|
||||
</span>
|
||||
</td>
|
||||
|
||||
{/* Metadata */}
|
||||
<td className="py-3 px-4 text-center">
|
||||
{p.canViewMetadata ? (
|
||||
<CheckCircle className="w-4 h-4 text-emerald-600 mx-auto" />
|
||||
) : (
|
||||
<XCircle className="w-4 h-4 text-slate-300 mx-auto" />
|
||||
)}
|
||||
</td>
|
||||
|
||||
{/* Preview */}
|
||||
<td className="py-3 px-4 text-center">
|
||||
{p.canPreview ? (
|
||||
<CheckCircle className="w-4 h-4 text-emerald-600 mx-auto" />
|
||||
) : (
|
||||
<XCircle className="w-4 h-4 text-slate-300 mx-auto" />
|
||||
)}
|
||||
</td>
|
||||
|
||||
{/* Play */}
|
||||
<td className="py-3 px-4 text-center">
|
||||
{p.canPlay ? (
|
||||
<CheckCircle className="w-4 h-4 text-emerald-600 mx-auto" />
|
||||
) : (
|
||||
<XCircle className="w-4 h-4 text-slate-300 mx-auto" />
|
||||
)}
|
||||
</td>
|
||||
|
||||
{/* Download */}
|
||||
<td className="py-3 px-4 text-center">
|
||||
{p.canDownload ? (
|
||||
<CheckCircle className="w-4 h-4 text-emerald-600 mx-auto" />
|
||||
) : (
|
||||
<XCircle className="w-4 h-4 text-rose-500 mx-auto" />
|
||||
)}
|
||||
</td>
|
||||
|
||||
{/* Status */}
|
||||
<td className="py-3 px-4">
|
||||
{isRevoked ? (
|
||||
<span className="inline-block px-2 py-0.5 rounded-full text-[10px] font-medium bg-rose-50 text-rose-700">
|
||||
Revoked
|
||||
</span>
|
||||
) : isExpired ? (
|
||||
<span className="inline-block px-2 py-0.5 rounded-full text-[10px] font-medium bg-amber-50 text-amber-700">
|
||||
Expired
|
||||
</span>
|
||||
) : (
|
||||
<span className="inline-block px-2 py-0.5 rounded-full text-[10px] font-medium bg-emerald-50 text-emerald-700">
|
||||
Active
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
|
||||
{/* Actions */}
|
||||
<td className="py-3 px-4 text-right">
|
||||
<div className="flex items-center justify-end gap-1.5">
|
||||
{!isRevoked && (
|
||||
<button
|
||||
onClick={() => handleRevoke(p.id)}
|
||||
className="p-1.5 rounded-lg hover:bg-rose-50 text-slate-400 hover:text-rose-600 transition-colors"
|
||||
title="Revoke access"
|
||||
>
|
||||
<Ban className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={() => handleDelete(p.id)}
|
||||
className="p-1.5 rounded-lg hover:bg-slate-100 text-slate-400 hover:text-rose-600 transition-colors"
|
||||
title="Delete record"
|
||||
>
|
||||
<Trash2 className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<GrantPermissionModal
|
||||
isOpen={isGrantModalOpen}
|
||||
onClose={() => setIsGrantModalOpen(false)}
|
||||
onSuccess={loadPermissions}
|
||||
/>
|
||||
|
||||
<BatchGrantModal
|
||||
isOpen={isBatchModalOpen}
|
||||
onClose={() => setIsBatchModalOpen(false)}
|
||||
onSuccess={loadPermissions}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
998
apps/frontend/src/app/admin/users/page.tsx
Normal file
998
apps/frontend/src/app/admin/users/page.tsx
Normal file
@@ -0,0 +1,998 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState, useEffect, useMemo } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useAuth } from '@/context/auth-context';
|
||||
import { api } from '@/lib/api-client';
|
||||
import { formatBytes, formatDate, copyTextToClipboard } from '@/lib/utils';
|
||||
import { Navbar } from '@/components/layout/Navbar';
|
||||
import { Sidebar } from '@/components/layout/Sidebar';
|
||||
import { CreateUserModal } from '@/components/admin/CreateUserModal';
|
||||
import { EditUserModal } from '@/components/admin/EditUserModal';
|
||||
import { AdminResetPasswordModal } from '@/components/admin/AdminResetPasswordModal';
|
||||
import { DeleteUserModal } from '@/components/admin/DeleteUserModal';
|
||||
import { EcohubWatermark } from '@/components/common/EcohubWatermark';
|
||||
import { UserRole, UserStatus } from '@fileshare/shared';
|
||||
import {
|
||||
Users,
|
||||
UserPlus,
|
||||
Search,
|
||||
Building2,
|
||||
Edit2,
|
||||
Loader2,
|
||||
Eye,
|
||||
EyeOff,
|
||||
Copy,
|
||||
Check,
|
||||
KeyRound,
|
||||
Download,
|
||||
Share2,
|
||||
Trash2,
|
||||
Server,
|
||||
RefreshCw,
|
||||
LayoutGrid,
|
||||
List,
|
||||
Shield,
|
||||
HardDrive,
|
||||
CheckCircle2,
|
||||
FolderOpen,
|
||||
} from 'lucide-react';
|
||||
|
||||
export default function AdminUsersPage() {
|
||||
const router = useRouter();
|
||||
const { user, isAdmin, isSuperAdmin, canViewOtherUsers, isLoading } = useAuth();
|
||||
|
||||
const [usersList, setUsersList] = useState<any[]>([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [search, setSearch] = useState('');
|
||||
const [roleFilter, setRoleFilter] = useState('');
|
||||
const [statusFilter, setStatusFilter] = useState('');
|
||||
const [viewMode, setViewMode] = useState<'table' | 'cards'>('table');
|
||||
const [isDataLoading, setIsDataLoading] = useState(true);
|
||||
const [isSyncing, setIsSyncing] = useState(false);
|
||||
const [lastSyncedAt, setLastSyncedAt] = useState<Date | null>(null);
|
||||
|
||||
// Password visibility map & copied state
|
||||
const [visiblePasswords, setVisiblePasswords] = useState<Record<string, boolean>>({});
|
||||
const [copiedId, setCopiedId] = useState<string | null>(null);
|
||||
|
||||
// Modals
|
||||
const [isCreateOpen, setIsCreateOpen] = useState(false);
|
||||
const [editTargetUser, setEditTargetUser] = useState<any | null>(null);
|
||||
const [resetPasswordTargetUser, setResetPasswordTargetUser] = useState<any | null>(null);
|
||||
const [deleteTargetUser, setDeleteTargetUser] = useState<any | null>(null);
|
||||
const [isSidebarOpen, setIsSidebarOpen] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLoading) {
|
||||
if (!user) router.push('/login');
|
||||
else if (!isAdmin || !canViewOtherUsers) router.push('/dashboard');
|
||||
}
|
||||
}, [user, isAdmin, canViewOtherUsers, isLoading, router]);
|
||||
|
||||
const loadUsers = async (isSilent = false) => {
|
||||
if (!isSilent) {
|
||||
setIsDataLoading(true);
|
||||
}
|
||||
setIsSyncing(true);
|
||||
try {
|
||||
let query = `/admin/users?limit=100`;
|
||||
if (search) query += `&search=${encodeURIComponent(search)}`;
|
||||
if (roleFilter) query += `&role=${roleFilter}`;
|
||||
if (statusFilter) query += `&status=${statusFilter}`;
|
||||
|
||||
const res = await api.get<any>(query);
|
||||
setUsersList(res.users || []);
|
||||
setTotal(res.total || 0);
|
||||
setLastSyncedAt(new Date());
|
||||
} catch (err) {
|
||||
console.error('Failed to load users', err);
|
||||
} finally {
|
||||
if (!isSilent) setIsDataLoading(false);
|
||||
setIsSyncing(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (isAdmin && canViewOtherUsers) {
|
||||
loadUsers();
|
||||
}
|
||||
}, [isAdmin, canViewOtherUsers, search, roleFilter, statusFilter]);
|
||||
|
||||
// Periodic Auto-Sync with Database (Silent every 10s + on Window Focus)
|
||||
useEffect(() => {
|
||||
if (!isAdmin || !canViewOtherUsers) return;
|
||||
|
||||
const interval = setInterval(() => {
|
||||
if (document.visibilityState === 'visible') {
|
||||
loadUsers(true);
|
||||
}
|
||||
}, 10000);
|
||||
|
||||
const handleFocus = () => {
|
||||
loadUsers(true);
|
||||
};
|
||||
|
||||
window.addEventListener('focus', handleFocus);
|
||||
|
||||
return () => {
|
||||
clearInterval(interval);
|
||||
window.removeEventListener('focus', handleFocus);
|
||||
};
|
||||
}, [isAdmin, canViewOtherUsers, search, roleFilter, statusFilter]);
|
||||
|
||||
const togglePasswordVisibility = (userId: string) => {
|
||||
setVisiblePasswords((prev) => ({
|
||||
...prev,
|
||||
[userId]: !prev[userId],
|
||||
}));
|
||||
};
|
||||
|
||||
const copyPassword = async (userId: string, pass: string) => {
|
||||
try {
|
||||
await copyTextToClipboard(pass);
|
||||
setCopiedId(userId);
|
||||
setTimeout(() => setCopiedId(null), 2000);
|
||||
} catch (err) {
|
||||
console.warn('Failed to copy password', err);
|
||||
}
|
||||
};
|
||||
|
||||
const handleToggleSharePermission = async (targetUser: any) => {
|
||||
try {
|
||||
await api.patch(`/admin/users/${targetUser.id}`, {
|
||||
canCreateShareLinks: !targetUser.canCreateShareLinks,
|
||||
});
|
||||
loadUsers(true);
|
||||
} catch (err: any) {
|
||||
alert(err.message || 'Failed to update share permission');
|
||||
}
|
||||
};
|
||||
|
||||
const handleToggleDeletePermission = async (targetUser: any) => {
|
||||
try {
|
||||
await api.patch(`/admin/users/${targetUser.id}`, {
|
||||
canDeleteFiles: !targetUser.canDeleteFiles,
|
||||
});
|
||||
loadUsers(true);
|
||||
} catch (err: any) {
|
||||
alert(err.message || 'Failed to update delete permission');
|
||||
}
|
||||
};
|
||||
|
||||
const handleToggleViewOtherUsersPermission = async (targetUser: any) => {
|
||||
if (!isSuperAdmin) return;
|
||||
try {
|
||||
await api.patch(`/admin/users/${targetUser.id}`, {
|
||||
canViewOtherUsers: !targetUser.canViewOtherUsers,
|
||||
});
|
||||
loadUsers(true);
|
||||
} catch (err: any) {
|
||||
alert(err.message || 'Failed to update view users permission');
|
||||
}
|
||||
};
|
||||
|
||||
const handleApproveUser = async (targetUser: any) => {
|
||||
try {
|
||||
await api.patch(`/admin/users/${targetUser.id}`, {
|
||||
status: UserStatus.ACTIVE,
|
||||
});
|
||||
loadUsers(true);
|
||||
} catch (err: any) {
|
||||
alert(err.message || 'Failed to approve user');
|
||||
}
|
||||
};
|
||||
|
||||
// Dynamic Summary Metrics
|
||||
const stats = useMemo(() => {
|
||||
const activeCount = usersList.filter((u) => u.status === UserStatus.ACTIVE).length;
|
||||
const pendingCount = usersList.filter((u) => u.status === UserStatus.PENDING).length;
|
||||
const companies = new Set(usersList.map((u) => u.companyName || 'Ecohub')).size;
|
||||
const totalStorageBytes = usersList.reduce((acc, u) => acc + Number(u.storageQuotaBytes || 0), 0);
|
||||
const totalUsedBytes = usersList.reduce((acc, u) => acc + Number(u.storageUsedBytes || 0), 0);
|
||||
|
||||
return {
|
||||
totalUsers: total || usersList.length,
|
||||
activeUsers: activeCount,
|
||||
pendingUsers: pendingCount,
|
||||
totalCompanies: companies,
|
||||
storageUsedFormatted: formatBytes(totalUsedBytes),
|
||||
storageQuotaFormatted: formatBytes(totalStorageBytes),
|
||||
};
|
||||
}, [usersList, total]);
|
||||
|
||||
const getInitials = (name?: string) => {
|
||||
if (!name) return 'U';
|
||||
const parts = name.trim().split(' ');
|
||||
if (parts.length >= 2) return `${parts[0][0]}${parts[1][0]}`.toUpperCase();
|
||||
return name.slice(0, 2).toUpperCase();
|
||||
};
|
||||
|
||||
const getAvatarBg = (role?: UserRole) => {
|
||||
if (role === UserRole.SUPER_ADMIN) return 'bg-gradient-to-br from-rose-500 to-red-600 text-white';
|
||||
if (role === UserRole.ADMIN) return 'bg-gradient-to-br from-amber-500 to-orange-600 text-white';
|
||||
return 'bg-gradient-to-br from-emerald-500 to-teal-600 text-white';
|
||||
};
|
||||
|
||||
const parseAllowedCompanies = (raw: string | null | undefined, primary: string) => {
|
||||
if (raw === '*') return { all: true, count: 0, list: [] };
|
||||
if (!raw) return { all: false, count: 0, list: [] };
|
||||
try {
|
||||
const list: string[] = raw.startsWith('[')
|
||||
? JSON.parse(raw)
|
||||
: raw.split(',').map((s) => s.trim()).filter(Boolean);
|
||||
const others = list.filter((c) => c.toLowerCase() !== primary.toLowerCase());
|
||||
return { all: false, count: others.length, list: others };
|
||||
} catch {
|
||||
return { all: false, count: 0, list: [] };
|
||||
}
|
||||
};
|
||||
|
||||
if (isLoading || !isAdmin || !canViewOtherUsers) {
|
||||
return (
|
||||
<div className="min-h-screen bg-[#f8fafc] flex items-center justify-center">
|
||||
<Loader2 className="w-8 h-8 text-emerald-600 animate-spin" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-[#f8fafc] text-slate-900 flex flex-col relative">
|
||||
<EcohubWatermark variant="corner" />
|
||||
|
||||
<Navbar onToggleSidebar={() => setIsSidebarOpen(!isSidebarOpen)} />
|
||||
|
||||
<div className="flex-1 flex min-w-0">
|
||||
<Sidebar isOpen={isSidebarOpen} onClose={() => setIsSidebarOpen(false)} />
|
||||
|
||||
<main className="flex-1 lg:pl-64 min-w-0 flex flex-col w-full">
|
||||
<div className="flex-1 p-4 sm:p-6 lg:p-8 space-y-6 w-full max-w-full">
|
||||
{/* Top Header */}
|
||||
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
|
||||
<div>
|
||||
<div className="flex items-center gap-2.5 flex-wrap">
|
||||
<div className="w-9 h-9 rounded-xl bg-emerald-100/80 border border-emerald-200 flex items-center justify-center text-emerald-700 shadow-xs">
|
||||
<Users className="w-5 h-5" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-lg sm:text-xl font-bold text-slate-900 tracking-tight">
|
||||
User Directory & Organizations
|
||||
</h1>
|
||||
<p className="text-xs text-slate-500">
|
||||
Manage registered users, company access scopes, passwords & storage
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 flex-wrap sm:flex-nowrap">
|
||||
{/* Live DB Sync Indicator */}
|
||||
<div
|
||||
className="inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-xl bg-white border border-slate-200/80 text-slate-600 text-xs font-medium shadow-xs"
|
||||
title={lastSyncedAt ? `Live Auto-Sync Active • Last synced: ${lastSyncedAt.toLocaleTimeString()}` : 'Live Auto-Sync Active'}
|
||||
>
|
||||
<span className={`w-2 h-2 rounded-full ${isSyncing ? 'bg-amber-500 animate-spin' : 'bg-emerald-500 animate-pulse'}`} />
|
||||
<span className="hidden md:inline">{isSyncing ? 'Syncing...' : 'Synced'}</span>
|
||||
<button
|
||||
onClick={() => loadUsers(false)}
|
||||
disabled={isSyncing}
|
||||
className="p-0.5 hover:text-emerald-600 transition-colors"
|
||||
title="Refresh Now"
|
||||
>
|
||||
<RefreshCw className={`w-3.5 h-3.5 ${isSyncing ? 'animate-spin text-emerald-600' : ''}`} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* View Mode Toggle */}
|
||||
<div className="flex items-center bg-white border border-slate-200/80 rounded-xl p-0.5 shadow-xs">
|
||||
<button
|
||||
onClick={() => setViewMode('table')}
|
||||
className={`flex items-center gap-1 px-2.5 py-1.5 rounded-lg text-xs font-semibold transition-all ${
|
||||
viewMode === 'table'
|
||||
? 'bg-emerald-600 text-white shadow-xs'
|
||||
: 'text-slate-600 hover:text-slate-900'
|
||||
}`}
|
||||
title="Table View (Fit to Screen)"
|
||||
>
|
||||
<List className="w-3.5 h-3.5" />
|
||||
<span className="hidden sm:inline">Table</span>
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setViewMode('cards')}
|
||||
className={`flex items-center gap-1 px-2.5 py-1.5 rounded-lg text-xs font-semibold transition-all ${
|
||||
viewMode === 'cards'
|
||||
? 'bg-emerald-600 text-white shadow-xs'
|
||||
: 'text-slate-600 hover:text-slate-900'
|
||||
}`}
|
||||
title="User Cards View (Simple & Easy)"
|
||||
>
|
||||
<LayoutGrid className="w-3.5 h-3.5" />
|
||||
<span className="hidden sm:inline">Cards</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Create User Button */}
|
||||
<button
|
||||
onClick={() => setIsCreateOpen(true)}
|
||||
className="flex items-center gap-2 px-3.5 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white font-semibold text-xs shadow-md shadow-emerald-600/20 transition-all active:scale-95 whitespace-nowrap"
|
||||
>
|
||||
<UserPlus className="w-4 h-4" />
|
||||
<span>Create User</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Quick Metrics Bar (User-Friendly Overview) */}
|
||||
<div className="grid grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4">
|
||||
<div className="bg-white p-3.5 sm:p-4 rounded-2xl border border-slate-200/80 shadow-xs flex items-center gap-3">
|
||||
<div className="w-10 h-10 rounded-xl bg-blue-50 border border-blue-100 flex items-center justify-center text-blue-600 shrink-0">
|
||||
<Users className="w-5 h-5" />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<span className="text-[11px] font-medium text-slate-500 block truncate">Total Users</span>
|
||||
<span className="text-lg font-bold text-slate-900 leading-tight">{stats.totalUsers}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white p-3.5 sm:p-4 rounded-2xl border border-slate-200/80 shadow-xs flex items-center gap-3">
|
||||
<div className="w-10 h-10 rounded-xl bg-emerald-50 border border-emerald-100 flex items-center justify-center text-emerald-600 shrink-0">
|
||||
<CheckCircle2 className="w-5 h-5" />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<span className="text-[11px] font-medium text-slate-500 block truncate">Active Accounts</span>
|
||||
<span className="text-lg font-bold text-slate-900 leading-tight">{stats.activeUsers}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white p-3.5 sm:p-4 rounded-2xl border border-slate-200/80 shadow-xs flex items-center gap-3">
|
||||
<div className="w-10 h-10 rounded-xl bg-purple-50 border border-purple-100 flex items-center justify-center text-purple-600 shrink-0">
|
||||
<Building2 className="w-5 h-5" />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<span className="text-[11px] font-medium text-slate-500 block truncate">Organizations</span>
|
||||
<span className="text-lg font-bold text-slate-900 leading-tight">{stats.totalCompanies}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white p-3.5 sm:p-4 rounded-2xl border border-slate-200/80 shadow-xs flex items-center gap-3">
|
||||
<div className="w-10 h-10 rounded-xl bg-amber-50 border border-amber-100 flex items-center justify-center text-amber-600 shrink-0">
|
||||
<HardDrive className="w-5 h-5" />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<span className="text-[11px] font-medium text-slate-500 block truncate">Storage Used / Quota</span>
|
||||
<span className="text-xs sm:text-sm font-bold text-slate-900 leading-tight block truncate">
|
||||
{stats.storageUsedFormatted} <span className="text-slate-400 font-normal">/ {stats.storageQuotaFormatted}</span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Pending Approvals Alert Banner */}
|
||||
{stats.pendingUsers > 0 && (
|
||||
<div className="bg-amber-50 border border-amber-200/90 rounded-2xl p-4 flex flex-col sm:flex-row sm:items-center justify-between gap-3 text-xs text-amber-900 shadow-xs">
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="w-3 h-3 rounded-full bg-amber-500 animate-pulse shrink-0" />
|
||||
<div>
|
||||
<span className="font-bold text-amber-950">
|
||||
{stats.pendingUsers} Self-Registered User{stats.pendingUsers > 1 ? 's' : ''} Awaiting Approval
|
||||
</span>
|
||||
<p className="text-[11px] text-amber-700">
|
||||
New users cannot log in until an Administrator or Super Admin activates their account.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
<button
|
||||
onClick={() => setStatusFilter(UserStatus.PENDING)}
|
||||
className="px-3 py-1.5 bg-amber-600 hover:bg-amber-700 text-white rounded-xl font-semibold text-xs transition-colors shadow-xs"
|
||||
>
|
||||
Filter Pending ({stats.pendingUsers})
|
||||
</button>
|
||||
{statusFilter === UserStatus.PENDING && (
|
||||
<button
|
||||
onClick={() => setStatusFilter('')}
|
||||
className="px-3 py-1.5 bg-white border border-amber-300 text-amber-800 hover:bg-amber-100 rounded-xl font-medium text-xs transition-colors"
|
||||
>
|
||||
Clear Filter
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Filters Bar */}
|
||||
<div className="flex flex-col sm:flex-row gap-3 items-stretch sm:items-center justify-between bg-white p-3 rounded-2xl border border-slate-200/80 shadow-xs">
|
||||
<div className="relative flex-1 min-w-0">
|
||||
<Search className="w-4 h-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search user name, username, email or company..."
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
className="w-full pl-9 pr-4 py-1.5 rounded-xl bg-slate-50 border border-slate-200 text-slate-900 text-xs placeholder:text-slate-400 focus:outline-none focus:border-emerald-600 transition-colors"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<select
|
||||
value={roleFilter}
|
||||
onChange={(e) => setRoleFilter(e.target.value)}
|
||||
className="px-3 py-1.5 rounded-xl bg-slate-50 border border-slate-200 text-slate-700 text-xs focus:outline-none font-medium cursor-pointer"
|
||||
>
|
||||
<option value="">All Roles</option>
|
||||
<option value={UserRole.USER}>Regular Users</option>
|
||||
<option value={UserRole.ADMIN}>Administrators</option>
|
||||
<option value={UserRole.SUPER_ADMIN}>Super Admins</option>
|
||||
</select>
|
||||
|
||||
<select
|
||||
value={statusFilter}
|
||||
onChange={(e) => setStatusFilter(e.target.value)}
|
||||
className="px-3 py-1.5 rounded-xl bg-slate-50 border border-slate-200 text-slate-700 text-xs focus:outline-none font-medium cursor-pointer"
|
||||
>
|
||||
<option value="">All Statuses</option>
|
||||
<option value={UserStatus.ACTIVE}>Active</option>
|
||||
<option value={UserStatus.SUSPENDED}>Suspended</option>
|
||||
<option value={UserStatus.PENDING}>Pending</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Main Content Area */}
|
||||
{isDataLoading ? (
|
||||
<div className="p-16 bg-white rounded-2xl border border-slate-200/80 shadow-xs flex flex-col items-center justify-center gap-3">
|
||||
<Loader2 className="w-8 h-8 text-emerald-600 animate-spin" />
|
||||
<span className="text-xs text-slate-500 font-medium">Loading user directory...</span>
|
||||
</div>
|
||||
) : usersList.length === 0 ? (
|
||||
<div className="p-16 bg-white rounded-2xl border border-slate-200/80 shadow-xs text-center space-y-2">
|
||||
<Users className="w-10 h-10 text-slate-300 mx-auto" />
|
||||
<h3 className="text-sm font-semibold text-slate-800">No users found</h3>
|
||||
<p className="text-xs text-slate-400">Try adjusting your search query or filters.</p>
|
||||
</div>
|
||||
) : viewMode === 'table' ? (
|
||||
/* Fit-To-Screen Compact Modern Table */
|
||||
<div className="bg-white rounded-2xl border border-slate-200/80 shadow-xs overflow-hidden w-full">
|
||||
<div className="overflow-x-auto w-full">
|
||||
<table className="w-full text-left border-collapse">
|
||||
<thead>
|
||||
<tr className="border-b border-slate-200 bg-slate-50/70 text-[11px] font-semibold text-slate-500 uppercase tracking-wider">
|
||||
<th className="py-3 px-4">User</th>
|
||||
<th className="py-3 px-4">Organization & Scopes</th>
|
||||
<th className="py-3 px-4">Role & Status</th>
|
||||
<th className="py-3 px-4">Storage Quota</th>
|
||||
<th className="py-3 px-4">Feature Toggles</th>
|
||||
{isSuperAdmin && <th className="py-3 px-4">Password</th>}
|
||||
<th className="py-3 px-4 text-right">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-slate-100">
|
||||
{usersList.map((u) => {
|
||||
const quota = Number(u.storageQuotaBytes);
|
||||
const used = Number(u.storageUsedBytes);
|
||||
const pct = quota > 0 ? Math.min(Math.round((used / quota) * 100), 100) : 0;
|
||||
const isVisible = !!visiblePasswords[u.id];
|
||||
const orgScope = parseAllowedCompanies(u.allowedCompanies, u.companyName || 'Ecohub');
|
||||
|
||||
return (
|
||||
<tr key={u.id} className="hover:bg-slate-50/60 transition-colors text-xs">
|
||||
{/* User Avatar & Info */}
|
||||
<td className="py-3 px-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div
|
||||
className={`w-8 h-8 rounded-full flex items-center justify-center font-bold text-xs shrink-0 shadow-xs ${getAvatarBg(
|
||||
u.role,
|
||||
)}`}
|
||||
>
|
||||
{getInitials(u.fullName)}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<span className="font-semibold text-slate-900 block truncate leading-snug">
|
||||
{u.fullName}
|
||||
</span>
|
||||
<span className="text-[11px] text-slate-500 font-mono block truncate">
|
||||
@{u.username} • {u.email}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
|
||||
{/* Organization & Permissions Scope */}
|
||||
<td className="py-3 px-4">
|
||||
<div className="flex flex-col gap-1 items-start">
|
||||
<span className="inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md text-[11px] font-semibold bg-emerald-50 text-emerald-800 border border-emerald-200/80">
|
||||
<Building2 className="w-3 h-3 text-emerald-600 shrink-0" />
|
||||
<span className="truncate max-w-[140px]">{u.companyName || 'Ecohub'}</span>
|
||||
</span>
|
||||
|
||||
{/* Scope Badge */}
|
||||
{u.role === UserRole.SUPER_ADMIN || orgScope.all ? (
|
||||
<span className="text-[10px] font-bold text-purple-700 bg-purple-50 border border-purple-200/80 px-1.5 py-0.2 rounded font-mono">
|
||||
All Orgs Access
|
||||
</span>
|
||||
) : orgScope.count > 0 ? (
|
||||
<span
|
||||
className="text-[10px] font-medium text-sky-700 bg-sky-50 border border-sky-200 px-1.5 py-0.2 rounded cursor-default"
|
||||
title={`Allowed Orgs: ${u.companyName}, ${orgScope.list.join(', ')}`}
|
||||
>
|
||||
+{orgScope.count} Other {orgScope.count === 1 ? 'Org' : 'Orgs'}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-[10px] text-slate-400">Own Org Only</span>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
|
||||
{/* Role & Status */}
|
||||
<td className="py-3 px-4">
|
||||
<div className="flex items-center gap-1.5 flex-wrap">
|
||||
<span
|
||||
className={`px-2 py-0.5 rounded-md text-[10px] font-mono font-bold uppercase tracking-wider ${
|
||||
u.role === UserRole.SUPER_ADMIN
|
||||
? 'bg-rose-50 text-rose-700 border border-rose-200'
|
||||
: u.role === UserRole.ADMIN
|
||||
? 'bg-amber-50 text-amber-700 border border-amber-200'
|
||||
: 'bg-slate-100 text-slate-700 border border-slate-200'
|
||||
}`}
|
||||
>
|
||||
{u.role === UserRole.SUPER_ADMIN ? 'Super Admin' : u.role}
|
||||
</span>
|
||||
<span
|
||||
className={`inline-flex items-center gap-1 px-1.5 py-0.5 rounded-full text-[10px] font-medium ${
|
||||
u.status === UserStatus.ACTIVE
|
||||
? 'bg-emerald-50 text-emerald-700'
|
||||
: u.status === UserStatus.PENDING
|
||||
? 'bg-amber-50 text-amber-700 border border-amber-200'
|
||||
: 'bg-rose-50 text-rose-700'
|
||||
}`}
|
||||
>
|
||||
<span
|
||||
className={`w-1.5 h-1.5 rounded-full ${
|
||||
u.status === UserStatus.ACTIVE
|
||||
? 'bg-emerald-500'
|
||||
: u.status === UserStatus.PENDING
|
||||
? 'bg-amber-500 animate-pulse'
|
||||
: 'bg-rose-500'
|
||||
}`}
|
||||
/>
|
||||
<span>{u.status === UserStatus.PENDING ? 'Pending Approval' : u.status}</span>
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
|
||||
{/* Storage Gauge */}
|
||||
<td className="py-3 px-4">
|
||||
<div className="w-32 space-y-1">
|
||||
<div className="flex justify-between text-[11px] text-slate-600">
|
||||
<span className="font-semibold text-slate-800">{formatBytes(used)}</span>
|
||||
<span className="text-slate-400">/ {formatBytes(quota)}</span>
|
||||
</div>
|
||||
<div className="w-full h-1.5 bg-slate-100 rounded-full overflow-hidden">
|
||||
<div
|
||||
className={`h-full rounded-full transition-all ${
|
||||
pct > 90 ? 'bg-rose-500' : 'bg-emerald-500'
|
||||
}`}
|
||||
style={{ width: `${pct}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
|
||||
{/* Clean Interactive Permission Icons */}
|
||||
<td className="py-3 px-4">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<button
|
||||
onClick={() => handleToggleSharePermission(u)}
|
||||
className={`p-1.5 rounded-lg border transition-all ${
|
||||
u.canCreateShareLinks
|
||||
? 'bg-emerald-50 text-emerald-700 border-emerald-200 hover:bg-emerald-100'
|
||||
: 'bg-slate-50 text-slate-400 border-slate-200 hover:bg-slate-100'
|
||||
}`}
|
||||
title={`Share Links: ${u.canCreateShareLinks ? 'Enabled (Click to disable)' : 'Disabled (Click to enable)'}`}
|
||||
>
|
||||
<Share2 className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => handleToggleDeletePermission(u)}
|
||||
className={`p-1.5 rounded-lg border transition-all ${
|
||||
u.canDeleteFiles
|
||||
? 'bg-sky-50 text-sky-700 border-sky-200 hover:bg-sky-100'
|
||||
: 'bg-rose-50 text-rose-700 border-rose-200 hover:bg-rose-100'
|
||||
}`}
|
||||
title={`File Deletion: ${u.canDeleteFiles ? 'Allowed (Click to block)' : 'Blocked (Click to allow)'}`}
|
||||
>
|
||||
<Trash2 className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
|
||||
{isSuperAdmin && (
|
||||
<button
|
||||
onClick={() => handleToggleViewOtherUsersPermission(u)}
|
||||
disabled={u.role === UserRole.SUPER_ADMIN}
|
||||
className={`p-1.5 rounded-lg border transition-all ${
|
||||
u.role === UserRole.SUPER_ADMIN || u.canViewOtherUsers
|
||||
? 'bg-purple-50 text-purple-700 border-purple-200 hover:bg-purple-100'
|
||||
: 'bg-slate-50 text-slate-400 border-slate-200 hover:bg-slate-100'
|
||||
} disabled:opacity-50`}
|
||||
title={`View Other Users: ${
|
||||
u.role === UserRole.SUPER_ADMIN
|
||||
? 'Super Admin (Always allowed)'
|
||||
: u.canViewOtherUsers
|
||||
? 'Allowed (Click to block)'
|
||||
: 'Blocked (Click to allow)'
|
||||
}`}
|
||||
>
|
||||
<Eye className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
|
||||
{/* Super Admin Password Viewing */}
|
||||
{isSuperAdmin && (
|
||||
<td className="py-3 px-4">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className="font-mono text-xs px-2 py-0.5 rounded bg-slate-50 border border-slate-200 text-amber-800 font-semibold max-w-[110px] truncate">
|
||||
{isVisible ? u.viewablePassword || '<not saved>' : '••••••'}
|
||||
</span>
|
||||
<button
|
||||
onClick={() => togglePasswordVisibility(u.id)}
|
||||
className="p-1 rounded text-slate-400 hover:text-slate-700 hover:bg-slate-100 transition-colors"
|
||||
title={isVisible ? 'Hide password' : 'View password'}
|
||||
>
|
||||
{isVisible ? <EyeOff className="w-3.5 h-3.5 text-amber-600" /> : <Eye className="w-3.5 h-3.5" />}
|
||||
</button>
|
||||
{u.viewablePassword && isVisible && (
|
||||
<button
|
||||
onClick={() => copyPassword(u.id, u.viewablePassword)}
|
||||
className="p-1 rounded text-slate-400 hover:text-emerald-600 hover:bg-slate-100 transition-colors"
|
||||
title="Copy password"
|
||||
>
|
||||
{copiedId === u.id ? <Check className="w-3.5 h-3.5 text-emerald-600" /> : <Copy className="w-3.5 h-3.5" />}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
)}
|
||||
|
||||
{/* Sleek Action Buttons */}
|
||||
<td className="py-3 px-4 text-right">
|
||||
<div className="flex items-center justify-end gap-1">
|
||||
{u.status === UserStatus.PENDING && (
|
||||
<button
|
||||
onClick={() => handleApproveUser(u)}
|
||||
className="px-2.5 py-1 rounded-lg bg-emerald-600 hover:bg-emerald-700 text-white text-[11px] font-semibold flex items-center gap-1 shadow-xs transition-all shrink-0 mr-1"
|
||||
title="Approve and activate account"
|
||||
>
|
||||
<Check className="w-3.5 h-3.5" />
|
||||
<span>Approve</span>
|
||||
</button>
|
||||
)}
|
||||
|
||||
<Link
|
||||
href={`/admin/files?userId=${u.id}`}
|
||||
className="p-1.5 rounded-lg bg-emerald-50 hover:bg-emerald-100 text-emerald-700 border border-emerald-200 transition-colors"
|
||||
title="Browse & download user files"
|
||||
>
|
||||
<Download className="w-3.5 h-3.5" />
|
||||
</Link>
|
||||
|
||||
<button
|
||||
onClick={() => setResetPasswordTargetUser(u)}
|
||||
className="p-1.5 rounded-lg hover:bg-amber-50 text-slate-400 hover:text-amber-600 transition-colors"
|
||||
title="Reset password"
|
||||
>
|
||||
<KeyRound className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => setEditTargetUser(u)}
|
||||
className="p-1.5 rounded-lg hover:bg-slate-100 text-slate-400 hover:text-slate-700 transition-colors"
|
||||
title="Edit user settings"
|
||||
>
|
||||
<Edit2 className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
|
||||
{(() => {
|
||||
const isOtherCompany =
|
||||
!isSuperAdmin &&
|
||||
(u.companyName || 'Ecohub').trim().toLowerCase() !==
|
||||
(user?.companyName || 'Ecohub').trim().toLowerCase();
|
||||
const cannotDeleteUser = u.id === user?.id || isOtherCompany;
|
||||
|
||||
return (
|
||||
<button
|
||||
onClick={() => setDeleteTargetUser(u)}
|
||||
disabled={cannotDeleteUser}
|
||||
className="p-1.5 rounded-lg hover:bg-rose-50 text-slate-400 hover:text-rose-600 transition-colors disabled:opacity-20 disabled:pointer-events-none"
|
||||
title={
|
||||
u.id === user?.id
|
||||
? 'Cannot delete your own account'
|
||||
: isOtherCompany
|
||||
? 'Admins cannot delete users from other companies (Super Admin only)'
|
||||
: 'Delete user account'
|
||||
}
|
||||
>
|
||||
<Trash2 className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
);
|
||||
})()}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
/* User-Friendly Cards Grid View */
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
|
||||
{usersList.map((u) => {
|
||||
const quota = Number(u.storageQuotaBytes);
|
||||
const used = Number(u.storageUsedBytes);
|
||||
const pct = quota > 0 ? Math.min(Math.round((used / quota) * 100), 100) : 0;
|
||||
const isVisible = !!visiblePasswords[u.id];
|
||||
const orgScope = parseAllowedCompanies(u.allowedCompanies, u.companyName || 'Ecohub');
|
||||
|
||||
return (
|
||||
<div
|
||||
key={u.id}
|
||||
className="bg-white rounded-2xl border border-slate-200/80 p-5 shadow-xs hover:shadow-md transition-all flex flex-col justify-between space-y-4"
|
||||
>
|
||||
{/* Card Header */}
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<div
|
||||
className={`w-11 h-11 rounded-2xl flex items-center justify-center font-bold text-sm shrink-0 shadow-sm ${getAvatarBg(
|
||||
u.role,
|
||||
)}`}
|
||||
>
|
||||
{getInitials(u.fullName)}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<h3 className="font-bold text-slate-900 text-sm truncate leading-snug">
|
||||
{u.fullName}
|
||||
</h3>
|
||||
<span className="text-[11px] text-slate-500 font-mono block truncate">
|
||||
@{u.username}
|
||||
</span>
|
||||
<span className="text-[11px] text-slate-400 block truncate">{u.email}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col items-end gap-1 shrink-0">
|
||||
<span
|
||||
className={`px-2 py-0.5 rounded-md text-[10px] font-mono font-bold uppercase ${
|
||||
u.role === UserRole.SUPER_ADMIN
|
||||
? 'bg-rose-50 text-rose-700 border border-rose-200'
|
||||
: u.role === UserRole.ADMIN
|
||||
? 'bg-amber-50 text-amber-700 border border-amber-200'
|
||||
: 'bg-slate-100 text-slate-700'
|
||||
}`}
|
||||
>
|
||||
{u.role === UserRole.SUPER_ADMIN ? 'Super Admin' : u.role}
|
||||
</span>
|
||||
<span
|
||||
className={`inline-flex items-center gap-1 px-1.5 py-0.5 rounded-full text-[10px] font-medium ${
|
||||
u.status === UserStatus.ACTIVE
|
||||
? 'bg-emerald-50 text-emerald-700'
|
||||
: u.status === UserStatus.PENDING
|
||||
? 'bg-amber-50 text-amber-700 border border-amber-200'
|
||||
: 'bg-rose-50 text-rose-700'
|
||||
}`}
|
||||
>
|
||||
<span
|
||||
className={`w-1.5 h-1.5 rounded-full ${
|
||||
u.status === UserStatus.ACTIVE
|
||||
? 'bg-emerald-500'
|
||||
: u.status === UserStatus.PENDING
|
||||
? 'bg-amber-500 animate-pulse'
|
||||
: 'bg-rose-500'
|
||||
}`}
|
||||
/>
|
||||
<span>{u.status === UserStatus.PENDING ? 'Pending' : u.status}</span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Company & Permitted Scope */}
|
||||
<div className="p-3 rounded-xl bg-slate-50 border border-slate-100 space-y-1.5 text-xs">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-[11px] text-slate-500 font-medium flex items-center gap-1.5">
|
||||
<Building2 className="w-3.5 h-3.5 text-emerald-600" />
|
||||
<span>Company / Org:</span>
|
||||
</span>
|
||||
<span className="font-semibold text-slate-800">{u.companyName || 'Ecohub'}</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between text-[11px]">
|
||||
<span className="text-slate-500 font-medium">Access Scope:</span>
|
||||
{u.role === UserRole.SUPER_ADMIN || orgScope.all ? (
|
||||
<span className="font-bold text-purple-700 bg-purple-50 px-1.5 py-0.5 rounded border border-purple-200 text-[10px]">
|
||||
All Organizations
|
||||
</span>
|
||||
) : orgScope.count > 0 ? (
|
||||
<span
|
||||
className="font-medium text-sky-700 bg-sky-50 px-1.5 py-0.5 rounded border border-sky-200 text-[10px]"
|
||||
title={orgScope.list.join(', ')}
|
||||
>
|
||||
+{orgScope.count} Other Orgs
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-slate-500 text-[10px]">Own Org Only</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Storage Progress */}
|
||||
<div className="space-y-1.5">
|
||||
<div className="flex justify-between text-[11px] text-slate-600">
|
||||
<span className="font-semibold text-slate-800 flex items-center gap-1">
|
||||
<HardDrive className="w-3.5 h-3.5 text-slate-400" />
|
||||
<span>{formatBytes(used)} used</span>
|
||||
</span>
|
||||
<span className="text-slate-400 font-medium">{formatBytes(quota)} quota ({pct}%)</span>
|
||||
</div>
|
||||
<div className="w-full h-2 bg-slate-100 rounded-full overflow-hidden">
|
||||
<div
|
||||
className={`h-full rounded-full transition-all ${
|
||||
pct > 90 ? 'bg-rose-500' : 'bg-emerald-500'
|
||||
}`}
|
||||
style={{ width: `${pct}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Feature Permissions Interactive Switch Bar */}
|
||||
<div className="flex items-center justify-between pt-1 border-t border-slate-100 text-xs">
|
||||
<span className="text-[11px] font-semibold text-slate-500">Permissions:</span>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<button
|
||||
onClick={() => handleToggleSharePermission(u)}
|
||||
className={`p-1.5 rounded-lg border text-[11px] transition-all flex items-center gap-1 ${
|
||||
u.canCreateShareLinks
|
||||
? 'bg-emerald-50 text-emerald-700 border-emerald-200'
|
||||
: 'bg-slate-50 text-slate-400 border-slate-200'
|
||||
}`}
|
||||
title={`Public Link Sharing: ${u.canCreateShareLinks ? 'Enabled' : 'Disabled'}`}
|
||||
>
|
||||
<Share2 className="w-3 h-3" />
|
||||
<span>Share</span>
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => handleToggleDeletePermission(u)}
|
||||
className={`p-1.5 rounded-lg border text-[11px] transition-all flex items-center gap-1 ${
|
||||
u.canDeleteFiles
|
||||
? 'bg-sky-50 text-sky-700 border-sky-200'
|
||||
: 'bg-rose-50 text-rose-700 border-rose-200'
|
||||
}`}
|
||||
title={`File Deletion: ${u.canDeleteFiles ? 'Allowed' : 'Blocked'}`}
|
||||
>
|
||||
<Trash2 className="w-3 h-3" />
|
||||
<span>Delete</span>
|
||||
</button>
|
||||
|
||||
{isSuperAdmin && (
|
||||
<button
|
||||
onClick={() => handleToggleViewOtherUsersPermission(u)}
|
||||
disabled={u.role === UserRole.SUPER_ADMIN}
|
||||
className={`p-1.5 rounded-lg border text-[11px] transition-all flex items-center gap-1 ${
|
||||
u.role === UserRole.SUPER_ADMIN || u.canViewOtherUsers
|
||||
? 'bg-purple-50 text-purple-700 border-purple-200'
|
||||
: 'bg-slate-50 text-slate-400 border-slate-200'
|
||||
} disabled:opacity-50`}
|
||||
title="View other users directory"
|
||||
>
|
||||
<Eye className="w-3 h-3" />
|
||||
<span>View</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Card Footer Actions */}
|
||||
<div className="pt-3 border-t border-slate-100 flex items-center justify-between">
|
||||
<Link
|
||||
href={`/admin/files?userId=${u.id}`}
|
||||
className="flex items-center gap-1.5 px-3 py-1.5 rounded-xl bg-emerald-50 hover:bg-emerald-100 text-emerald-700 text-xs font-semibold transition-colors"
|
||||
>
|
||||
<FolderOpen className="w-3.5 h-3.5" />
|
||||
<span>Files ({u.fileCount || 0})</span>
|
||||
</Link>
|
||||
|
||||
<div className="flex items-center gap-1">
|
||||
{u.status === UserStatus.PENDING && (
|
||||
<button
|
||||
onClick={() => handleApproveUser(u)}
|
||||
className="flex items-center gap-1 px-2.5 py-1.5 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white text-xs font-semibold shadow-xs transition-colors shrink-0"
|
||||
title="Approve user"
|
||||
>
|
||||
<Check className="w-3.5 h-3.5" />
|
||||
<span>Approve</span>
|
||||
</button>
|
||||
)}
|
||||
|
||||
<button
|
||||
onClick={() => setResetPasswordTargetUser(u)}
|
||||
className="p-2 rounded-xl hover:bg-amber-50 text-slate-400 hover:text-amber-600 transition-colors"
|
||||
title="Reset Password"
|
||||
>
|
||||
<KeyRound className="w-4 h-4" />
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => setEditTargetUser(u)}
|
||||
className="p-2 rounded-xl hover:bg-slate-100 text-slate-400 hover:text-slate-700 transition-colors"
|
||||
title="Edit User"
|
||||
>
|
||||
<Edit2 className="w-4 h-4" />
|
||||
</button>
|
||||
|
||||
{(() => {
|
||||
const isOtherCompany =
|
||||
!isSuperAdmin &&
|
||||
(u.companyName || 'Ecohub').trim().toLowerCase() !==
|
||||
(user?.companyName || 'Ecohub').trim().toLowerCase();
|
||||
const cannotDeleteUser = u.id === user?.id || isOtherCompany;
|
||||
|
||||
return (
|
||||
<button
|
||||
onClick={() => setDeleteTargetUser(u)}
|
||||
disabled={cannotDeleteUser}
|
||||
className="p-2 rounded-xl hover:bg-rose-50 text-slate-400 hover:text-rose-600 transition-colors disabled:opacity-20 disabled:pointer-events-none"
|
||||
title={
|
||||
u.id === user?.id
|
||||
? 'Cannot delete self'
|
||||
: isOtherCompany
|
||||
? 'Admins cannot delete users from other companies (Super Admin only)'
|
||||
: 'Delete User'
|
||||
}
|
||||
>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</button>
|
||||
);
|
||||
})()}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<CreateUserModal
|
||||
isOpen={isCreateOpen}
|
||||
onClose={() => setIsCreateOpen(false)}
|
||||
onSuccess={loadUsers}
|
||||
/>
|
||||
|
||||
<EditUserModal
|
||||
isOpen={!!editTargetUser}
|
||||
onClose={() => setEditTargetUser(null)}
|
||||
onSuccess={loadUsers}
|
||||
user={editTargetUser}
|
||||
/>
|
||||
|
||||
<AdminResetPasswordModal
|
||||
isOpen={!!resetPasswordTargetUser}
|
||||
onClose={() => setResetPasswordTargetUser(null)}
|
||||
onSuccess={loadUsers}
|
||||
user={resetPasswordTargetUser}
|
||||
/>
|
||||
|
||||
<DeleteUserModal
|
||||
isOpen={!!deleteTargetUser}
|
||||
onClose={() => setDeleteTargetUser(null)}
|
||||
onSuccess={loadUsers}
|
||||
user={deleteTargetUser}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
325
apps/frontend/src/app/dashboard/page.tsx
Normal file
325
apps/frontend/src/app/dashboard/page.tsx
Normal file
@@ -0,0 +1,325 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useAuth } from '@/context/auth-context';
|
||||
import { api } from '@/lib/api-client';
|
||||
import { formatBytes } from '@/lib/utils';
|
||||
import { Navbar } from '@/components/layout/Navbar';
|
||||
import { Sidebar } from '@/components/layout/Sidebar';
|
||||
import { FileUploaderModal } from '@/components/uploader/FileUploaderModal';
|
||||
import { FilePreviewModal } from '@/components/file-manager/FilePreviewModal';
|
||||
import { FileCard } from '@/components/file-manager/FileCard';
|
||||
import { EcohubWatermark } from '@/components/common/EcohubWatermark';
|
||||
import {
|
||||
HardDrive,
|
||||
Video,
|
||||
FileText,
|
||||
Share2,
|
||||
UploadCloud,
|
||||
ArrowRight,
|
||||
Clock,
|
||||
Sparkles,
|
||||
Building2,
|
||||
FolderOpen,
|
||||
} from 'lucide-react';
|
||||
|
||||
export default function DashboardPage() {
|
||||
const router = useRouter();
|
||||
const { user, isLoading, refreshProfile } = useAuth();
|
||||
|
||||
const [recentFiles, setRecentFiles] = useState<any[]>([]);
|
||||
const [sharedCount, setSharedCount] = useState(0);
|
||||
const [videoCount, setVideoCount] = useState(0);
|
||||
const [isUploadOpen, setIsUploadOpen] = useState(false);
|
||||
const [isSidebarOpen, setIsSidebarOpen] = useState(false);
|
||||
const [selectedFileForPreview, setSelectedFileForPreview] = useState<any | null>(null);
|
||||
const [isSyncing, setIsSyncing] = useState(false);
|
||||
const [lastSyncedAt, setLastSyncedAt] = useState<Date | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLoading && !user) {
|
||||
router.push('/login');
|
||||
}
|
||||
}, [user, isLoading, router]);
|
||||
|
||||
const fetchDashboardData = async (isSilent = false) => {
|
||||
if (!isSilent) setIsSyncing(true);
|
||||
try {
|
||||
const [filesRes, sharedRes]: [any, any] = await Promise.all([
|
||||
api.get<any>('/files?limit=8&sortBy=date&sortOrder=desc'),
|
||||
api.get<any>('/sharing/shared-with-me'),
|
||||
]);
|
||||
|
||||
setRecentFiles(filesRes.files || []);
|
||||
setSharedCount(sharedRes.length || 0);
|
||||
|
||||
const videos = (filesRes.files || []).filter((f: any) => f.fileCategory === 'VIDEO');
|
||||
setVideoCount(videos.length);
|
||||
setLastSyncedAt(new Date());
|
||||
} catch (err) {
|
||||
console.error('Failed to load dashboard data', err);
|
||||
} finally {
|
||||
if (!isSilent) setIsSyncing(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (user) {
|
||||
fetchDashboardData();
|
||||
}
|
||||
}, [user?.id]);
|
||||
|
||||
// Periodic Auto-Sync with Database (Silent every 15s + on Window Focus)
|
||||
useEffect(() => {
|
||||
if (!user?.id) return;
|
||||
|
||||
const interval = setInterval(() => {
|
||||
if (document.visibilityState === 'visible') {
|
||||
fetchDashboardData(true);
|
||||
}
|
||||
}, 15000);
|
||||
|
||||
const handleFocus = () => {
|
||||
fetchDashboardData(true);
|
||||
};
|
||||
|
||||
window.addEventListener('focus', handleFocus);
|
||||
|
||||
return () => {
|
||||
clearInterval(interval);
|
||||
window.removeEventListener('focus', handleFocus);
|
||||
};
|
||||
}, [user?.id]);
|
||||
|
||||
if (isLoading || !user) {
|
||||
return (
|
||||
<div className="min-h-screen bg-[#f8fafc] flex items-center justify-center">
|
||||
<div className="w-8 h-8 border-2 border-emerald-600 border-t-transparent rounded-full animate-spin" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const quota = Number(user.storageQuotaBytes);
|
||||
const used = Number(user.storageUsedBytes);
|
||||
const remaining = Math.max(0, quota - used);
|
||||
const percent = quota > 0 ? Math.min(Math.round((used / quota) * 100), 100) : 0;
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-[#f8fafc] text-slate-900 flex flex-col relative">
|
||||
<EcohubWatermark variant="corner" />
|
||||
|
||||
<Navbar
|
||||
onOpenUpload={() => setIsUploadOpen(true)}
|
||||
onToggleSidebar={() => setIsSidebarOpen(!isSidebarOpen)}
|
||||
/>
|
||||
|
||||
<div className="flex-1 flex min-w-0">
|
||||
<Sidebar isOpen={isSidebarOpen} onClose={() => setIsSidebarOpen(false)} />
|
||||
|
||||
<main className="flex-1 lg:pl-64 min-w-0 flex flex-col w-full">
|
||||
<div className="flex-1 p-4 sm:p-6 lg:p-8 space-y-8 max-w-7xl w-full mx-auto">
|
||||
{/* Welcome Header */}
|
||||
<div className="flex flex-col lg:flex-row lg:items-center justify-between gap-4">
|
||||
<div>
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<h1 className="text-xl sm:text-2xl font-bold text-slate-900 flex items-center gap-2.5">
|
||||
<span>Welcome back, {user.fullName.split(' ')[0]}</span>
|
||||
<Sparkles className="w-5 h-5 text-emerald-600" />
|
||||
</h1>
|
||||
{user.companyName && (
|
||||
<span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-semibold bg-emerald-50 text-emerald-700 border border-emerald-200">
|
||||
<Building2 className="w-3.5 h-3.5" />
|
||||
{user.companyName}
|
||||
</span>
|
||||
)}
|
||||
{/* Live Database Sync Badge */}
|
||||
<div
|
||||
className="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full bg-emerald-50 text-emerald-700 border border-emerald-200/80 text-[11px] font-semibold"
|
||||
title={lastSyncedAt ? `Live Auto-Sync Active • Last synced: ${lastSyncedAt.toLocaleTimeString()}` : 'Live Auto-Sync Active'}
|
||||
>
|
||||
<span className={`w-2 h-2 rounded-full ${isSyncing ? 'bg-amber-500 animate-spin' : 'bg-emerald-500 animate-pulse'}`} />
|
||||
<span>{isSyncing ? 'Syncing...' : 'Live DB Sync'}</span>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-slate-500 mt-1">
|
||||
Ecohub encrypted vault & company-wide file explorer active
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2.5 flex-wrap sm:flex-nowrap">
|
||||
<button
|
||||
onClick={() => {
|
||||
fetchDashboardData(false);
|
||||
refreshProfile();
|
||||
}}
|
||||
disabled={isSyncing}
|
||||
className="flex items-center gap-1.5 px-3 py-2 rounded-xl bg-white hover:bg-slate-50 border border-slate-200 text-slate-700 text-xs font-semibold shadow-xs transition-all active:scale-95 disabled:opacity-50"
|
||||
title="Sync with database"
|
||||
>
|
||||
<Sparkles className={`w-3.5 h-3.5 text-emerald-600 ${isSyncing ? 'animate-spin' : ''}`} />
|
||||
<span>Sync DB</span>
|
||||
</button>
|
||||
<Link
|
||||
href="/files"
|
||||
className="flex items-center gap-2 px-4 py-2 rounded-xl bg-white hover:bg-slate-50 border border-slate-200 text-slate-700 font-medium text-xs shadow-sm transition-all whitespace-nowrap"
|
||||
>
|
||||
<FolderOpen className="w-4 h-4 text-emerald-600" />
|
||||
<span>Company Explorer</span>
|
||||
</Link>
|
||||
<button
|
||||
onClick={() => setIsUploadOpen(true)}
|
||||
className="flex items-center gap-2 px-4 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white font-medium text-xs shadow-md shadow-emerald-600/20 transition-all whitespace-nowrap"
|
||||
>
|
||||
<UploadCloud className="w-4 h-4" />
|
||||
<span>Upload Media</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Quick Stats Grid */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
|
||||
{/* Storage Quota Card */}
|
||||
<div className="p-5 rounded-2xl bg-white border border-slate-200 shadow-sm space-y-3">
|
||||
<div className="flex items-center justify-between text-slate-500">
|
||||
<span className="text-xs font-medium">Storage Quota</span>
|
||||
<div className="p-2 rounded-xl bg-emerald-50 text-emerald-600">
|
||||
<HardDrive className="w-4 h-4" />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-xl font-bold text-slate-900">{formatBytes(used)}</span>
|
||||
<span className="text-xs text-slate-500 ml-1.5">/ {formatBytes(quota)}</span>
|
||||
</div>
|
||||
<div className="w-full h-1.5 bg-slate-100 rounded-full overflow-hidden">
|
||||
<div
|
||||
className={`h-full rounded-full transition-all ${
|
||||
percent > 90 ? 'bg-rose-500' : 'bg-emerald-500'
|
||||
}`}
|
||||
style={{ width: `${percent}%` }}
|
||||
/>
|
||||
</div>
|
||||
<p className="text-[11px] text-slate-500">{formatBytes(remaining)} remaining</p>
|
||||
</div>
|
||||
|
||||
{/* Total Videos */}
|
||||
<div className="p-5 rounded-2xl bg-white border border-slate-200 shadow-sm space-y-3">
|
||||
<div className="flex items-center justify-between text-slate-500">
|
||||
<span className="text-xs font-medium">Video Assets</span>
|
||||
<div className="p-2 rounded-xl bg-sky-50 text-sky-600">
|
||||
<Video className="w-4 h-4" />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-xl font-bold text-slate-900">{videoCount}</span>
|
||||
<span className="text-xs text-slate-500 ml-1.5">transcoded</span>
|
||||
</div>
|
||||
<p className="text-[11px] text-sky-600 font-medium">HLS Streaming & Ecohub Watermark</p>
|
||||
</div>
|
||||
|
||||
{/* Total Files */}
|
||||
<div className="p-5 rounded-2xl bg-white border border-slate-200 shadow-sm space-y-3">
|
||||
<div className="flex items-center justify-between text-slate-500">
|
||||
<span className="text-xs font-medium">Files In Vault</span>
|
||||
<div className="p-2 rounded-xl bg-emerald-50 text-emerald-600">
|
||||
<FileText className="w-4 h-4" />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-xl font-bold text-slate-900">{recentFiles.length}</span>
|
||||
<span className="text-xs text-slate-500 ml-1.5">stored</span>
|
||||
</div>
|
||||
<p className="text-[11px] text-emerald-600 font-medium">Verified signatures</p>
|
||||
</div>
|
||||
|
||||
{/* Shared With Me */}
|
||||
<div className="p-5 rounded-2xl bg-white border border-slate-200 shadow-sm space-y-3">
|
||||
<div className="flex items-center justify-between text-slate-500">
|
||||
<span className="text-xs font-medium">Shared With Me</span>
|
||||
<div className="p-2 rounded-xl bg-amber-50 text-amber-600">
|
||||
<Share2 className="w-4 h-4" />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-xl font-bold text-slate-900">{sharedCount}</span>
|
||||
<span className="text-xs text-slate-500 ml-1.5">delegated</span>
|
||||
</div>
|
||||
<p className="text-[11px] text-amber-600 font-medium">Granular permissions</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Recent Uploads Section */}
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-sm font-semibold text-slate-800 flex items-center gap-2">
|
||||
<Clock className="w-4 h-4 text-emerald-600" />
|
||||
<span>Recent Uploads</span>
|
||||
</h2>
|
||||
<Link
|
||||
href="/files"
|
||||
className="text-xs font-medium text-emerald-600 hover:text-emerald-700 flex items-center gap-1"
|
||||
>
|
||||
<span>View all in Company Explorer</span>
|
||||
<ArrowRight className="w-3.5 h-3.5" />
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{recentFiles.length === 0 ? (
|
||||
<div className="p-12 text-center rounded-2xl bg-white border border-slate-200 shadow-sm">
|
||||
<UploadCloud className="w-12 h-12 text-slate-400 mx-auto mb-3" />
|
||||
<h3 className="text-sm font-medium text-slate-800">No files uploaded yet</h3>
|
||||
<p className="text-xs text-slate-500 mt-1 max-w-sm mx-auto">
|
||||
Drag and drop your videos, images, or documents to begin using Ecohub.
|
||||
</p>
|
||||
<button
|
||||
onClick={() => setIsUploadOpen(true)}
|
||||
className="mt-4 px-4 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white text-xs font-medium shadow-sm transition-all"
|
||||
>
|
||||
Upload First File
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
|
||||
{recentFiles.map((file) => (
|
||||
<FileCard
|
||||
key={file.id}
|
||||
file={file}
|
||||
onPreview={(f) => setSelectedFileForPreview(f)}
|
||||
onRename={() => router.push('/files')}
|
||||
onMove={() => router.push('/files')}
|
||||
onDelete={async (f) => {
|
||||
if (confirm(`Delete file "${f.originalFilename}"?`)) {
|
||||
await api.delete(`/files/${f.id}`);
|
||||
fetchDashboardData();
|
||||
refreshProfile();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
{/* Uploader Modal */}
|
||||
<FileUploaderModal
|
||||
isOpen={isUploadOpen}
|
||||
onClose={() => setIsUploadOpen(false)}
|
||||
onUploadComplete={() => {
|
||||
fetchDashboardData();
|
||||
refreshProfile();
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* File Preview Modal */}
|
||||
<FilePreviewModal
|
||||
isOpen={!!selectedFileForPreview}
|
||||
onClose={() => setSelectedFileForPreview(null)}
|
||||
file={selectedFileForPreview}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
1167
apps/frontend/src/app/files/page.tsx
Normal file
1167
apps/frontend/src/app/files/page.tsx
Normal file
File diff suppressed because it is too large
Load Diff
103
apps/frontend/src/app/globals.css
Normal file
103
apps/frontend/src/app/globals.css
Normal file
@@ -0,0 +1,103 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
@layer base {
|
||||
:root {
|
||||
--background: #f8fafc;
|
||||
--foreground: #0f172a;
|
||||
--card: #ffffff;
|
||||
--card-foreground: #0f172a;
|
||||
--primary: #16a34a;
|
||||
--primary-foreground: #ffffff;
|
||||
--secondary: #f1f5f9;
|
||||
--secondary-foreground: #334155;
|
||||
--muted: #f1f5f9;
|
||||
--muted-foreground: #64748b;
|
||||
--accent: #22c55e;
|
||||
--accent-foreground: #ffffff;
|
||||
--destructive: #ef4444;
|
||||
--destructive-foreground: #ffffff;
|
||||
--border: #e2e8f0;
|
||||
--input: #e2e8f0;
|
||||
--ring: #16a34a;
|
||||
--radius: 0.75rem;
|
||||
}
|
||||
}
|
||||
|
||||
body {
|
||||
color: var(--foreground);
|
||||
background: #f8fafc;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Inter", Helvetica, Arial, sans-serif;
|
||||
overflow-x: hidden;
|
||||
background-image:
|
||||
radial-gradient(at 0% 0%, rgba(34, 197, 94, 0.05) 0px, transparent 45%),
|
||||
radial-gradient(at 100% 0%, rgba(16, 185, 129, 0.04) 0px, transparent 40%),
|
||||
radial-gradient(at 50% 100%, rgba(22, 163, 74, 0.03) 0px, transparent 50%);
|
||||
background-attachment: fixed;
|
||||
}
|
||||
|
||||
/* Custom crisp modern scrollbars */
|
||||
::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
}
|
||||
::-webkit-scrollbar-track {
|
||||
background: #f1f5f9;
|
||||
}
|
||||
::-webkit-scrollbar-thumb {
|
||||
background: #cbd5e1;
|
||||
border-radius: 9999px;
|
||||
}
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
background: #94a3b8;
|
||||
}
|
||||
|
||||
/* Premium White Glassmorphism & Card styles */
|
||||
.glass-panel {
|
||||
background: rgba(255, 255, 255, 0.94);
|
||||
backdrop-filter: blur(16px);
|
||||
-webkit-backdrop-filter: blur(16px);
|
||||
border: 1px solid rgba(226, 232, 240, 0.9);
|
||||
box-shadow: 0 4px 20px -2px rgba(15, 23, 42, 0.04);
|
||||
}
|
||||
|
||||
.glass-card {
|
||||
background: #ffffff;
|
||||
border: 1px solid #e2e8f0;
|
||||
box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.03), 0 1px 2px -1px rgba(0, 0, 0, 0.03);
|
||||
transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
}
|
||||
|
||||
.glass-card:hover {
|
||||
border-color: rgba(34, 197, 94, 0.5);
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 12px 24px -6px rgba(22, 163, 74, 0.12);
|
||||
}
|
||||
|
||||
.glow-card-active {
|
||||
box-shadow: 0 0 25px -5px rgba(34, 197, 94, 0.25);
|
||||
border-color: #22c55e;
|
||||
}
|
||||
|
||||
.gradient-text {
|
||||
background: linear-gradient(135deg, #15803d 0%, #16a34a 50%, #22c55e 100%);
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
}
|
||||
|
||||
.gradient-border {
|
||||
position: relative;
|
||||
background: linear-gradient(135deg, rgba(34, 197, 94, 0.3), rgba(16, 185, 129, 0.1), rgba(34, 197, 94, 0.1));
|
||||
padding: 1px;
|
||||
border-radius: 1rem;
|
||||
}
|
||||
|
||||
/* Watermark background animation */
|
||||
.watermark-bg {
|
||||
background-image: url('/logo.png');
|
||||
background-repeat: no-repeat;
|
||||
background-position: right -40px bottom -40px;
|
||||
background-size: 280px;
|
||||
opacity: 0.03;
|
||||
}
|
||||
BIN
apps/frontend/src/app/icon.png
Normal file
BIN
apps/frontend/src/app/icon.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 99 KiB |
82
apps/frontend/src/app/layout.tsx
Normal file
82
apps/frontend/src/app/layout.tsx
Normal file
@@ -0,0 +1,82 @@
|
||||
import type { Metadata } from 'next';
|
||||
import './globals.css';
|
||||
import { AuthProvider } from '@/context/auth-context';
|
||||
import { HydrationGuard } from '@/components/common/HydrationGuard';
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'Ecohub - Secure Video & File Sharing Management System',
|
||||
description: 'Enterprise-grade secure video streaming, file management, and administrator-controlled sharing platform by Ecohub',
|
||||
icons: {
|
||||
icon: '/logo.png',
|
||||
apple: '/logo.png',
|
||||
},
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<html lang="en" suppressHydrationWarning>
|
||||
<head>
|
||||
<script
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: `
|
||||
(function() {
|
||||
// Intercept extension hydration error noise before Next.js error overlay hooks console
|
||||
var origError = window.console.error;
|
||||
window.console.error = function() {
|
||||
var str = Array.prototype.slice.call(arguments).map(function(arg) {
|
||||
return typeof arg === 'string' ? arg : (arg && arg.message) || '';
|
||||
}).join(' ');
|
||||
|
||||
if (
|
||||
str.indexOf('bis_skin_checked') !== -1 ||
|
||||
str.indexOf('bis_register') !== -1 ||
|
||||
str.indexOf('cz-shortcut-listen') !== -1 ||
|
||||
str.indexOf('data-gr-ext-installed') !== -1
|
||||
) {
|
||||
return;
|
||||
}
|
||||
return origError.apply(window.console, arguments);
|
||||
};
|
||||
|
||||
// Real-time DOM attribute cleaner
|
||||
try {
|
||||
var clean = function() {
|
||||
var els = document.querySelectorAll('[bis_skin_checked], [bis_register]');
|
||||
for (var i = 0; i < els.length; i++) {
|
||||
els[i].removeAttribute('bis_skin_checked');
|
||||
els[i].removeAttribute('bis_register');
|
||||
}
|
||||
};
|
||||
var obs = new MutationObserver(function(mutations) {
|
||||
for (var i = 0; i < mutations.length; i++) {
|
||||
var m = mutations[i];
|
||||
if (m.type === 'attributes' && m.attributeName && m.attributeName.indexOf('bis_') === 0) {
|
||||
m.target.removeAttribute(m.attributeName);
|
||||
}
|
||||
}
|
||||
});
|
||||
if (document.documentElement) {
|
||||
obs.observe(document.documentElement, {
|
||||
attributes: true,
|
||||
subtree: true,
|
||||
attributeFilter: ['bis_skin_checked', 'bis_register']
|
||||
});
|
||||
clean();
|
||||
}
|
||||
} catch(e) {}
|
||||
})();
|
||||
`,
|
||||
}}
|
||||
/>
|
||||
</head>
|
||||
<body suppressHydrationWarning className="min-h-screen bg-[#f8fafc] text-slate-900 antialiased selection:bg-emerald-500/20 selection:text-emerald-800">
|
||||
<HydrationGuard />
|
||||
<AuthProvider>{children}</AuthProvider>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
165
apps/frontend/src/app/login/page.tsx
Normal file
165
apps/frontend/src/app/login/page.tsx
Normal file
@@ -0,0 +1,165 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useAuth } from '@/context/auth-context';
|
||||
import { EcohubLogo } from '@/components/common/EcohubLogo';
|
||||
import { EcohubWatermark } from '@/components/common/EcohubWatermark';
|
||||
import {
|
||||
Lock,
|
||||
User,
|
||||
Loader2,
|
||||
ArrowRight,
|
||||
Eye,
|
||||
EyeOff,
|
||||
ShieldCheck,
|
||||
} from 'lucide-react';
|
||||
|
||||
export default function LoginPage() {
|
||||
const router = useRouter();
|
||||
const { login } = useAuth();
|
||||
|
||||
const [identifier, setIdentifier] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
await login(identifier, password);
|
||||
router.push('/dashboard');
|
||||
} catch (err: any) {
|
||||
setError(err.message || 'Invalid username or password');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-[#f8fafc] flex items-center justify-center p-4 relative overflow-hidden selection:bg-emerald-500/20">
|
||||
{/* Ambient background glows */}
|
||||
<div className="absolute top-1/4 -left-20 w-96 h-96 bg-emerald-500/10 rounded-full blur-3xl pointer-events-none" />
|
||||
<div className="absolute bottom-1/4 -right-20 w-96 h-96 bg-lime-500/10 rounded-full blur-3xl pointer-events-none" />
|
||||
|
||||
<div className="w-full max-w-md space-y-6 relative z-10">
|
||||
{/* Brand Header */}
|
||||
<div className="text-center space-y-2">
|
||||
<div className="inline-flex items-center justify-center p-3 rounded-3xl bg-white shadow-xl shadow-slate-200/80 border border-slate-200/80 mb-1">
|
||||
<EcohubLogo size="xl" showText={false} />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-2xl font-black tracking-tight text-slate-900 flex items-center justify-center gap-1.5">
|
||||
<span>Ecohub</span>
|
||||
<span className="text-emerald-600">Cloud</span>
|
||||
</h1>
|
||||
<p className="text-xs text-slate-500 mt-1 font-medium">
|
||||
Enterprise Secure Video & Company File Management
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Login Card */}
|
||||
<div className="bg-white p-7 sm:p-8 rounded-3xl border border-slate-200 shadow-xl shadow-slate-200/50 relative">
|
||||
<div className="flex items-center justify-between pb-4 border-b border-slate-100 mb-5">
|
||||
<div>
|
||||
<h2 className="text-sm font-bold text-slate-900">Sign In</h2>
|
||||
<p className="text-[11px] text-slate-500">Access your organization files & shared media</p>
|
||||
</div>
|
||||
<span className="flex items-center gap-1 text-[11px] font-semibold text-emerald-700 bg-emerald-50 px-2.5 py-1 rounded-full border border-emerald-200">
|
||||
<span className="w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse" />
|
||||
Live Vault
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="mb-4 p-3 rounded-xl bg-rose-50 border border-rose-200 text-xs text-rose-700 flex items-center gap-2 font-medium">
|
||||
<span className="w-1.5 h-1.5 rounded-full bg-rose-500 shrink-0" />
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-4 text-xs">
|
||||
{/* Identifier input */}
|
||||
<div>
|
||||
<label className="block text-slate-700 font-semibold mb-1.5">
|
||||
Username or Email Address
|
||||
</label>
|
||||
<div className="relative">
|
||||
<input
|
||||
type="text"
|
||||
value={identifier}
|
||||
onChange={(e) => setIdentifier(e.target.value)}
|
||||
required
|
||||
placeholder="e.g. Ecohub or ecohub@fileshare.local"
|
||||
className="w-full pl-9 pr-3 py-2.5 rounded-xl bg-slate-50 border border-slate-200 text-slate-900 placeholder:text-slate-400 focus:outline-none focus:border-emerald-600 focus:ring-1 focus:ring-emerald-600 transition"
|
||||
/>
|
||||
<User className="w-4 h-4 text-slate-400 absolute left-3 top-3" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Password input */}
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-1.5">
|
||||
<label className="text-slate-700 font-semibold">Password</label>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
className="text-[11px] text-slate-500 hover:text-emerald-600 flex items-center gap-1 transition"
|
||||
>
|
||||
{showPassword ? <EyeOff className="w-3 h-3" /> : <Eye className="w-3 h-3" />}
|
||||
<span>{showPassword ? 'Hide' : 'Show'}</span>
|
||||
</button>
|
||||
</div>
|
||||
<div className="relative">
|
||||
<input
|
||||
type={showPassword ? 'text' : 'password'}
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
placeholder="Password"
|
||||
className="w-full pl-9 pr-10 py-2.5 rounded-xl bg-slate-50 border border-slate-200 text-slate-900 placeholder:text-slate-400 focus:outline-none focus:border-emerald-600 focus:ring-1 focus:ring-emerald-600 transition"
|
||||
/>
|
||||
<Lock className="w-4 h-4 text-slate-400 absolute left-3 top-3" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Submit button */}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isLoading}
|
||||
className="w-full mt-2 py-3 rounded-xl bg-emerald-600 hover:bg-emerald-500 active:scale-[0.99] text-white font-bold text-xs shadow-lg shadow-emerald-600/25 transition-all flex items-center justify-center gap-2 group disabled:opacity-50"
|
||||
>
|
||||
{isLoading ? (
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
) : (
|
||||
<>
|
||||
<span>Sign In to Ecohub Vault</span>
|
||||
<ArrowRight className="w-3.5 h-3.5 group-hover:translate-x-0.5 transition-transform" />
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{/* Footer Navigation */}
|
||||
<div className="flex items-center justify-between text-xs text-slate-500 px-2 font-medium">
|
||||
<span className="flex items-center gap-1">
|
||||
<ShieldCheck className="w-3.5 h-3.5 text-emerald-600" />
|
||||
Ecohub Enterprise Vault
|
||||
</span>
|
||||
<Link href="/register" className="text-emerald-700 hover:text-emerald-800 font-semibold transition">
|
||||
Create an account →
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<EcohubWatermark variant="corner" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
23
apps/frontend/src/app/not-found.tsx
Normal file
23
apps/frontend/src/app/not-found.tsx
Normal file
@@ -0,0 +1,23 @@
|
||||
import Link from 'next/link';
|
||||
|
||||
export default function NotFound() {
|
||||
return (
|
||||
<div className="min-h-screen bg-[#f8fafc] flex flex-col items-center justify-center p-4 text-center">
|
||||
<div className="max-w-md w-full bg-white rounded-2xl shadow-sm border border-slate-200/80 p-8 space-y-4">
|
||||
<div className="w-16 h-16 bg-emerald-50 text-emerald-600 rounded-full flex items-center justify-center mx-auto text-2xl font-bold">
|
||||
404
|
||||
</div>
|
||||
<h1 className="text-xl font-bold text-slate-800">Page Not Found</h1>
|
||||
<p className="text-sm text-slate-500">
|
||||
The page or file share resource you requested does not exist or has been moved.
|
||||
</p>
|
||||
<Link
|
||||
href="/dashboard"
|
||||
className="inline-flex items-center justify-center w-full px-4 py-2.5 text-sm font-medium text-white bg-emerald-600 hover:bg-emerald-700 rounded-xl transition shadow-sm"
|
||||
>
|
||||
Return to Dashboard
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
27
apps/frontend/src/app/page.tsx
Normal file
27
apps/frontend/src/app/page.tsx
Normal file
@@ -0,0 +1,27 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useAuth } from '@/context/auth-context';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
|
||||
export default function RootPage() {
|
||||
const { user, isLoading } = useAuth();
|
||||
const router = useRouter();
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLoading) {
|
||||
if (user) {
|
||||
router.replace('/files');
|
||||
} else {
|
||||
router.replace('/login');
|
||||
}
|
||||
}
|
||||
}, [user, isLoading, router]);
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-[#f8fafc] flex items-center justify-center">
|
||||
<Loader2 className="w-8 h-8 text-emerald-600 animate-spin" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
229
apps/frontend/src/app/register/page.tsx
Normal file
229
apps/frontend/src/app/register/page.tsx
Normal file
@@ -0,0 +1,229 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useAuth } from '@/context/auth-context';
|
||||
import { EcohubLogo } from '@/components/common/EcohubLogo';
|
||||
import { EcohubWatermark } from '@/components/common/EcohubWatermark';
|
||||
import { Lock, User, Mail, Loader2, ArrowRight, Building2, Clock } from 'lucide-react';
|
||||
|
||||
export default function RegisterPage() {
|
||||
const router = useRouter();
|
||||
const { register } = useAuth();
|
||||
|
||||
const [fullName, setFullName] = useState('');
|
||||
const [username, setUsername] = useState('');
|
||||
const [companyName, setCompanyName] = useState('');
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isSubmitted, setIsSubmitted] = useState(false);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
const res: any = await register({
|
||||
email,
|
||||
username,
|
||||
fullName,
|
||||
password,
|
||||
companyName: companyName.trim() || undefined,
|
||||
});
|
||||
|
||||
if (res?.pendingApproval) {
|
||||
setIsSubmitted(true);
|
||||
} else {
|
||||
router.push('/dashboard');
|
||||
}
|
||||
} catch (err: any) {
|
||||
setError(err.message || 'Registration failed');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (isSubmitted) {
|
||||
return (
|
||||
<div className="min-h-screen bg-[#f8fafc] flex items-center justify-center p-4 relative overflow-hidden">
|
||||
<EcohubWatermark variant="corner" />
|
||||
<div className="w-full max-w-md bg-white p-8 rounded-3xl border border-slate-200 shadow-xl shadow-slate-200/50 text-center space-y-5 relative z-10">
|
||||
<div className="w-16 h-16 rounded-2xl bg-amber-50 border border-amber-200 flex items-center justify-center text-amber-600 mx-auto shadow-inner">
|
||||
<Clock className="w-8 h-8" />
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-xl font-black text-slate-900">Account Pending Approval</h2>
|
||||
<p className="text-xs text-slate-500 mt-1 font-medium">
|
||||
Administrator or Super Admin review required
|
||||
</p>
|
||||
</div>
|
||||
<div className="p-4 bg-slate-50 border border-slate-200 rounded-2xl text-left text-xs space-y-1.5">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-slate-500">Full Name:</span>
|
||||
<span className="font-semibold text-slate-800">{fullName}</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-slate-500">Username:</span>
|
||||
<span className="font-mono font-semibold text-slate-800">@{username}</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-slate-500">Organization:</span>
|
||||
<span className="font-semibold text-slate-800">{companyName.trim() || 'Ecohub'}</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-slate-500">Status:</span>
|
||||
<span className="font-bold text-amber-700 bg-amber-100 px-2 py-0.5 rounded text-[10px]">
|
||||
PENDING APPROVAL
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-[11px] text-slate-600 leading-relaxed">
|
||||
Your registration is received! For system security, an <strong>Administrator</strong> or <strong>Super Admin</strong> must activate your account before you can log in.
|
||||
</p>
|
||||
<Link
|
||||
href="/login"
|
||||
className="inline-flex items-center justify-center w-full py-3 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white font-bold text-xs shadow-md shadow-emerald-600/20 transition-all"
|
||||
>
|
||||
Back to Sign In
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-[#f8fafc] flex items-center justify-center p-4 relative overflow-hidden">
|
||||
{/* Ambient background glows */}
|
||||
<div className="absolute top-1/4 -left-20 w-96 h-96 bg-emerald-500/10 rounded-full blur-3xl pointer-events-none" />
|
||||
<div className="absolute bottom-1/4 -right-20 w-96 h-96 bg-lime-500/10 rounded-full blur-3xl pointer-events-none" />
|
||||
|
||||
<div className="w-full max-w-md space-y-6 relative z-10">
|
||||
<div className="text-center space-y-2">
|
||||
<div className="inline-flex items-center justify-center p-3 rounded-3xl bg-white shadow-xl shadow-slate-200/80 border border-slate-200/80 mb-1">
|
||||
<EcohubLogo size="xl" showText={false} />
|
||||
</div>
|
||||
<h2 className="text-2xl font-black text-slate-900 tracking-tight">
|
||||
Create Ecohub Account
|
||||
</h2>
|
||||
<p className="text-xs text-slate-500">
|
||||
Receive private company storage space and instant video processing
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="bg-white p-7 sm:p-8 rounded-3xl border border-slate-200 shadow-xl shadow-slate-200/50">
|
||||
{error && (
|
||||
<div className="mb-4 p-3 rounded-xl bg-rose-50 border border-rose-200 text-xs text-rose-700 font-medium">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-3.5 text-xs">
|
||||
<div>
|
||||
<label className="block text-slate-700 font-semibold mb-1.5">Full Name</label>
|
||||
<div className="relative">
|
||||
<input
|
||||
type="text"
|
||||
value={fullName}
|
||||
onChange={(e) => setFullName(e.target.value)}
|
||||
required
|
||||
placeholder="e.g. John Doe"
|
||||
className="w-full pl-9 pr-3 py-2.5 rounded-xl bg-slate-50 border border-slate-200 text-slate-900 placeholder:text-slate-400 focus:outline-none focus:border-emerald-600 focus:ring-1 focus:ring-emerald-600 transition"
|
||||
/>
|
||||
<User className="w-4 h-4 text-slate-400 absolute left-3 top-3" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-slate-700 font-semibold mb-1.5">
|
||||
Company / Organization Name
|
||||
</label>
|
||||
<div className="relative">
|
||||
<input
|
||||
type="text"
|
||||
value={companyName}
|
||||
onChange={(e) => setCompanyName(e.target.value)}
|
||||
placeholder="e.g. Ecohub Technologies / Acme Corp"
|
||||
className="w-full pl-9 pr-3 py-2.5 rounded-xl bg-slate-50 border border-slate-200 text-slate-900 placeholder:text-slate-400 focus:outline-none focus:border-emerald-600 focus:ring-1 focus:ring-emerald-600 transition"
|
||||
/>
|
||||
<Building2 className="w-4 h-4 text-slate-400 absolute left-3 top-3" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className="block text-slate-700 font-semibold mb-1.5">Username</label>
|
||||
<input
|
||||
type="text"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
required
|
||||
placeholder="john_doe"
|
||||
className="w-full px-3 py-2.5 rounded-xl bg-slate-50 border border-slate-200 text-slate-900 placeholder:text-slate-400 focus:outline-none focus:border-emerald-600 focus:ring-1 focus:ring-emerald-600 transition"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-slate-700 font-semibold mb-1.5">Email Address</label>
|
||||
<div className="relative">
|
||||
<input
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
placeholder="john@example.com"
|
||||
className="w-full pl-8 pr-3 py-2.5 rounded-xl bg-slate-50 border border-slate-200 text-slate-900 placeholder:text-slate-400 focus:outline-none focus:border-emerald-600 focus:ring-1 focus:ring-emerald-600 transition"
|
||||
/>
|
||||
<Mail className="w-3.5 h-3.5 text-slate-400 absolute left-2.5 top-3" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-slate-700 font-semibold mb-1.5">Password</label>
|
||||
<div className="relative">
|
||||
<input
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
minLength={8}
|
||||
placeholder="Minimum 8 characters"
|
||||
className="w-full pl-9 pr-3 py-2.5 rounded-xl bg-slate-50 border border-slate-200 text-slate-900 placeholder:text-slate-400 focus:outline-none focus:border-emerald-600 focus:ring-1 focus:ring-emerald-600 transition"
|
||||
/>
|
||||
<Lock className="w-4 h-4 text-slate-400 absolute left-3 top-3" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isLoading}
|
||||
className="w-full py-3 rounded-xl bg-emerald-600 hover:bg-emerald-500 active:scale-[0.99] text-white font-bold text-xs shadow-lg shadow-emerald-600/25 transition-all flex items-center justify-center gap-2 mt-4"
|
||||
>
|
||||
{isLoading ? (
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
) : (
|
||||
<>
|
||||
<span>Create Account & Initialize Vault</span>
|
||||
<ArrowRight className="w-3.5 h-3.5" />
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<p className="text-center text-xs text-slate-500">
|
||||
Already registered?{' '}
|
||||
<Link href="/login" className="text-emerald-700 hover:text-emerald-800 font-bold">
|
||||
Sign In
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<EcohubWatermark variant="corner" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
605
apps/frontend/src/app/s/[token]/page.tsx
Normal file
605
apps/frontend/src/app/s/[token]/page.tsx
Normal file
@@ -0,0 +1,605 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState, useEffect, useCallback, use } from 'react';
|
||||
import { api } from '@/lib/api-client';
|
||||
import { formatBytes, formatDuration, formatDate } from '@/lib/utils';
|
||||
import { EcohubLogo } from '@/components/common/EcohubLogo';
|
||||
import { EcohubWatermark } from '@/components/common/EcohubWatermark';
|
||||
import {
|
||||
FileVideo,
|
||||
FileText,
|
||||
FileSpreadsheet,
|
||||
FileCode,
|
||||
FileArchive,
|
||||
File as FileIcon,
|
||||
Folder,
|
||||
Download,
|
||||
Lock,
|
||||
Eye,
|
||||
EyeOff,
|
||||
ChevronRight,
|
||||
Play,
|
||||
AlertCircle,
|
||||
Loader2,
|
||||
Clock,
|
||||
X,
|
||||
} from 'lucide-react';
|
||||
|
||||
interface PublicFile {
|
||||
id: string;
|
||||
originalFilename: string;
|
||||
mimeType: string;
|
||||
fileExtension: string;
|
||||
fileSizeBytes: string;
|
||||
fileCategory: string;
|
||||
status: string;
|
||||
durationSeconds?: number | null;
|
||||
width?: number | null;
|
||||
height?: number | null;
|
||||
hasThumbnail?: boolean;
|
||||
hasHlsStream?: boolean;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
interface PublicSubfolder {
|
||||
id: string;
|
||||
name: string;
|
||||
logicalPath: string;
|
||||
fileCount: number;
|
||||
subfolderCount: number;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
interface PublicResourceResponse {
|
||||
requiresPassword?: boolean;
|
||||
title?: string;
|
||||
resourceType?: 'FILE' | 'FOLDER';
|
||||
allowDownload?: boolean;
|
||||
ownerName?: string;
|
||||
createdAt?: string;
|
||||
expiresAt?: string | null;
|
||||
file?: PublicFile;
|
||||
rootFolderId?: string;
|
||||
currentFolder?: {
|
||||
id: string;
|
||||
name: string;
|
||||
logicalPath: string;
|
||||
isRootOfShare: boolean;
|
||||
};
|
||||
subfolders?: PublicSubfolder[];
|
||||
files?: PublicFile[];
|
||||
}
|
||||
|
||||
export default function PublicSharePage({ params }: { params: Promise<{ token: string }> }) {
|
||||
const unwrappedParams = use(params);
|
||||
const token = unwrappedParams.token;
|
||||
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [data, setData] = useState<PublicResourceResponse | null>(null);
|
||||
|
||||
// Password state
|
||||
const [password, setPassword] = useState('');
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const [passwordError, setPasswordError] = useState<string | null>(null);
|
||||
const [isSubmittingPassword, setIsSubmittingPassword] = useState(false);
|
||||
|
||||
// Folder navigation state
|
||||
const [currentSubfolderId, setCurrentSubfolderId] = useState<string | undefined>(undefined);
|
||||
const [folderHistory, setFolderHistory] = useState<{ id?: string; name: string }[]>([]);
|
||||
|
||||
// Preview/Player modal for files inside shared folders
|
||||
const [activeVideoModal, setActiveVideoModal] = useState<PublicFile | null>(null);
|
||||
|
||||
const fetchResource = useCallback(
|
||||
async (pwd?: string, subfolderId?: string) => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
setPasswordError(null);
|
||||
try {
|
||||
const res = await api.getPublicShareResource(token, pwd || password, subfolderId);
|
||||
setData(res);
|
||||
if (!res.requiresPassword && subfolderId === undefined && res.resourceType === 'FOLDER') {
|
||||
setFolderHistory([{ id: undefined, name: res.title || 'Shared Folder' }]);
|
||||
}
|
||||
} catch (err: any) {
|
||||
if (err.message && err.message.toLowerCase().includes('password')) {
|
||||
setPasswordError('Incorrect password. Please try again.');
|
||||
} else {
|
||||
setError(err.message || 'Failed to load shared content');
|
||||
}
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
},
|
||||
[token, password],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
fetchResource();
|
||||
}, [fetchResource]);
|
||||
|
||||
const handlePasswordSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!password.trim()) {
|
||||
setPasswordError('Please enter the password');
|
||||
return;
|
||||
}
|
||||
setIsSubmittingPassword(true);
|
||||
await fetchResource(password.trim(), currentSubfolderId);
|
||||
setIsSubmittingPassword(false);
|
||||
};
|
||||
|
||||
const handleNavigateSubfolder = (subfolder: PublicSubfolder) => {
|
||||
setCurrentSubfolderId(subfolder.id);
|
||||
setFolderHistory((prev) => [...prev, { id: subfolder.id, name: subfolder.name }]);
|
||||
fetchResource(password, subfolder.id);
|
||||
};
|
||||
|
||||
const handleBreadcrumbClick = (index: number) => {
|
||||
const target = folderHistory[index];
|
||||
const newHistory = folderHistory.slice(0, index + 1);
|
||||
setFolderHistory(newHistory);
|
||||
setCurrentSubfolderId(target.id);
|
||||
fetchResource(password, target.id);
|
||||
};
|
||||
|
||||
const renderFileIcon = (category: string, mime: string) => {
|
||||
if (category === 'VIDEO' || mime.startsWith('video/')) {
|
||||
return <FileVideo className="w-8 h-8 text-rose-500" />;
|
||||
}
|
||||
if (category === 'IMAGE' || mime.startsWith('image/')) {
|
||||
return <FileIcon className="w-8 h-8 text-emerald-600" />;
|
||||
}
|
||||
if (category === 'AUDIO' || mime.startsWith('audio/')) {
|
||||
return <FileSpreadsheet className="w-8 h-8 text-amber-500" />;
|
||||
}
|
||||
if (category === 'DOCUMENT') {
|
||||
return <FileText className="w-8 h-8 text-sky-500" />;
|
||||
}
|
||||
if (category === 'ARCHIVE') {
|
||||
return <FileArchive className="w-8 h-8 text-emerald-600" />;
|
||||
}
|
||||
return <FileCode className="w-8 h-8 text-slate-500" />;
|
||||
};
|
||||
|
||||
// 1. Loading State
|
||||
if (isLoading && !data) {
|
||||
return (
|
||||
<div className="min-h-screen bg-[#f8fafc] text-slate-900 flex flex-col items-center justify-center p-4">
|
||||
<div className="flex flex-col items-center gap-3">
|
||||
<Loader2 className="w-8 h-8 text-emerald-600 animate-spin" />
|
||||
<p className="text-xs text-slate-500 font-medium tracking-wide">Loading Ecohub shared link...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 2. Error State
|
||||
if (error) {
|
||||
return (
|
||||
<div className="min-h-screen bg-[#f8fafc] text-slate-900 flex flex-col items-center justify-center p-4">
|
||||
<div className="w-full max-w-md p-8 rounded-3xl bg-white border border-slate-200 shadow-xl text-center space-y-4">
|
||||
<div className="w-14 h-14 rounded-2xl bg-rose-50 border border-rose-200 text-rose-600 flex items-center justify-center mx-auto">
|
||||
<AlertCircle className="w-7 h-7" />
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-lg font-bold text-slate-900">Unable to Access Link</h2>
|
||||
<p className="text-xs text-slate-500 mt-1.5 leading-relaxed">{error}</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => window.location.reload()}
|
||||
className="px-5 py-2 rounded-xl bg-slate-100 hover:bg-slate-200 text-xs font-semibold text-slate-700 transition-colors"
|
||||
>
|
||||
Try Again
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 3. Password Protection Screen
|
||||
if (data?.requiresPassword) {
|
||||
return (
|
||||
<div className="min-h-screen bg-[#f8fafc] text-slate-900 flex flex-col items-center justify-center p-4">
|
||||
<div className="w-full max-w-md p-8 rounded-3xl bg-white border border-slate-200 shadow-xl space-y-6">
|
||||
<div className="flex justify-center mb-2">
|
||||
<EcohubLogo size="md" showText={true} />
|
||||
</div>
|
||||
|
||||
<div className="text-center space-y-2">
|
||||
<div className="w-14 h-14 rounded-2xl bg-emerald-50 border border-emerald-200 text-emerald-600 flex items-center justify-center mx-auto shadow-inner">
|
||||
<Lock className="w-7 h-7" />
|
||||
</div>
|
||||
<h2 className="text-lg font-bold text-slate-900">Password Protected</h2>
|
||||
<p className="text-xs text-slate-500">
|
||||
{data.ownerName ? `Shared by ${data.ownerName}. ` : ''}
|
||||
Please enter the password to view this content.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handlePasswordSubmit} className="space-y-4">
|
||||
<div className="relative">
|
||||
<input
|
||||
type={showPassword ? 'text' : 'password'}
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder="Enter password"
|
||||
autoFocus
|
||||
required
|
||||
className="w-full px-4 py-2.5 rounded-xl bg-slate-50 border border-slate-200 text-xs text-slate-900 placeholder:text-slate-400 focus:outline-none focus:border-emerald-600 transition-all pr-10"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
className="absolute right-3 top-2.5 text-slate-400 hover:text-slate-600"
|
||||
>
|
||||
{showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{passwordError && (
|
||||
<p className="text-[11px] text-rose-600 flex items-center gap-1 font-medium">
|
||||
<AlertCircle className="w-3.5 h-3.5 flex-shrink-0" />
|
||||
{passwordError}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isSubmittingPassword}
|
||||
className="w-full py-2.5 rounded-xl bg-emerald-600 hover:bg-emerald-700 disabled:opacity-50 text-white text-xs font-semibold shadow-md shadow-emerald-600/25 transition-all flex items-center justify-center gap-2"
|
||||
>
|
||||
{isSubmittingPassword && <Loader2 className="w-4 h-4 animate-spin" />}
|
||||
<span>Unlock Content</span>
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 4. Main Shared Content View (File or Folder)
|
||||
const isVideo =
|
||||
data?.file &&
|
||||
(data.file.fileCategory === 'VIDEO' || data.file.mimeType.startsWith('video/'));
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-[#f8fafc] text-slate-900 flex flex-col relative selection:bg-emerald-500/20">
|
||||
<EcohubWatermark variant="corner" />
|
||||
|
||||
{/* Top Header Bar */}
|
||||
<header className="h-16 px-6 sm:px-10 border-b border-slate-200 bg-white/90 backdrop-blur-md flex items-center justify-between sticky top-0 z-40 shadow-sm">
|
||||
<div className="flex items-center gap-3">
|
||||
<EcohubLogo size="sm" showText={true} />
|
||||
<span className="hidden sm:inline text-[10px] uppercase px-2 py-0.5 rounded-full bg-emerald-50 text-emerald-700 border border-emerald-200 font-semibold">
|
||||
Secure Share Link
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 text-xs">
|
||||
{data?.expiresAt && (
|
||||
<span className="hidden sm:flex items-center gap-1 text-[11px] text-slate-500">
|
||||
<Clock className="w-3.5 h-3.5 text-amber-500" />
|
||||
Expires {formatDate(data.expiresAt)}
|
||||
</span>
|
||||
)}
|
||||
|
||||
{data?.resourceType === 'FILE' && data.file && data.allowDownload && (
|
||||
<a
|
||||
href={api.getPublicShareDownloadUrl(token, password)}
|
||||
download
|
||||
className="flex items-center gap-1.5 px-4 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white font-medium shadow-sm transition-all"
|
||||
>
|
||||
<Download className="w-3.5 h-3.5" />
|
||||
<span>Download File</span>
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{/* Main Container */}
|
||||
<main className="flex-1 p-4 sm:p-8 max-w-6xl w-full mx-auto space-y-6">
|
||||
{/* CASE A: SHARED SINGLE FILE */}
|
||||
{data?.resourceType === 'FILE' && data.file && (
|
||||
<div className="space-y-6">
|
||||
{/* If Video: Embedded Player with Ecohub Watermark */}
|
||||
{isVideo ? (
|
||||
<div className="rounded-3xl overflow-hidden bg-black border border-slate-200 shadow-xl relative aspect-video max-h-[72vh] flex items-center justify-center">
|
||||
{/* Ecohub Watermark overlay on the video */}
|
||||
<EcohubWatermark variant="player" className="absolute top-4 left-4 z-20" />
|
||||
|
||||
<video
|
||||
controls
|
||||
controlsList="nodownload"
|
||||
autoPlay={false}
|
||||
playsInline
|
||||
src={api.getPublicSharePlaybackUrl(token, password)}
|
||||
poster={
|
||||
data.file.hasThumbnail
|
||||
? api.getPublicShareThumbnailUrl(token, password)
|
||||
: undefined
|
||||
}
|
||||
className="w-full h-full object-contain"
|
||||
>
|
||||
Your browser does not support HTML5 video playback.
|
||||
</video>
|
||||
</div>
|
||||
) : data.file.fileCategory === 'IMAGE' ? (
|
||||
<div className="rounded-3xl overflow-hidden bg-white border border-slate-200 shadow-md p-4 flex items-center justify-center max-h-[70vh] relative">
|
||||
<EcohubWatermark variant="corner" />
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={api.getPublicSharePlaybackUrl(token, password)}
|
||||
alt={data.file.originalFilename}
|
||||
className="max-h-[66vh] max-w-full rounded-2xl object-contain"
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
/* Non-video, non-image file placeholder view */
|
||||
<div className="rounded-3xl bg-white border border-slate-200 p-12 text-center space-y-4 shadow-sm relative">
|
||||
<EcohubWatermark variant="subtle" />
|
||||
<div className="w-20 h-20 rounded-3xl bg-slate-50 border border-slate-200 flex items-center justify-center mx-auto shadow-sm">
|
||||
{renderFileIcon(data.file.fileCategory, data.file.mimeType)}
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-xl font-bold text-slate-900">{data.file.originalFilename}</h2>
|
||||
<p className="text-xs text-slate-500 mt-1">
|
||||
{formatBytes(data.file.fileSizeBytes)} • {data.file.mimeType}
|
||||
</p>
|
||||
</div>
|
||||
{data.allowDownload ? (
|
||||
<a
|
||||
href={api.getPublicShareDownloadUrl(token, password)}
|
||||
download
|
||||
className="inline-flex items-center gap-2 px-6 py-2.5 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white text-xs font-semibold shadow-md transition-all"
|
||||
>
|
||||
<Download className="w-4 h-4" />
|
||||
<span>Download File ({formatBytes(data.file.fileSizeBytes)})</span>
|
||||
</a>
|
||||
) : (
|
||||
<p className="text-xs text-amber-700 bg-amber-50 border border-amber-200 px-4 py-2 rounded-xl inline-block">
|
||||
Direct download is disabled by the owner of this link.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* File Metadata Card */}
|
||||
<div className="rounded-2xl bg-white border border-slate-200 p-5 shadow-sm flex flex-col sm:flex-row sm:items-center justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-base font-semibold text-slate-900">{data.file.originalFilename}</h1>
|
||||
<div className="flex flex-wrap items-center gap-3 text-xs text-slate-500 mt-1">
|
||||
<span>Size: {formatBytes(data.file.fileSizeBytes)}</span>
|
||||
<span>•</span>
|
||||
<span>Format: {data.file.fileExtension.toUpperCase()}</span>
|
||||
{data.file.durationSeconds && (
|
||||
<>
|
||||
<span>•</span>
|
||||
<span>Duration: {formatDuration(data.file.durationSeconds)}</span>
|
||||
</>
|
||||
)}
|
||||
{data.file.width && data.file.height && (
|
||||
<>
|
||||
<span>•</span>
|
||||
<span>
|
||||
Resolution: {data.file.width}x{data.file.height}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
<span>•</span>
|
||||
<span>Uploaded: {formatDate(data.file.createdAt)}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{data.allowDownload && (
|
||||
<a
|
||||
href={api.getPublicShareDownloadUrl(token, password)}
|
||||
download
|
||||
className="flex items-center justify-center gap-2 px-5 py-2.5 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-800 text-xs font-medium transition-colors"
|
||||
>
|
||||
<Download className="w-4 h-4" />
|
||||
<span>Download</span>
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* CASE B: SHARED FOLDER */}
|
||||
{data?.resourceType === 'FOLDER' && (
|
||||
<div className="space-y-6">
|
||||
{/* Folder Breadcrumb & Info Header */}
|
||||
<div className="rounded-2xl bg-white border border-slate-200 p-5 shadow-sm flex flex-col sm:flex-row sm:items-center justify-between gap-4">
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-8 h-8 rounded-lg bg-emerald-50 text-emerald-600 flex items-center justify-center">
|
||||
<Folder className="w-4 h-4" />
|
||||
</div>
|
||||
<h1 className="text-lg font-bold text-slate-900">{data.title || 'Shared Folder'}</h1>
|
||||
</div>
|
||||
|
||||
{/* Subfolder Breadcrumb Navigation */}
|
||||
<div className="flex items-center gap-1.5 text-xs text-slate-500">
|
||||
{folderHistory.map((item, idx) => (
|
||||
<React.Fragment key={idx}>
|
||||
{idx > 0 && <ChevronRight className="w-3.5 h-3.5 text-slate-400" />}
|
||||
<button
|
||||
onClick={() => handleBreadcrumbClick(idx)}
|
||||
className={`hover:text-emerald-600 transition-colors ${
|
||||
idx === folderHistory.length - 1 ? 'text-slate-900 font-semibold' : ''
|
||||
}`}
|
||||
>
|
||||
{item.name}
|
||||
</button>
|
||||
</React.Fragment>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="text-xs text-slate-500 flex items-center gap-4">
|
||||
<span>
|
||||
{data.subfolders?.length || 0} Folders • {data.files?.length || 0} Files
|
||||
</span>
|
||||
{!data.allowDownload && (
|
||||
<span className="px-2 py-0.5 rounded-md bg-amber-50 border border-amber-200 text-amber-700 text-[10px]">
|
||||
Downloads Restricted
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Subfolders Grid */}
|
||||
{data.subfolders && data.subfolders.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<h3 className="text-xs font-semibold text-slate-600 uppercase tracking-wider">
|
||||
Folders ({data.subfolders.length})
|
||||
</h3>
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-3">
|
||||
{data.subfolders.map((sf) => (
|
||||
<div
|
||||
key={sf.id}
|
||||
onClick={() => handleNavigateSubfolder(sf)}
|
||||
className="p-3.5 rounded-xl bg-white border border-slate-200 hover:border-emerald-500 hover:shadow-sm cursor-pointer transition-all flex items-center gap-3 group"
|
||||
>
|
||||
<Folder className="w-5 h-5 text-emerald-600 group-hover:scale-105 transition-transform" />
|
||||
<div className="truncate flex-1">
|
||||
<p className="text-xs font-semibold text-slate-800 truncate">{sf.name}</p>
|
||||
<p className="text-[10px] text-slate-500">
|
||||
{sf.fileCount} files • {sf.subfolderCount} folders
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Files Grid */}
|
||||
<div className="space-y-2">
|
||||
<h3 className="text-xs font-semibold text-slate-600 uppercase tracking-wider">
|
||||
Files ({data.files?.length || 0})
|
||||
</h3>
|
||||
|
||||
{data.files && data.files.length > 0 ? (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
{data.files.map((file) => {
|
||||
const isVid =
|
||||
file.fileCategory === 'VIDEO' || file.mimeType.startsWith('video/');
|
||||
return (
|
||||
<div
|
||||
key={file.id}
|
||||
className="rounded-2xl bg-white border border-slate-200 hover:border-emerald-300 p-4 shadow-sm hover:shadow-md transition-all flex flex-col justify-between group"
|
||||
>
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="w-10 h-10 rounded-xl bg-slate-50 border border-slate-200 flex items-center justify-center flex-shrink-0">
|
||||
{renderFileIcon(file.fileCategory, file.mimeType)}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<h4
|
||||
className="text-xs font-semibold text-slate-800 truncate group-hover:text-emerald-700 transition-colors"
|
||||
title={file.originalFilename}
|
||||
>
|
||||
{file.originalFilename}
|
||||
</h4>
|
||||
<p className="text-[10px] text-slate-500 mt-0.5">
|
||||
{formatBytes(file.fileSizeBytes)}
|
||||
{file.durationSeconds && ` • ${formatDuration(file.durationSeconds)}`}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Thumbnail / Action Bar */}
|
||||
<div className="mt-4 pt-3 border-t border-slate-100 flex items-center justify-between text-xs">
|
||||
{isVid ? (
|
||||
<button
|
||||
onClick={() => setActiveVideoModal(file)}
|
||||
className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-emerald-50 text-emerald-700 hover:bg-emerald-600 hover:text-white transition-colors font-medium text-[11px]"
|
||||
>
|
||||
<Play className="w-3 h-3 fill-current" />
|
||||
<span>Play Video</span>
|
||||
</button>
|
||||
) : (
|
||||
<span className="text-[10px] text-slate-500 uppercase tracking-wider font-semibold">
|
||||
{file.fileExtension}
|
||||
</span>
|
||||
)}
|
||||
|
||||
{data.allowDownload && (
|
||||
<a
|
||||
href={api.getPublicShareDownloadUrl(token, password, file.id)}
|
||||
download
|
||||
className="p-1.5 rounded-lg text-slate-400 hover:text-emerald-600 hover:bg-slate-100 transition-colors"
|
||||
title="Download"
|
||||
>
|
||||
<Download className="w-4 h-4" />
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<div className="rounded-2xl bg-white border border-slate-200 p-12 text-center text-slate-400 text-xs shadow-sm">
|
||||
This folder does not contain any files.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
|
||||
{/* Embedded Video Modal when playing a file inside a shared folder */}
|
||||
{activeVideoModal && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/80 backdrop-blur-md">
|
||||
<div className="w-full max-w-4xl bg-white border border-slate-200 rounded-3xl overflow-hidden shadow-2xl flex flex-col">
|
||||
<div className="p-4 border-b border-slate-200 flex items-center justify-between">
|
||||
<div className="truncate pr-4">
|
||||
<h3 className="text-sm font-semibold text-slate-900 truncate">
|
||||
{activeVideoModal.originalFilename}
|
||||
</h3>
|
||||
<p className="text-[10px] text-slate-500">
|
||||
{formatBytes(activeVideoModal.fileSizeBytes)}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setActiveVideoModal(null)}
|
||||
className="p-1.5 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-600 transition-colors"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="bg-black aspect-video flex items-center justify-center relative">
|
||||
<EcohubWatermark variant="player" className="absolute top-4 left-4 z-20" />
|
||||
<video
|
||||
controls
|
||||
controlsList="nodownload"
|
||||
autoPlay
|
||||
playsInline
|
||||
src={api.getPublicSharePlaybackUrl(token, password, activeVideoModal.id)}
|
||||
className="w-full h-full object-contain"
|
||||
>
|
||||
Your browser does not support HTML5 video playback.
|
||||
</video>
|
||||
</div>
|
||||
|
||||
{data?.allowDownload && (
|
||||
<div className="p-3 bg-slate-50 border-t border-slate-200 flex justify-end">
|
||||
<a
|
||||
href={api.getPublicShareDownloadUrl(token, password, activeVideoModal.id)}
|
||||
download
|
||||
className="flex items-center gap-1.5 px-4 py-1.5 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white text-xs font-semibold shadow-sm transition-all"
|
||||
>
|
||||
<Download className="w-3.5 h-3.5" />
|
||||
<span>Download Video</span>
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
229
apps/frontend/src/app/shared/page.tsx
Normal file
229
apps/frontend/src/app/shared/page.tsx
Normal file
@@ -0,0 +1,229 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useAuth } from '@/context/auth-context';
|
||||
import { api } from '@/lib/api-client';
|
||||
import { Navbar } from '@/components/layout/Navbar';
|
||||
import { Sidebar } from '@/components/layout/Sidebar';
|
||||
import { FileCard } from '@/components/file-manager/FileCard';
|
||||
import { FileRow } from '@/components/file-manager/FileRow';
|
||||
import { FilePreviewModal } from '@/components/file-manager/FilePreviewModal';
|
||||
import { EcohubWatermark } from '@/components/common/EcohubWatermark';
|
||||
import { Share2, Users, LayoutGrid, List, Search, Loader2, RefreshCw } from 'lucide-react';
|
||||
|
||||
export default function SharedPage() {
|
||||
const router = useRouter();
|
||||
const { user, isLoading } = useAuth();
|
||||
|
||||
const [sharedFiles, setSharedFiles] = useState<any[]>([]);
|
||||
const [isDataLoading, setIsDataLoading] = useState(true);
|
||||
const [isSyncing, setIsSyncing] = useState(false);
|
||||
const [lastSyncedAt, setLastSyncedAt] = useState<Date | null>(null);
|
||||
const [search, setSearch] = useState('');
|
||||
const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
|
||||
const [isSidebarOpen, setIsSidebarOpen] = useState(false);
|
||||
const [selectedFileForPreview, setSelectedFileForPreview] = useState<any | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLoading && !user) {
|
||||
router.push('/login');
|
||||
}
|
||||
}, [user, isLoading, router]);
|
||||
|
||||
const loadSharedFiles = async (isSilent = false) => {
|
||||
if (!user) return;
|
||||
if (!isSilent) setIsDataLoading(true);
|
||||
setIsSyncing(true);
|
||||
try {
|
||||
const files = await api.get<any[]>('/sharing/shared-with-me');
|
||||
setSharedFiles(files || []);
|
||||
setLastSyncedAt(new Date());
|
||||
} catch (err) {
|
||||
console.error('Failed to load shared files', err);
|
||||
} finally {
|
||||
if (!isSilent) setIsDataLoading(false);
|
||||
setIsSyncing(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
loadSharedFiles();
|
||||
}, [user]);
|
||||
|
||||
// Periodic Auto-Sync with Database (Silent every 8s + on Window Focus)
|
||||
useEffect(() => {
|
||||
if (!user) return;
|
||||
|
||||
const interval = setInterval(() => {
|
||||
if (document.visibilityState === 'visible') {
|
||||
loadSharedFiles(true);
|
||||
}
|
||||
}, 8000);
|
||||
|
||||
const handleFocus = () => {
|
||||
loadSharedFiles(true);
|
||||
};
|
||||
|
||||
window.addEventListener('focus', handleFocus);
|
||||
|
||||
return () => {
|
||||
clearInterval(interval);
|
||||
window.removeEventListener('focus', handleFocus);
|
||||
};
|
||||
}, [user]);
|
||||
|
||||
const filtered = sharedFiles.filter((f) =>
|
||||
f.originalFilename.toLowerCase().includes(search.toLowerCase()),
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-[#f8fafc] text-slate-900 flex flex-col relative">
|
||||
<EcohubWatermark variant="corner" />
|
||||
|
||||
<Navbar onToggleSidebar={() => setIsSidebarOpen(!isSidebarOpen)} />
|
||||
|
||||
<div className="flex-1 flex min-w-0">
|
||||
<Sidebar isOpen={isSidebarOpen} onClose={() => setIsSidebarOpen(false)} />
|
||||
|
||||
<main className="flex-1 lg:pl-64 min-w-0 flex flex-col w-full">
|
||||
<div className="flex-1 p-4 sm:p-6 lg:p-8 space-y-6 max-w-7xl w-full mx-auto">
|
||||
{/* Header */}
|
||||
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
|
||||
<div>
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<h1 className="text-xl font-bold text-slate-900 flex items-center gap-2.5">
|
||||
<Share2 className="w-5 h-5 text-emerald-600" />
|
||||
<span>Shared With Me</span>
|
||||
</h1>
|
||||
{/* Live Database Sync Badge */}
|
||||
<div
|
||||
className="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full bg-emerald-50 text-emerald-700 border border-emerald-200/80 text-[11px] font-semibold"
|
||||
title={lastSyncedAt ? `Live Auto-Sync Active • Last synced: ${lastSyncedAt.toLocaleTimeString()}` : 'Live Auto-Sync Active'}
|
||||
>
|
||||
<span className={`w-2 h-2 rounded-full ${isSyncing ? 'bg-amber-500 animate-spin' : 'bg-emerald-500 animate-pulse'}`} />
|
||||
<span>{isSyncing ? 'Syncing...' : 'Live DB Sync'}</span>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-slate-500 mt-1">
|
||||
Files and media shared with you by system administrators
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2.5 flex-wrap sm:flex-nowrap">
|
||||
{/* Manual Sync Button */}
|
||||
<button
|
||||
onClick={() => loadSharedFiles(false)}
|
||||
disabled={isSyncing}
|
||||
className="flex items-center gap-1.5 px-3 py-2 rounded-xl bg-white hover:bg-slate-50 border border-slate-200 text-slate-700 text-xs font-semibold shadow-xs transition-all active:scale-95 disabled:opacity-50"
|
||||
title="Sync with database"
|
||||
>
|
||||
<RefreshCw className={`w-3.5 h-3.5 text-emerald-600 ${isSyncing ? 'animate-spin' : ''}`} />
|
||||
<span>Sync DB</span>
|
||||
</button>
|
||||
|
||||
{/* Search */}
|
||||
<div className="relative w-48 sm:w-64 text-xs">
|
||||
<Search className="w-3.5 h-3.5 text-slate-400 absolute left-3 top-2.5" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search shared files..."
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
className="w-full pl-8 pr-3 py-1.5 rounded-xl bg-white border border-slate-200 text-slate-900 placeholder:text-slate-400 focus:outline-none focus:border-emerald-600 shadow-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* View toggle */}
|
||||
<div className="flex items-center p-0.5 rounded-lg bg-white border border-slate-200 shadow-sm">
|
||||
<button
|
||||
onClick={() => setViewMode('grid')}
|
||||
className={`p-1.5 rounded-md ${
|
||||
viewMode === 'grid' ? 'bg-emerald-600 text-white' : 'text-slate-500 hover:text-slate-800'
|
||||
}`}
|
||||
>
|
||||
<LayoutGrid className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setViewMode('list')}
|
||||
className={`p-1.5 rounded-md ${
|
||||
viewMode === 'list' ? 'bg-emerald-600 text-white' : 'text-slate-500 hover:text-slate-800'
|
||||
}`}
|
||||
>
|
||||
<List className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
{isDataLoading ? (
|
||||
<div className="p-16 flex items-center justify-center">
|
||||
<Loader2 className="w-8 h-8 text-emerald-600 animate-spin" />
|
||||
</div>
|
||||
) : filtered.length === 0 ? (
|
||||
<div className="p-16 text-center rounded-2xl bg-white border border-slate-200 shadow-sm">
|
||||
<Users className="w-12 h-12 text-slate-400 mx-auto mb-3" />
|
||||
<h3 className="text-sm font-medium text-slate-800">No shared files yet</h3>
|
||||
<p className="text-xs text-slate-500 mt-1 max-w-sm mx-auto">
|
||||
When an administrator grants you access to another user's files or videos, they will appear here.
|
||||
</p>
|
||||
</div>
|
||||
) : viewMode === 'grid' ? (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
|
||||
{filtered.map((file) => (
|
||||
<FileCard
|
||||
key={file.id}
|
||||
file={file}
|
||||
isOwner={false}
|
||||
onPreview={(f) => setSelectedFileForPreview(f)}
|
||||
onRename={() => {}}
|
||||
onMove={() => {}}
|
||||
onDelete={() => {}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="bg-white rounded-2xl overflow-hidden border border-slate-200 shadow-sm">
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full min-w-[640px] text-left border-collapse">
|
||||
<thead>
|
||||
<tr className="border-b border-slate-200 bg-slate-50 text-[11px] font-semibold text-slate-500 uppercase tracking-wider">
|
||||
<th className="py-3 px-4">Filename</th>
|
||||
<th className="py-3 px-4 hidden md:table-cell">Category</th>
|
||||
<th className="py-3 px-4">Size</th>
|
||||
<th className="py-3 px-4 hidden sm:table-cell">Uploaded</th>
|
||||
<th className="py-3 px-4">Status</th>
|
||||
<th className="py-3 px-4 text-right">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{filtered.map((file) => (
|
||||
<FileRow
|
||||
key={file.id}
|
||||
file={file}
|
||||
isOwner={false}
|
||||
onPreview={(f) => setSelectedFileForPreview(f)}
|
||||
onRename={() => {}}
|
||||
onMove={() => {}}
|
||||
onDelete={() => {}}
|
||||
/>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
{/* Preview Modal */}
|
||||
<FilePreviewModal
|
||||
isOpen={!!selectedFileForPreview}
|
||||
onClose={() => setSelectedFileForPreview(null)}
|
||||
file={selectedFileForPreview}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
198
apps/frontend/src/app/video/[id]/page.tsx
Normal file
198
apps/frontend/src/app/video/[id]/page.tsx
Normal file
@@ -0,0 +1,198 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { useParams, useRouter } from 'next/navigation';
|
||||
import { useAuth } from '@/context/auth-context';
|
||||
import { api } from '@/lib/api-client';
|
||||
import { formatBytes, formatDate } from '@/lib/utils';
|
||||
import { Navbar } from '@/components/layout/Navbar';
|
||||
import { Sidebar } from '@/components/layout/Sidebar';
|
||||
import { HlsVideoPlayer } from '@/components/video-player/HlsVideoPlayer';
|
||||
import { EcohubWatermark } from '@/components/common/EcohubWatermark';
|
||||
import {
|
||||
ArrowLeft,
|
||||
Download,
|
||||
Video,
|
||||
Calendar,
|
||||
HardDrive,
|
||||
Layers,
|
||||
Loader2,
|
||||
AlertTriangle,
|
||||
Building2,
|
||||
} from 'lucide-react';
|
||||
|
||||
export default function VideoPlayerPage() {
|
||||
const params = useParams();
|
||||
const fileId = params?.id as string;
|
||||
const router = useRouter();
|
||||
const { user, isLoading } = useAuth();
|
||||
|
||||
const [file, setFile] = useState<any | null>(null);
|
||||
const [isDataLoading, setIsDataLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isSidebarOpen, setIsSidebarOpen] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLoading && !user) {
|
||||
router.push('/login');
|
||||
}
|
||||
}, [user, isLoading, router]);
|
||||
|
||||
useEffect(() => {
|
||||
if (fileId && user) {
|
||||
setIsDataLoading(true);
|
||||
setError(null);
|
||||
|
||||
api.get<any>(`/files/${fileId}`)
|
||||
.then((res) => {
|
||||
setFile(res);
|
||||
})
|
||||
.catch((err) => {
|
||||
setError(err.message || 'Access denied or video not found');
|
||||
})
|
||||
.finally(() => {
|
||||
setIsDataLoading(false);
|
||||
});
|
||||
}
|
||||
}, [fileId, user]);
|
||||
|
||||
if (isLoading || isDataLoading) {
|
||||
return (
|
||||
<div className="min-h-screen bg-[#f8fafc] flex items-center justify-center">
|
||||
<Loader2 className="w-8 h-8 text-emerald-600 animate-spin" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const canDownload = file?.permissions ? file.permissions.canDownload : true;
|
||||
const downloadUrl = file ? api.getDownloadUrl(file.id) : '#';
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-[#f8fafc] text-slate-900 flex flex-col relative">
|
||||
<EcohubWatermark variant="corner" />
|
||||
|
||||
<Navbar onToggleSidebar={() => setIsSidebarOpen(!isSidebarOpen)} />
|
||||
|
||||
<div className="flex-1 flex">
|
||||
<Sidebar isOpen={isSidebarOpen} onClose={() => setIsSidebarOpen(false)} />
|
||||
|
||||
<main className="flex-1 lg:pl-64 p-6 sm:p-8 space-y-6 max-w-6xl mx-auto w-full">
|
||||
{/* Back button */}
|
||||
<div>
|
||||
<Link
|
||||
href="/files"
|
||||
className="inline-flex items-center gap-2 text-xs font-medium text-slate-600 hover:text-emerald-700 transition-colors"
|
||||
>
|
||||
<ArrowLeft className="w-4 h-4" />
|
||||
<span>Back to Company Explorer</span>
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{error ? (
|
||||
<div className="p-12 text-center rounded-2xl bg-rose-50 border border-rose-200 max-w-lg mx-auto shadow-sm">
|
||||
<AlertTriangle className="w-12 h-12 text-rose-600 mx-auto mb-3" />
|
||||
<h3 className="text-base font-semibold text-rose-900">Access Denied</h3>
|
||||
<p className="text-xs text-rose-700 mt-1">{error}</p>
|
||||
<Link
|
||||
href="/files"
|
||||
className="mt-4 inline-block px-4 py-2 rounded-xl bg-slate-100 text-slate-800 text-xs font-medium hover:bg-slate-200"
|
||||
>
|
||||
Return to Files
|
||||
</Link>
|
||||
</div>
|
||||
) : file ? (
|
||||
<div className="space-y-6">
|
||||
{/* Player Container */}
|
||||
<div className="w-full">
|
||||
<HlsVideoPlayer
|
||||
fileId={file.id}
|
||||
hasHlsStream={file.hasHlsStream}
|
||||
title={file.originalFilename}
|
||||
durationSeconds={file.durationSeconds}
|
||||
width={file.width}
|
||||
height={file.height}
|
||||
videoCodec={file.videoCodec}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Title & Actions Bar */}
|
||||
<div className="p-5 rounded-2xl bg-white border border-slate-200 shadow-sm flex flex-col sm:flex-row sm:items-center justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-lg font-bold text-slate-900">{file.originalFilename}</h1>
|
||||
<div className="flex items-center gap-2 mt-1">
|
||||
<p className="text-xs text-slate-500">
|
||||
Uploaded by {file.ownerName || 'User'} ({file.ownerEmail})
|
||||
</p>
|
||||
{file.ownerCompanyName && (
|
||||
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-[10px] font-semibold bg-emerald-50 text-emerald-700 border border-emerald-200">
|
||||
<Building2 className="w-3 h-3" />
|
||||
{file.ownerCompanyName}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
{canDownload ? (
|
||||
<a
|
||||
href={downloadUrl}
|
||||
download={file.originalFilename}
|
||||
className="flex items-center gap-2 px-4 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white font-medium text-xs shadow-md shadow-emerald-600/20 transition-all"
|
||||
>
|
||||
<Download className="w-4 h-4" />
|
||||
<span>Download Video</span>
|
||||
</a>
|
||||
) : (
|
||||
<span className="text-xs text-slate-500 italic bg-slate-50 px-3 py-1.5 rounded-lg border border-slate-200">
|
||||
Download permission not granted
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Technical Video Metadata */}
|
||||
<div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
|
||||
<div className="p-4 rounded-xl bg-white border border-slate-200 shadow-sm">
|
||||
<span className="text-[11px] text-slate-500 flex items-center gap-1.5 mb-1">
|
||||
<Video className="w-3.5 h-3.5 text-emerald-600" /> Resolution
|
||||
</span>
|
||||
<span className="text-sm font-semibold text-slate-900">
|
||||
{file.width && file.height ? `${file.width} x ${file.height}` : 'Standard'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="p-4 rounded-xl bg-white border border-slate-200 shadow-sm">
|
||||
<span className="text-[11px] text-slate-500 flex items-center gap-1.5 mb-1">
|
||||
<Layers className="w-3.5 h-3.5 text-sky-600" /> Codecs
|
||||
</span>
|
||||
<span className="text-sm font-semibold text-slate-900 uppercase font-mono">
|
||||
{file.videoCodec || 'H.264'} / {file.audioCodec || 'AAC'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="p-4 rounded-xl bg-white border border-slate-200 shadow-sm">
|
||||
<span className="text-[11px] text-slate-500 flex items-center gap-1.5 mb-1">
|
||||
<HardDrive className="w-3.5 h-3.5 text-emerald-600" /> File Size
|
||||
</span>
|
||||
<span className="text-sm font-semibold text-slate-900">
|
||||
{formatBytes(file.fileSizeBytes)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="p-4 rounded-xl bg-white border border-slate-200 shadow-sm">
|
||||
<span className="text-[11px] text-slate-500 flex items-center gap-1.5 mb-1">
|
||||
<Calendar className="w-3.5 h-3.5 text-amber-600" /> Upload Date
|
||||
</span>
|
||||
<span className="text-sm font-semibold text-slate-900">
|
||||
{formatDate(file.createdAt)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
153
apps/frontend/src/components/admin/AdminResetPasswordModal.tsx
Normal file
153
apps/frontend/src/components/admin/AdminResetPasswordModal.tsx
Normal file
@@ -0,0 +1,153 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState } from 'react';
|
||||
import { api } from '@/lib/api-client';
|
||||
import { KeyRound, Eye, EyeOff, CheckCircle2, AlertCircle, X, ShieldAlert } from 'lucide-react';
|
||||
|
||||
interface AdminResetPasswordModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
user: {
|
||||
id: string;
|
||||
username: string;
|
||||
fullName: string;
|
||||
} | null;
|
||||
onSuccess: () => void;
|
||||
}
|
||||
|
||||
export const AdminResetPasswordModal: React.FC<AdminResetPasswordModalProps> = ({
|
||||
isOpen,
|
||||
onClose,
|
||||
user,
|
||||
onSuccess,
|
||||
}) => {
|
||||
const [newPassword, setNewPassword] = useState('');
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [success, setSuccess] = useState<string | null>(null);
|
||||
|
||||
if (!isOpen || !user) return null;
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
setSuccess(null);
|
||||
|
||||
if (!newPassword || newPassword.length < 1) {
|
||||
setError('Please provide a new password');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
try {
|
||||
await api.patch(`/admin/users/${user.id}/password`, {
|
||||
newPassword,
|
||||
});
|
||||
|
||||
setSuccess(`Password for "${user.username}" reset successfully!`);
|
||||
setNewPassword('');
|
||||
setTimeout(() => {
|
||||
onSuccess();
|
||||
onClose();
|
||||
setSuccess(null);
|
||||
}, 1200);
|
||||
} catch (err: any) {
|
||||
setError(err.message || 'Failed to reset password');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/60 backdrop-blur-sm animate-in fade-in">
|
||||
<div className="relative w-full max-w-md rounded-2xl bg-white border border-slate-200 p-6 shadow-2xl">
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="absolute top-4 right-4 p-1.5 text-slate-400 hover:text-slate-600 rounded-lg hover:bg-slate-100 transition-colors"
|
||||
>
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
|
||||
<div className="flex items-center gap-3 mb-5">
|
||||
<div className="w-10 h-10 rounded-xl bg-amber-100 text-amber-700 flex items-center justify-center">
|
||||
<KeyRound className="w-5 h-5" />
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-lg font-bold text-slate-900">Reset User Password</h2>
|
||||
<p className="text-xs text-slate-500">
|
||||
Set new password for <span className="text-amber-700 font-semibold">{user.fullName}</span> ({user.username})
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="mb-4 flex items-center gap-2 p-3 rounded-xl bg-rose-50 border border-rose-200 text-xs text-rose-700">
|
||||
<AlertCircle className="w-4 h-4 shrink-0" />
|
||||
<span>{error}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{success && (
|
||||
<div className="mb-4 flex items-center gap-2 p-3 rounded-xl bg-emerald-50 border border-emerald-200 text-xs text-emerald-700">
|
||||
<CheckCircle2 className="w-4 h-4 shrink-0" />
|
||||
<span>{success}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-xs font-semibold text-slate-700 mb-1.5">
|
||||
New Password
|
||||
</label>
|
||||
<div className="relative">
|
||||
<input
|
||||
type={showPassword ? 'text' : 'password'}
|
||||
value={newPassword}
|
||||
onChange={(e) => setNewPassword(e.target.value)}
|
||||
placeholder="Type new password"
|
||||
required
|
||||
className="w-full px-3.5 py-2.5 rounded-xl bg-slate-50 border border-slate-300 text-sm text-slate-900 focus:outline-none focus:border-amber-600 focus:ring-1 focus:ring-amber-600 transition-colors pr-10"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600"
|
||||
>
|
||||
{showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
|
||||
</button>
|
||||
</div>
|
||||
<p className="mt-1.5 text-[11px] text-slate-500">
|
||||
Super Admin can view this password and change it anytime. Active sessions for this user will be revoked immediately.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-end gap-3 pt-3 border-t border-slate-100">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
disabled={isLoading}
|
||||
className="px-4 py-2 rounded-xl text-xs font-semibold text-slate-600 hover:text-slate-900 hover:bg-slate-100 transition-colors"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isLoading}
|
||||
className="flex items-center gap-2 px-5 py-2 rounded-xl bg-amber-600 hover:bg-amber-700 active:scale-95 text-white font-bold text-xs shadow-md shadow-amber-600/20 transition-all disabled:opacity-50"
|
||||
>
|
||||
{isLoading ? (
|
||||
<>Resetting...</>
|
||||
) : (
|
||||
<>
|
||||
<ShieldAlert className="w-4 h-4" />
|
||||
<span>Reset Password</span>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
342
apps/frontend/src/components/admin/BatchGrantModal.tsx
Normal file
342
apps/frontend/src/components/admin/BatchGrantModal.tsx
Normal file
@@ -0,0 +1,342 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { api } from '@/lib/api-client';
|
||||
import {
|
||||
ShieldCheck,
|
||||
CheckCircle2,
|
||||
AlertCircle,
|
||||
X,
|
||||
Play,
|
||||
Download,
|
||||
Eye,
|
||||
FolderTree,
|
||||
Calendar,
|
||||
Layers,
|
||||
Users,
|
||||
} from 'lucide-react';
|
||||
|
||||
interface BatchGrantModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
selectedFileIds?: string[];
|
||||
ownerId?: string;
|
||||
onSuccess: () => void;
|
||||
}
|
||||
|
||||
export const BatchGrantModal: React.FC<BatchGrantModalProps> = ({
|
||||
isOpen,
|
||||
onClose,
|
||||
selectedFileIds = [],
|
||||
ownerId,
|
||||
onSuccess,
|
||||
}) => {
|
||||
const [users, setUsers] = useState<any[]>([]);
|
||||
const [granteeUserId, setGranteeUserId] = useState('');
|
||||
const [sourceOwnerId, setSourceOwnerId] = useState(ownerId || '');
|
||||
const [grantAll, setGrantAll] = useState(selectedFileIds.length === 0);
|
||||
const [canViewMetadata, setCanViewMetadata] = useState(true);
|
||||
const [canPreview, setCanPreview] = useState(true);
|
||||
const [canPlay, setCanPlay] = useState(true);
|
||||
const [canDownload, setCanDownload] = useState(false);
|
||||
const [canListFolder, setCanListFolder] = useState(false);
|
||||
const [expiresAt, setExpiresAt] = useState('');
|
||||
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [success, setSuccess] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
loadUsers();
|
||||
setGrantAll(selectedFileIds.length === 0);
|
||||
setSourceOwnerId(ownerId || '');
|
||||
}
|
||||
}, [isOpen, selectedFileIds, ownerId]);
|
||||
|
||||
const loadUsers = async () => {
|
||||
try {
|
||||
const data: any = await api.get('/admin/users?limit=100');
|
||||
setUsers(data.users || []);
|
||||
} catch (err: any) {
|
||||
setError('Failed to fetch user list');
|
||||
}
|
||||
};
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
setSuccess(null);
|
||||
|
||||
const effectiveOwner = ownerId || sourceOwnerId;
|
||||
|
||||
if (!granteeUserId) {
|
||||
setError('Please select a recipient user');
|
||||
return;
|
||||
}
|
||||
|
||||
if (grantAll && !effectiveOwner) {
|
||||
setError('Please select which user owns the files you want to grant permissions for');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!grantAll && selectedFileIds.length === 0) {
|
||||
setError('Please select at least one file or choose "All Files" with an owner');
|
||||
return;
|
||||
}
|
||||
|
||||
if (effectiveOwner && granteeUserId === effectiveOwner) {
|
||||
setError('Recipient user cannot be the same as the file owner');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
try {
|
||||
await api.post('/admin/permissions/batch', {
|
||||
granteeUserId,
|
||||
fileIds: grantAll ? undefined : selectedFileIds,
|
||||
grantAllFilesOfOwner: grantAll ? effectiveOwner : undefined,
|
||||
canViewMetadata,
|
||||
canPreview,
|
||||
canPlay,
|
||||
canDownload,
|
||||
canListFolder,
|
||||
expiresAt: expiresAt ? new Date(expiresAt).toISOString() : undefined,
|
||||
});
|
||||
|
||||
setSuccess('Permissions granted successfully!');
|
||||
setTimeout(() => {
|
||||
onSuccess();
|
||||
onClose();
|
||||
setSuccess(null);
|
||||
}, 1200);
|
||||
} catch (err: any) {
|
||||
setError(err.message || 'Failed to grant permissions');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/60 backdrop-blur-sm animate-in fade-in">
|
||||
<div className="relative w-full max-w-lg rounded-2xl bg-white border border-slate-200 p-6 shadow-2xl">
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="absolute top-4 right-4 p-1.5 text-slate-400 hover:text-slate-600 rounded-lg hover:bg-slate-100 transition-colors"
|
||||
>
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
|
||||
<div className="flex items-center gap-3 mb-5">
|
||||
<div className="w-10 h-10 rounded-xl bg-emerald-50 text-emerald-600 flex items-center justify-center">
|
||||
<Layers className="w-5 h-5" />
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-lg font-bold text-slate-900">Batch Permission Grant</h2>
|
||||
<p className="text-xs text-slate-500">
|
||||
Grant permissions 1-by-1 or for ALL files at once
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="mb-4 flex items-center gap-2 p-3 rounded-xl bg-rose-50 border border-rose-200 text-xs text-rose-700">
|
||||
<AlertCircle className="w-4 h-4 shrink-0" />
|
||||
<span>{error}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{success && (
|
||||
<div className="mb-4 flex items-center gap-2 p-3 rounded-xl bg-emerald-50 border border-emerald-200 text-xs text-emerald-700">
|
||||
<CheckCircle2 className="w-4 h-4 shrink-0" />
|
||||
<span>{success}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
{/* Scope selection */}
|
||||
<div className="p-3.5 rounded-xl bg-slate-50 border border-slate-200 space-y-2">
|
||||
<div className="text-xs font-semibold text-slate-700">Grant Scope:</div>
|
||||
<div className="grid grid-cols-2 gap-2 text-xs">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setGrantAll(false)}
|
||||
disabled={selectedFileIds.length === 0}
|
||||
className={`p-2.5 rounded-lg border text-left transition-all ${
|
||||
!grantAll
|
||||
? 'border-emerald-600 bg-emerald-50 text-emerald-900 font-semibold'
|
||||
: 'border-slate-200 bg-white text-slate-600 hover:text-slate-900'
|
||||
} ${selectedFileIds.length === 0 ? 'opacity-40 cursor-not-allowed' : ''}`}
|
||||
>
|
||||
<div className="font-medium">Selected Files</div>
|
||||
<div className="text-[11px] text-slate-500">
|
||||
{selectedFileIds.length} file(s) selected
|
||||
</div>
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setGrantAll(true)}
|
||||
className={`p-2.5 rounded-lg border text-left transition-all ${
|
||||
grantAll
|
||||
? 'border-emerald-600 bg-emerald-50 text-emerald-900 font-semibold'
|
||||
: 'border-slate-200 bg-white text-slate-600 hover:text-slate-900'
|
||||
}`}
|
||||
>
|
||||
<div className="font-medium">All User Files (Select All)</div>
|
||||
<div className="text-[11px] text-slate-500">
|
||||
Grant across all files at once
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Select Source File Owner (when not pre-selected) */}
|
||||
{grantAll && !ownerId && (
|
||||
<div>
|
||||
<label className="block text-xs font-semibold text-slate-700 mb-1.5 flex items-center gap-1.5">
|
||||
<Users className="w-3.5 h-3.5 text-purple-600" />
|
||||
<span>Source File Owner (Whose files are being shared)</span>
|
||||
</label>
|
||||
<select
|
||||
value={sourceOwnerId}
|
||||
onChange={(e) => setSourceOwnerId(e.target.value)}
|
||||
required
|
||||
className="w-full px-3.5 py-2.5 rounded-xl bg-slate-50 border border-slate-200 text-sm text-slate-900 focus:outline-none focus:border-purple-600 transition-colors"
|
||||
>
|
||||
<option value="">-- Choose file owner --</option>
|
||||
{users.map((u) => (
|
||||
<option key={u.id} value={u.id}>
|
||||
{u.fullName} ({u.username}) {u.companyName ? `• ${u.companyName}` : ''}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Select Recipient User */}
|
||||
<div>
|
||||
<label className="block text-xs font-semibold text-slate-700 mb-1.5 flex items-center gap-1.5">
|
||||
<Users className="w-3.5 h-3.5 text-emerald-600" />
|
||||
<span>Grant Permissions To (Recipient User)</span>
|
||||
</label>
|
||||
<select
|
||||
value={granteeUserId}
|
||||
onChange={(e) => setGranteeUserId(e.target.value)}
|
||||
required
|
||||
className="w-full px-3.5 py-2.5 rounded-xl bg-slate-50 border border-slate-200 text-sm text-slate-900 focus:outline-none focus:border-emerald-600 transition-colors"
|
||||
>
|
||||
<option value="">-- Choose recipient user --</option>
|
||||
{users
|
||||
.filter((u) => u.id !== (ownerId || sourceOwnerId))
|
||||
.map((u) => (
|
||||
<option key={u.id} value={u.id}>
|
||||
{u.fullName} ({u.username}) {u.companyName ? `• ${u.companyName}` : ''} - {u.role}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Permission Flags */}
|
||||
<div className="space-y-2 pt-1">
|
||||
<div className="text-xs font-semibold text-slate-700">Allowed Actions:</div>
|
||||
<div className="grid grid-cols-2 gap-2 text-xs">
|
||||
<label className="flex items-center gap-2.5 p-2.5 rounded-xl bg-slate-50 border border-slate-200 cursor-pointer hover:bg-slate-100">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={canPlay}
|
||||
onChange={(e) => setCanPlay(e.target.checked)}
|
||||
className="rounded border-slate-300 text-emerald-600 focus:ring-emerald-500 w-4 h-4"
|
||||
/>
|
||||
<div className="flex items-center gap-1.5 text-slate-800 font-medium">
|
||||
<Play className="w-3.5 h-3.5 text-emerald-600" />
|
||||
<span>Can Play (Stream)</span>
|
||||
</div>
|
||||
</label>
|
||||
|
||||
<label className="flex items-center gap-2.5 p-2.5 rounded-xl bg-slate-50 border border-slate-200 cursor-pointer hover:bg-slate-100">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={canDownload}
|
||||
onChange={(e) => setCanDownload(e.target.checked)}
|
||||
className="rounded border-slate-300 text-emerald-600 focus:ring-emerald-500 w-4 h-4"
|
||||
/>
|
||||
<div className="flex items-center gap-1.5 text-slate-800 font-medium">
|
||||
<Download className="w-3.5 h-3.5 text-emerald-600" />
|
||||
<span>Can Download</span>
|
||||
</div>
|
||||
</label>
|
||||
|
||||
<label className="flex items-center gap-2.5 p-2.5 rounded-xl bg-slate-50 border border-slate-200 cursor-pointer hover:bg-slate-100">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={canPreview}
|
||||
onChange={(e) => setCanPreview(e.target.checked)}
|
||||
className="rounded border-slate-300 text-emerald-600 focus:ring-emerald-500 w-4 h-4"
|
||||
/>
|
||||
<div className="flex items-center gap-1.5 text-slate-800 font-medium">
|
||||
<Eye className="w-3.5 h-3.5 text-sky-600" />
|
||||
<span>Can Preview</span>
|
||||
</div>
|
||||
</label>
|
||||
|
||||
<label className="flex items-center gap-2.5 p-2.5 rounded-xl bg-slate-50 border border-slate-200 cursor-pointer hover:bg-slate-100">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={canListFolder}
|
||||
onChange={(e) => setCanListFolder(e.target.checked)}
|
||||
className="rounded border-slate-300 text-emerald-600 focus:ring-emerald-500 w-4 h-4"
|
||||
/>
|
||||
<div className="flex items-center gap-1.5 text-slate-800 font-medium">
|
||||
<FolderTree className="w-3.5 h-3.5 text-amber-600" />
|
||||
<span>Can List Folder</span>
|
||||
</div>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Expiration date */}
|
||||
<div>
|
||||
<label className="block text-xs font-semibold text-slate-700 mb-1 flex items-center gap-1.5">
|
||||
<Calendar className="w-3.5 h-3.5 text-slate-500" />
|
||||
<span>Expires At (Optional)</span>
|
||||
</label>
|
||||
<input
|
||||
type="datetime-local"
|
||||
value={expiresAt}
|
||||
onChange={(e) => setExpiresAt(e.target.value)}
|
||||
className="w-full px-3.5 py-2 rounded-xl bg-slate-50 border border-slate-200 text-xs text-slate-900 focus:outline-none focus:border-emerald-600"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-end gap-3 pt-3 border-t border-slate-200">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
disabled={isLoading}
|
||||
className="px-4 py-2 rounded-xl text-xs font-semibold text-slate-600 hover:text-slate-900 hover:bg-slate-100 transition-colors"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isLoading}
|
||||
className="flex items-center gap-2 px-5 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-700 active:scale-95 text-white font-medium text-xs shadow-md shadow-emerald-600/20 transition-all disabled:opacity-50"
|
||||
>
|
||||
{isLoading ? (
|
||||
<>Applying...</>
|
||||
) : (
|
||||
<>
|
||||
<ShieldCheck className="w-4 h-4" />
|
||||
<span>Grant Permissions</span>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
547
apps/frontend/src/components/admin/CreateUserModal.tsx
Normal file
547
apps/frontend/src/components/admin/CreateUserModal.tsx
Normal file
@@ -0,0 +1,547 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { api } from '@/lib/api-client';
|
||||
import { useAuth } from '@/context/auth-context';
|
||||
import { UserRole } from '@fileshare/shared';
|
||||
import { X, UserPlus, Loader2, Building2, Server, Check, Plus, CheckSquare, Square, Layers } from 'lucide-react';
|
||||
|
||||
interface CreateUserModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onSuccess: () => void;
|
||||
}
|
||||
|
||||
export const CreateUserModal: React.FC<CreateUserModalProps> = ({
|
||||
isOpen,
|
||||
onClose,
|
||||
onSuccess,
|
||||
}) => {
|
||||
const { isSuperAdmin } = useAuth();
|
||||
const [email, setEmail] = useState('');
|
||||
const [username, setUsername] = useState('');
|
||||
const [fullName, setFullName] = useState('');
|
||||
const [companyName, setCompanyName] = useState('Ecohub Technologies');
|
||||
const [availableCompanies, setAvailableCompanies] = useState<string[]>([]);
|
||||
const [accessAllCompanies, setAccessAllCompanies] = useState(false);
|
||||
const [allowedCompaniesList, setAllowedCompaniesList] = useState<string[]>([]);
|
||||
const [customCompanyInput, setCustomCompanyInput] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [role, setRole] = useState<UserRole>(UserRole.USER);
|
||||
const [quotaGb, setQuotaGb] = useState(10);
|
||||
const [canCreateShareLinks, setCanCreateShareLinks] = useState(false);
|
||||
const [canDeleteFiles, setCanDeleteFiles] = useState(true);
|
||||
const [canViewOtherUsers, setCanViewOtherUsers] = useState(false);
|
||||
const [remoteFileServerUrl, setRemoteFileServerUrl] = useState('');
|
||||
const [canUseRemoteServer, setCanUseRemoteServer] = useState(true);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
api.getCompanies().then((res) => {
|
||||
const list = res || [];
|
||||
setAvailableCompanies(list);
|
||||
}).catch(() => {});
|
||||
setAccessAllCompanies(false);
|
||||
setAllowedCompaniesList([]);
|
||||
}
|
||||
}, [isOpen]);
|
||||
|
||||
const handleAddNewCompany = async (nameToAdd: string) => {
|
||||
const trimmed = nameToAdd.trim();
|
||||
if (!trimmed) return;
|
||||
try {
|
||||
const updated = await api.createCompany(trimmed);
|
||||
setAvailableCompanies(updated || []);
|
||||
if (!allowedCompaniesList.some((c) => c.toLowerCase() === trimmed.toLowerCase())) {
|
||||
setAllowedCompaniesList((prev) => [...prev, trimmed]);
|
||||
}
|
||||
} catch {
|
||||
if (!availableCompanies.some((c) => c.toLowerCase() === trimmed.toLowerCase())) {
|
||||
setAvailableCompanies((prev) => [...prev, trimmed]);
|
||||
}
|
||||
if (!allowedCompaniesList.some((c) => c.toLowerCase() === trimmed.toLowerCase())) {
|
||||
setAllowedCompaniesList((prev) => [...prev, trimmed]);
|
||||
}
|
||||
}
|
||||
setCustomCompanyInput('');
|
||||
};
|
||||
|
||||
const handleSelectAllOrgs = () => {
|
||||
const primary = companyName.trim() || 'Ecohub Technologies';
|
||||
const all = Array.from(new Set([primary, ...availableCompanies]));
|
||||
setAllowedCompaniesList(all);
|
||||
};
|
||||
|
||||
const handleClearOrgs = () => {
|
||||
setAllowedCompaniesList([]);
|
||||
};
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
setIsSubmitting(true);
|
||||
|
||||
try {
|
||||
const primaryComp = companyName.trim() || 'Ecohub Technologies';
|
||||
const allowedCompaniesPayload = accessAllCompanies
|
||||
? '*'
|
||||
: JSON.stringify(Array.from(new Set([primaryComp, ...allowedCompaniesList])));
|
||||
|
||||
await api.post('/admin/users', {
|
||||
email,
|
||||
username,
|
||||
fullName,
|
||||
companyName: primaryComp,
|
||||
allowedCompanies: allowedCompaniesPayload,
|
||||
password,
|
||||
role,
|
||||
storageQuotaBytes: quotaGb * 1024 * 1024 * 1024,
|
||||
canCreateShareLinks,
|
||||
canDeleteFiles,
|
||||
canViewOtherUsers: isSuperAdmin ? (role === UserRole.SUPER_ADMIN ? true : canViewOtherUsers) : false,
|
||||
remoteFileServerUrl: remoteFileServerUrl.trim() || undefined,
|
||||
canUseRemoteServer,
|
||||
});
|
||||
|
||||
onSuccess();
|
||||
onClose();
|
||||
} catch (err: any) {
|
||||
setError(err.message || 'Failed to create user');
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/60 backdrop-blur-sm">
|
||||
<div className="w-full max-w-md bg-white border border-slate-200 rounded-2xl shadow-2xl overflow-hidden max-h-[92vh] flex flex-col">
|
||||
<div className="flex items-center justify-between px-6 py-4 border-b border-slate-200 shrink-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<UserPlus className="w-5 h-5 text-emerald-600" />
|
||||
<h3 className="text-base font-semibold text-slate-900">Create New User</h3>
|
||||
</div>
|
||||
<button onClick={onClose} className="p-1 rounded-lg text-slate-400 hover:text-slate-600">
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="p-6 space-y-3.5 text-xs overflow-y-auto custom-scrollbar">
|
||||
{error && (
|
||||
<div className="p-3 rounded-xl bg-rose-50 border border-rose-200 text-rose-700">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<label className="block text-slate-700 font-medium mb-1">Full Name</label>
|
||||
<input
|
||||
type="text"
|
||||
value={fullName}
|
||||
onChange={(e) => setFullName(e.target.value)}
|
||||
required
|
||||
className="w-full px-3 py-2 rounded-xl bg-slate-50 border border-slate-200 text-slate-900 focus:outline-none focus:border-emerald-600"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Primary Company / Organization */}
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-1">
|
||||
<label className="text-slate-700 font-medium flex items-center gap-1.5">
|
||||
<Building2 className="w-3.5 h-3.5 text-emerald-600" />
|
||||
<span>Primary Company / Organization</span>
|
||||
</label>
|
||||
<span className="text-[10px] text-slate-400">User's home organization</span>
|
||||
</div>
|
||||
<div className="relative">
|
||||
<input
|
||||
type="text"
|
||||
list="create-modal-companies-list"
|
||||
value={companyName}
|
||||
onChange={(e) => setCompanyName(e.target.value)}
|
||||
placeholder="e.g. Ecohub Technologies"
|
||||
required
|
||||
className="w-full px-3 py-2 rounded-xl bg-slate-50 border border-slate-200 text-slate-900 focus:outline-none focus:border-emerald-600 text-xs"
|
||||
/>
|
||||
<datalist id="create-modal-companies-list">
|
||||
{availableCompanies.map((c) => (
|
||||
<option key={c} value={c} />
|
||||
))}
|
||||
</datalist>
|
||||
</div>
|
||||
{availableCompanies.length > 0 && (
|
||||
<div className="flex items-center gap-1.5 flex-wrap pt-1.5">
|
||||
<span className="text-[10px] text-slate-400 font-medium">Quick pick:</span>
|
||||
{availableCompanies.slice(0, 6).map((c) => (
|
||||
<button
|
||||
key={c}
|
||||
type="button"
|
||||
onClick={() => setCompanyName(c)}
|
||||
className={`px-2 py-0.5 rounded-md text-[10px] font-medium transition-colors ${
|
||||
companyName.trim().toLowerCase() === c.toLowerCase()
|
||||
? 'bg-emerald-600 text-white'
|
||||
: 'bg-slate-100 hover:bg-slate-200 text-slate-600'
|
||||
}`}
|
||||
>
|
||||
{c}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<p className="text-[10px] text-slate-500 mt-1">
|
||||
This user's files and folders will reside under this company in the File Explorer.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Organizations & Companies Access Permission Section */}
|
||||
<div className="p-3.5 rounded-2xl bg-slate-50 border border-slate-200 space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<label className="text-slate-800 font-bold flex items-center gap-1.5 text-xs">
|
||||
<Layers className="w-4 h-4 text-emerald-600" />
|
||||
<span>Organizations Access Permissions</span>
|
||||
</label>
|
||||
<span
|
||||
className={`text-[10px] px-2 py-0.5 rounded-full font-bold font-mono ${
|
||||
accessAllCompanies
|
||||
? 'bg-purple-100 text-purple-700 border border-purple-200'
|
||||
: 'bg-emerald-100 text-emerald-700 border border-emerald-200'
|
||||
}`}
|
||||
>
|
||||
{accessAllCompanies
|
||||
? 'FULL ACCESS (ALL ORGS)'
|
||||
: `${
|
||||
Array.from(new Set([companyName.trim() || 'Ecohub Technologies', ...allowedCompaniesList]))
|
||||
.length
|
||||
} ORGS ALLOWED`}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<p className="text-[11px] text-slate-500 leading-relaxed">
|
||||
Define which companies' files & folders this user can access in the File Explorer.
|
||||
</p>
|
||||
|
||||
{/* Toggle: All Companies vs Selected Companies */}
|
||||
<div className="p-2.5 rounded-xl bg-white border border-slate-200/80 space-y-2">
|
||||
<label className="flex items-center gap-2.5 cursor-pointer font-semibold text-slate-800">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={accessAllCompanies}
|
||||
onChange={(e) => setAccessAllCompanies(e.target.checked)}
|
||||
className="w-4 h-4 rounded border-slate-300 text-purple-600 focus:ring-purple-500"
|
||||
/>
|
||||
<span className="text-xs">Allow Access to ALL Companies (Full Organization Scope)</span>
|
||||
</label>
|
||||
{accessAllCompanies && (
|
||||
<p className="text-[10px] text-purple-600 pl-6.5">
|
||||
User will automatically have access to all current and future organizations.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!accessAllCompanies && (
|
||||
<div className="space-y-2.5 pt-1">
|
||||
{/* Header with Quick Actions */}
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-[11px] font-bold text-slate-700">
|
||||
Select Permitted Organizations:
|
||||
</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleSelectAllOrgs}
|
||||
className="text-[11px] text-emerald-600 hover:text-emerald-700 font-semibold"
|
||||
>
|
||||
Select All
|
||||
</button>
|
||||
<span className="text-slate-300 text-[10px]">|</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleClearOrgs}
|
||||
className="text-[11px] text-slate-500 hover:text-slate-700 font-semibold"
|
||||
>
|
||||
Deselect All
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Organizations Checkboxes Grid */}
|
||||
{(() => {
|
||||
const primaryComp = companyName.trim() || 'Ecohub Technologies';
|
||||
const allCompsToDisplay = Array.from(
|
||||
new Set([primaryComp, ...availableCompanies]),
|
||||
).sort((a, b) => a.localeCompare(b));
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2 max-h-48 overflow-y-auto p-2 bg-white border border-slate-200 rounded-xl">
|
||||
{allCompsToDisplay.map((comp) => {
|
||||
const isPrimary = comp.toLowerCase() === primaryComp.toLowerCase();
|
||||
const isSelected =
|
||||
isPrimary ||
|
||||
allowedCompaniesList.some((c) => c.toLowerCase() === comp.toLowerCase());
|
||||
|
||||
return (
|
||||
<div
|
||||
key={comp}
|
||||
onClick={() => {
|
||||
if (isPrimary) return;
|
||||
if (isSelected) {
|
||||
setAllowedCompaniesList(
|
||||
allowedCompaniesList.filter(
|
||||
(c) => c.toLowerCase() !== comp.toLowerCase(),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
setAllowedCompaniesList([...allowedCompaniesList, comp]);
|
||||
}
|
||||
}}
|
||||
className={`flex items-center justify-between p-2 rounded-lg border text-xs cursor-pointer select-none transition-all ${
|
||||
isSelected
|
||||
? 'bg-emerald-50/90 border-emerald-300 text-emerald-950 font-medium'
|
||||
: 'bg-slate-50/80 border-slate-200 text-slate-600 hover:bg-slate-100 hover:border-slate-300'
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<div
|
||||
className={`w-4 h-4 rounded flex items-center justify-center border transition-colors shrink-0 ${
|
||||
isSelected
|
||||
? 'bg-emerald-600 border-emerald-600 text-white'
|
||||
: 'border-slate-300 bg-white'
|
||||
}`}
|
||||
>
|
||||
{isSelected && <Check className="w-3 h-3 stroke-[3]" />}
|
||||
</div>
|
||||
<span className="truncate">{comp}</span>
|
||||
</div>
|
||||
{isPrimary && (
|
||||
<span className="text-[9px] font-bold text-emerald-700 bg-emerald-100 px-1.5 py-0.5 rounded border border-emerald-200 shrink-0">
|
||||
Primary
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
|
||||
{/* Create & Register New Organization Input */}
|
||||
<div className="p-2.5 bg-white border border-slate-200 rounded-xl space-y-1">
|
||||
<span className="text-[10px] text-slate-500 font-medium block">
|
||||
Need to add another organization?
|
||||
</span>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Type organization name..."
|
||||
value={customCompanyInput}
|
||||
onChange={(e) => setCustomCompanyInput(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
handleAddNewCompany(customCompanyInput);
|
||||
}
|
||||
}}
|
||||
className="flex-1 px-2.5 py-1.5 rounded-lg bg-slate-50 border border-slate-200 text-slate-800 text-xs focus:outline-none focus:border-emerald-600"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleAddNewCompany(customCompanyInput)}
|
||||
className="px-3 py-1.5 rounded-lg bg-emerald-600 hover:bg-emerald-700 text-white font-semibold text-xs flex items-center gap-1 shadow-xs"
|
||||
>
|
||||
<Plus className="w-3.5 h-3.5" />
|
||||
<span>Add Org</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className="block text-slate-700 font-medium mb-1">Email Address</label>
|
||||
<input
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
className="w-full px-3 py-2 rounded-xl bg-slate-50 border border-slate-200 text-slate-900 focus:outline-none focus:border-emerald-600"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-slate-700 font-medium mb-1">Username</label>
|
||||
<input
|
||||
type="text"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
required
|
||||
className="w-full px-3 py-2 rounded-xl bg-slate-50 border border-slate-200 text-slate-900 focus:outline-none focus:border-emerald-600"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-slate-700 font-medium mb-1">Initial Password</label>
|
||||
<input
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
minLength={8}
|
||||
placeholder="Minimum 8 characters"
|
||||
className="w-full px-3 py-2 rounded-xl bg-slate-50 border border-slate-200 text-slate-900 focus:outline-none focus:border-emerald-600"
|
||||
/>
|
||||
<p className="text-[10px] text-slate-400 mt-1">Password must be at least 8 characters long</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className="block text-slate-700 font-medium mb-1">System Role</label>
|
||||
<select
|
||||
value={role}
|
||||
onChange={(e) => {
|
||||
const newRole = e.target.value as UserRole;
|
||||
setRole(newRole);
|
||||
if (newRole !== UserRole.USER) {
|
||||
setCanCreateShareLinks(true);
|
||||
}
|
||||
}}
|
||||
className="w-full px-3 py-2 rounded-xl bg-slate-50 border border-slate-200 text-slate-900 focus:outline-none focus:border-emerald-600"
|
||||
>
|
||||
<option value={UserRole.USER}>Regular User</option>
|
||||
<option value={UserRole.ADMIN}>Administrator</option>
|
||||
<option value={UserRole.SUPER_ADMIN}>Super Admin</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-slate-700 font-medium mb-1">Quota (GB)</label>
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
value={quotaGb}
|
||||
onChange={(e) => setQuotaGb(Number(e.target.value))}
|
||||
className="w-full px-3 py-2 rounded-xl bg-slate-50 border border-slate-200 text-slate-900 focus:outline-none focus:border-emerald-600"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* User Feature Permissions */}
|
||||
<div className="p-3.5 rounded-xl bg-slate-50 border border-slate-200 space-y-2.5">
|
||||
<span className="text-slate-800 font-semibold block">Feature Permissions</span>
|
||||
|
||||
<label className="flex items-start gap-2.5 cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={canCreateShareLinks}
|
||||
onChange={(e) => setCanCreateShareLinks(e.target.checked)}
|
||||
className="mt-0.5 w-4 h-4 rounded border-slate-300 text-emerald-600 focus:ring-emerald-500"
|
||||
/>
|
||||
<div>
|
||||
<span className="font-semibold text-slate-800 block">
|
||||
Allow Public Share Links (Google Drive style)
|
||||
</span>
|
||||
<span className="text-[10px] text-slate-500">
|
||||
Allow user to generate shareable links for videos, files, and folders.
|
||||
</span>
|
||||
</div>
|
||||
</label>
|
||||
|
||||
<label className="flex items-start gap-2.5 cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={canDeleteFiles}
|
||||
onChange={(e) => setCanDeleteFiles(e.target.checked)}
|
||||
className="mt-0.5 w-4 h-4 rounded border-slate-300 text-emerald-600 focus:ring-emerald-500"
|
||||
/>
|
||||
<div>
|
||||
<span className="font-semibold text-slate-800 block">
|
||||
Allow File & Folder Deletion
|
||||
</span>
|
||||
<span className="text-[10px] text-slate-500">
|
||||
Allow user to delete their own files and folders.
|
||||
</span>
|
||||
</div>
|
||||
</label>
|
||||
|
||||
{isSuperAdmin && (
|
||||
<label className="flex items-start gap-2.5 cursor-pointer pt-2 border-t border-slate-200/60">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={canViewOtherUsers || role === UserRole.SUPER_ADMIN}
|
||||
disabled={role === UserRole.SUPER_ADMIN}
|
||||
onChange={(e) => setCanViewOtherUsers(e.target.checked)}
|
||||
className="mt-0.5 w-4 h-4 rounded border-slate-300 text-purple-600 focus:ring-purple-500"
|
||||
/>
|
||||
<div>
|
||||
<span className="font-semibold text-slate-800 block flex items-center gap-1.5">
|
||||
<span>Allow Viewing Other Users' Information & Files</span>
|
||||
<span className="text-[9px] bg-purple-100 text-purple-700 px-1.5 py-0.2 rounded font-bold font-mono">SUPER ADMIN ONLY</span>
|
||||
</span>
|
||||
<span className="text-[10px] text-slate-500">
|
||||
When enabled, this user can view other users' directories, accounts, files, and system statistics. By default, only Super Admin can view other users.
|
||||
</span>
|
||||
</div>
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* User-Wise Remote File Server Link / Upload Endpoint */}
|
||||
<div className="p-3.5 rounded-xl bg-slate-50 border border-slate-200 space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<label className="text-slate-800 font-semibold flex items-center gap-1.5">
|
||||
<Server className="w-3.5 h-3.5 text-sky-600" />
|
||||
<span>Remote File Server Link / Upload Endpoint (Optional)</span>
|
||||
</label>
|
||||
<span className="text-[10px] text-sky-700 font-medium bg-sky-50 px-1.5 py-0.5 rounded border border-sky-200">
|
||||
User-Wise
|
||||
</span>
|
||||
</div>
|
||||
<input
|
||||
type="text"
|
||||
value={remoteFileServerUrl}
|
||||
onChange={(e) => setRemoteFileServerUrl(e.target.value)}
|
||||
placeholder="https://remotefileserver.custom.com/upload or http://192.168.1.100:8080/files"
|
||||
className="w-full px-3 py-2 rounded-xl bg-white border border-slate-300 text-slate-900 font-mono text-xs focus:outline-none focus:border-emerald-600"
|
||||
/>
|
||||
<p className="text-[10px] text-slate-500">
|
||||
If configured, this user's uploaded videos and files will automatically be mirrored/dispatched to this custom remote endpoint.
|
||||
</p>
|
||||
|
||||
<label className="flex items-center gap-2 pt-1 cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={canUseRemoteServer}
|
||||
onChange={(e) => setCanUseRemoteServer(e.target.checked)}
|
||||
className="w-3.5 h-3.5 rounded border-slate-300 text-emerald-600 focus:ring-emerald-500"
|
||||
/>
|
||||
<span className="text-[11px] text-slate-700 font-medium">
|
||||
Enable Remote File Server Mirroring / Uploads for this user
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="pt-3 flex justify-end gap-2 border-t border-slate-200">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="px-4 py-2 rounded-xl bg-slate-100 text-slate-700 hover:bg-slate-200 font-medium"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isSubmitting}
|
||||
className="px-4 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white font-medium flex items-center gap-1.5 shadow-sm"
|
||||
>
|
||||
{isSubmitting && <Loader2 className="w-3.5 h-3.5 animate-spin" />}
|
||||
<span>Create Account</span>
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
178
apps/frontend/src/components/admin/DeleteUserModal.tsx
Normal file
178
apps/frontend/src/components/admin/DeleteUserModal.tsx
Normal file
@@ -0,0 +1,178 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState } from 'react';
|
||||
import { api } from '@/lib/api-client';
|
||||
import { useAuth } from '@/context/auth-context';
|
||||
import { UserRole } from '@fileshare/shared';
|
||||
import { X, Trash2, AlertTriangle, Loader2, Building2, HardDrive, FileText } from 'lucide-react';
|
||||
import { formatBytes } from '@/lib/utils';
|
||||
|
||||
interface DeleteUserModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onSuccess: () => void;
|
||||
user: any | null;
|
||||
}
|
||||
|
||||
export const DeleteUserModal: React.FC<DeleteUserModalProps> = ({
|
||||
isOpen,
|
||||
onClose,
|
||||
onSuccess,
|
||||
user,
|
||||
}) => {
|
||||
const { user: currentUser } = useAuth();
|
||||
const [isDeleting, setIsDeleting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
if (!isOpen || !user) return null;
|
||||
|
||||
const isSuperAdmin = currentUser?.role === UserRole.SUPER_ADMIN;
|
||||
const isSelf = currentUser?.id === user.id;
|
||||
const isOtherCompany =
|
||||
!isSuperAdmin &&
|
||||
(user.companyName || 'Ecohub').trim().toLowerCase() !==
|
||||
(currentUser?.companyName || 'Ecohub').trim().toLowerCase();
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (isSelf || isOtherCompany) return;
|
||||
setError(null);
|
||||
setIsDeleting(true);
|
||||
|
||||
try {
|
||||
await api.deleteUser(user.id);
|
||||
onSuccess();
|
||||
onClose();
|
||||
} catch (err: any) {
|
||||
setError(err.message || 'Failed to delete user');
|
||||
} finally {
|
||||
setIsDeleting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/60 backdrop-blur-sm animate-in fade-in duration-200">
|
||||
<div className="w-full max-w-md bg-white border border-slate-200 rounded-2xl shadow-2xl overflow-hidden flex flex-col">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between px-6 py-4 border-b border-rose-100 bg-rose-50/50">
|
||||
<div className="flex items-center gap-2.5">
|
||||
<div className="w-9 h-9 rounded-xl bg-rose-100 border border-rose-200 flex items-center justify-center text-rose-600">
|
||||
<Trash2 className="w-5 h-5" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-base font-bold text-slate-900">Delete User Account</h3>
|
||||
<p className="text-xs text-rose-600 font-medium">Permanent System & Storage Cleanup</p>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="p-1.5 rounded-lg text-slate-400 hover:text-slate-600 hover:bg-slate-100 transition-colors"
|
||||
>
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="p-6 space-y-4 text-xs">
|
||||
{error && (
|
||||
<div className="p-3 rounded-xl bg-rose-50 border border-rose-200 text-rose-700 flex items-start gap-2">
|
||||
<AlertTriangle className="w-4 h-4 text-rose-600 shrink-0 mt-0.5" />
|
||||
<span>{error}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* User Info Card */}
|
||||
<div className="p-3.5 rounded-xl bg-slate-50 border border-slate-200 space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="font-bold text-slate-900 text-sm">{user.fullName}</span>
|
||||
<span
|
||||
className={`px-2 py-0.5 rounded text-[10px] font-mono font-bold uppercase ${
|
||||
user.role === UserRole.SUPER_ADMIN
|
||||
? 'bg-rose-100 text-rose-700'
|
||||
: user.role === UserRole.ADMIN
|
||||
? 'bg-amber-100 text-amber-700'
|
||||
: 'bg-slate-200 text-slate-700'
|
||||
}`}
|
||||
>
|
||||
{user.role}
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-slate-500 font-mono text-[11px]">
|
||||
@{user.username} • {user.email}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-2 pt-2 border-t border-slate-200/80 text-[11px]">
|
||||
<div className="flex items-center gap-1.5 text-slate-600">
|
||||
<Building2 className="w-3.5 h-3.5 text-emerald-600" />
|
||||
<span className="font-medium truncate">{user.companyName || 'Ecohub'}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5 text-slate-600">
|
||||
<FileText className="w-3.5 h-3.5 text-sky-600" />
|
||||
<span>{user.fileCount || 0} Files</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5 text-slate-600 col-span-2">
|
||||
<HardDrive className="w-3.5 h-3.5 text-amber-600" />
|
||||
<span>Storage: {formatBytes(Number(user.storageUsedBytes || 0))} used</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Warning Banner */}
|
||||
<div className="p-3 rounded-xl bg-amber-50 border border-amber-200/80 text-amber-800 space-y-1">
|
||||
<div className="flex items-center gap-1.5 font-bold text-amber-900">
|
||||
<AlertTriangle className="w-4 h-4 text-amber-600 shrink-0" />
|
||||
<span>Are you absolutely sure?</span>
|
||||
</div>
|
||||
<p className="text-[11px] text-amber-700 leading-relaxed">
|
||||
This action <strong>cannot be undone</strong>. Deleting this account will permanently erase the user profile, all their personal folders, and purge all their uploaded physical files from storage.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{isSelf && (
|
||||
<div className="p-3 rounded-xl bg-rose-50 border border-rose-200 text-rose-700 font-medium">
|
||||
You are currently logged into this account. You cannot delete yourself.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isOtherCompany && (
|
||||
<div className="p-3 rounded-xl bg-rose-50 border border-rose-200 text-rose-700 font-medium flex items-start gap-2">
|
||||
<AlertTriangle className="w-4 h-4 text-rose-600 shrink-0 mt-0.5" />
|
||||
<span>
|
||||
Admins cannot delete users belonging to other companies ({user.companyName || 'Other Company'}). Only Super Admin has permission to delete external company accounts.
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Actions */}
|
||||
<div className="pt-2 flex justify-end gap-2.5 border-t border-slate-100">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
disabled={isDeleting}
|
||||
className="px-4 py-2 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-700 font-semibold transition-colors"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleDelete}
|
||||
disabled={isDeleting || isSelf || isOtherCompany}
|
||||
className="px-4 py-2 rounded-xl bg-rose-600 hover:bg-rose-700 active:scale-95 text-white font-semibold flex items-center gap-1.5 shadow-sm shadow-rose-600/30 transition-all disabled:opacity-50 disabled:pointer-events-none"
|
||||
>
|
||||
{isDeleting ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
<span>Deleting User...</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
<span>Delete User Permanently</span>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user