feat: add authenticated document portal, user management (vignesh, vivek), audit logging, and admin dashboard
This commit is contained in:
parent
a4edd7b34e
commit
eae4dda2d8
12 changed files with 1681 additions and 26 deletions
|
|
@ -1,31 +1,51 @@
|
|||
services:
|
||||
onlyoffice-documentserver:
|
||||
build:
|
||||
context: .
|
||||
target: documentserver-community
|
||||
image: onlyoffice/documentserver
|
||||
onlyoffice:
|
||||
image: onlyoffice/documentserver:latest
|
||||
container_name: onlyoffice-documentserver
|
||||
restart: unless-stopped
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
environment:
|
||||
# Uncomment strings below to enable the JSON Web Token validation.
|
||||
#- JWT_ENABLED=true
|
||||
#- JWT_SECRET=secret
|
||||
#- JWT_HEADER=Authorization
|
||||
#- JWT_IN_BODY=true
|
||||
- DB_TYPE=postgres
|
||||
- DB_HOST=host.docker.internal
|
||||
- DB_PORT=5432
|
||||
- DB_NAME=onlyoffice
|
||||
- DB_USER=vignesh
|
||||
- DB_PWD=vtechnosoft@123A
|
||||
- AWS_REGION=ap-south-2
|
||||
- AWS_DEFAULT_REGION=ap-south-2
|
||||
- EXAMPLE_ENABLED=false
|
||||
- JWT_ENABLED=true
|
||||
- JWT_SECRET=vignesh_onlyoffice_secret_key_2026
|
||||
- USE_UNAUTHORIZED_STORAGE=true
|
||||
ports:
|
||||
- '80:80'
|
||||
- '443:443'
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "-f", "http://localhost:8000/info/info.json"]
|
||||
interval: 30s
|
||||
retries: 5
|
||||
start_period: 60s
|
||||
timeout: 10s
|
||||
stdin_open: true
|
||||
restart: always
|
||||
stop_grace_period: 60s
|
||||
- "127.0.0.1:8083:80"
|
||||
volumes:
|
||||
- /var/www/onlyoffice/Data
|
||||
- /var/log/onlyoffice
|
||||
- /var/lib/onlyoffice/documentserver/App_Data/cache/files
|
||||
- /var/www/onlyoffice/documentserver-example/public/files
|
||||
- /usr/share/fonts
|
||||
- ./data:/var/www/onlyoffice/Data
|
||||
- ./logs:/var/log/onlyoffice
|
||||
- ./custom-local.json:/etc/onlyoffice/documentserver/local-production-linux.json
|
||||
|
||||
portal:
|
||||
build:
|
||||
context: ./portal
|
||||
dockerfile: Dockerfile
|
||||
container_name: onlyoffice-portal
|
||||
restart: unless-stopped
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
environment:
|
||||
- PORT=8084
|
||||
- PGHOST=host.docker.internal
|
||||
- PGPORT=5432
|
||||
- PGDATABASE=onlyoffice
|
||||
- PGUSER=vignesh
|
||||
- PGPASSWORD=vtechnosoft@123A
|
||||
- AWS_REGION=ap-south-2
|
||||
- AWS_S3_BUCKET=trypostmedia
|
||||
- AWS_S3_PREFIX=documents/
|
||||
- JWT_SECRET=vignesh_onlyoffice_secret_key_2026
|
||||
- DOCSERVER_PUBLIC_URL=https://documents.tradhox.com
|
||||
ports:
|
||||
- "127.0.0.1:8084:8084"
|
||||
depends_on:
|
||||
- onlyoffice
|
||||
|
|
|
|||
12
portal/Dockerfile
Normal file
12
portal/Dockerfile
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
FROM node:20-alpine
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY package.json ./
|
||||
RUN npm install --production
|
||||
|
||||
COPY . .
|
||||
|
||||
EXPOSE 8084
|
||||
|
||||
CMD ["node", "server.js"]
|
||||
18
portal/package.json
Normal file
18
portal/package.json
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
{
|
||||
"name": "onlyoffice-portal",
|
||||
"version": "1.0.0",
|
||||
"description": "Authenticated Document Management Portal for ONLYOFFICE with Audit Logs",
|
||||
"main": "server.js",
|
||||
"scripts": {
|
||||
"start": "node server.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-s3": "^3.637.0",
|
||||
"@aws-sdk/s3-request-presigner": "^3.637.0",
|
||||
"cookie-parser": "^1.4.6",
|
||||
"express": "^4.19.2",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"multer": "^1.4.5-lts.1",
|
||||
"pg": "^8.12.0"
|
||||
}
|
||||
}
|
||||
328
portal/public/admin.html
Normal file
328
portal/public/admin.html
Normal file
|
|
@ -0,0 +1,328 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Admin Dashboard — Tradhox Documents</title>
|
||||
<link rel="stylesheet" href="/css/style.css">
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
|
||||
<style>
|
||||
.tab-nav {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
margin-bottom: 24px;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
padding-bottom: 12px;
|
||||
}
|
||||
.tab-btn {
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--text-secondary);
|
||||
font-size: 0.95rem;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
padding: 8px 16px;
|
||||
border-radius: var(--radius-md);
|
||||
transition: all 0.2s;
|
||||
}
|
||||
.tab-btn.active {
|
||||
background: var(--bg-surface-hover);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
.tab-content {
|
||||
display: none;
|
||||
}
|
||||
.tab-content.active {
|
||||
display: block;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header class="app-header">
|
||||
<div class="brand">
|
||||
<span class="brand-badge" style="background: linear-gradient(135deg, #10b981, #059669);">Admin</span>
|
||||
<span>Control Center & Audit Logs</span>
|
||||
</div>
|
||||
|
||||
<div class="user-nav">
|
||||
<a href="/" class="btn btn-secondary btn-sm">📁 Documents Workspace</a>
|
||||
<div class="user-badge">
|
||||
<span>🛡️</span>
|
||||
<strong id="admin-name">Admin</strong>
|
||||
</div>
|
||||
<button id="logout-btn" class="btn btn-secondary btn-sm">Logout</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main class="container">
|
||||
<div class="tab-nav">
|
||||
<button class="tab-btn active" onclick="switchTab('audit-tab')">📋 Audit Logs</button>
|
||||
<button class="tab-btn" onclick="switchTab('users-tab')">👥 User Management</button>
|
||||
</div>
|
||||
|
||||
<!-- Tab 1: Audit Logs -->
|
||||
<div id="audit-tab" class="tab-content active">
|
||||
<div class="toolbar">
|
||||
<div>
|
||||
<h2 style="font-size: 1.3rem; font-weight: 700;">Activity & Edit Audit Trail</h2>
|
||||
<p style="color: var(--text-secondary); font-size: 0.85rem;">Tracks who logged in, opened documents, and saved changes to S3</p>
|
||||
</div>
|
||||
<div style="display:flex; gap:12px;">
|
||||
<input type="text" id="audit-search" class="form-control" placeholder="Search user, action, file..." style="width:260px;" oninput="debounceAuditSearch()">
|
||||
<button class="btn btn-secondary" onclick="loadAuditLogs()">🔄 Refresh</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card-table">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Timestamp</th>
|
||||
<th>User</th>
|
||||
<th>Action</th>
|
||||
<th>Target</th>
|
||||
<th>IP Address</th>
|
||||
<th>Details</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="audit-tbody">
|
||||
<tr>
|
||||
<td colspan="6" style="text-align:center; padding:32px; color:var(--text-secondary);">Loading audit records...</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Tab 2: User Management -->
|
||||
<div id="users-tab" class="tab-content">
|
||||
<div class="toolbar">
|
||||
<div>
|
||||
<h2 style="font-size: 1.3rem; font-weight: 700;">Authorized Users</h2>
|
||||
<p style="color: var(--text-secondary); font-size: 0.85rem;">Manage who can log in and collaborate in the Document Server</p>
|
||||
</div>
|
||||
<button class="btn btn-primary" onclick="openAddUserModal()">➕ Add New User</button>
|
||||
</div>
|
||||
|
||||
<div class="card-table">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>Username</th>
|
||||
<th>Display Name</th>
|
||||
<th>Role</th>
|
||||
<th>Created Date</th>
|
||||
<th style="text-align: right;">Action</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="users-tbody">
|
||||
<tr>
|
||||
<td colspan="6" style="text-align:center; padding:32px; color:var(--text-secondary);">Loading users...</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<!-- Add User Modal -->
|
||||
<div id="add-user-modal" class="modal-backdrop">
|
||||
<div class="modal">
|
||||
<div class="modal-header">
|
||||
<h3 style="font-weight: 700;">Add New User</h3>
|
||||
<button onclick="closeUserModal()" style="background:none; border:none; color:var(--text-secondary); font-size:1.2rem; cursor:pointer;">×</button>
|
||||
</div>
|
||||
<form id="add-user-form">
|
||||
<div class="form-group">
|
||||
<label class="form-label">Username</label>
|
||||
<input type="text" id="new-user-username" class="form-control" placeholder="e.g. rahul" required>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">Full / Display Name</label>
|
||||
<input type="text" id="new-user-displayname" class="form-control" placeholder="e.g. Rahul Sharma" required>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">Password</label>
|
||||
<input type="password" id="new-user-password" class="form-control" placeholder="Minimum 6 characters" required>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">Role</label>
|
||||
<select id="new-user-role" class="form-control">
|
||||
<option value="user">User (View & Edit Documents)</option>
|
||||
<option value="admin">Admin (Full Access + Dashboard)</option>
|
||||
</select>
|
||||
</div>
|
||||
<div style="display:flex; justify-content:flex-end; gap:8px; margin-top: 20px;">
|
||||
<button type="button" class="btn btn-secondary" onclick="closeUserModal()">Cancel</button>
|
||||
<button type="submit" class="btn btn-primary">Create User</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
let searchTimeout;
|
||||
|
||||
function switchTab(tabId) {
|
||||
document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
|
||||
document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
|
||||
event.target.classList.add('active');
|
||||
document.getElementById(tabId).classList.add('active');
|
||||
|
||||
if (tabId === 'users-tab') loadUsers();
|
||||
if (tabId === 'audit-tab') loadAuditLogs();
|
||||
}
|
||||
|
||||
async function checkAuth() {
|
||||
try {
|
||||
const res = await fetch('/api/me');
|
||||
if (!res.ok) { window.location.href = '/login'; return; }
|
||||
const data = await res.json();
|
||||
if (data.user.role !== 'admin') {
|
||||
alert('Access denied: Admin role required');
|
||||
window.location.href = '/';
|
||||
return;
|
||||
}
|
||||
document.getElementById('admin-name').textContent = data.user.displayName;
|
||||
} catch (err) {
|
||||
window.location.href = '/login';
|
||||
}
|
||||
}
|
||||
|
||||
async function loadAuditLogs() {
|
||||
const tbody = document.getElementById('audit-tbody');
|
||||
const search = document.getElementById('audit-search').value.trim();
|
||||
const url = search ? `/api/admin/audit-logs?search=${encodeURIComponent(search)}` : '/api/admin/audit-logs';
|
||||
|
||||
try {
|
||||
const res = await fetch(url);
|
||||
const data = await res.json();
|
||||
if (!data.logs || data.logs.length === 0) {
|
||||
tbody.innerHTML = `<tr><td colspan="6" style="text-align:center; padding:32px; color:var(--text-secondary);">No audit logs found.</td></tr>`;
|
||||
return;
|
||||
}
|
||||
|
||||
tbody.innerHTML = data.logs.map(log => {
|
||||
const actionClass = getActionBadgeClass(log.action);
|
||||
return `
|
||||
<tr>
|
||||
<td style="color:var(--text-secondary); font-size:0.83rem; white-space:nowrap;">
|
||||
${new Date(log.created_at).toLocaleString()}
|
||||
</td>
|
||||
<td><strong>${escapeHtml(log.username)}</strong></td>
|
||||
<td><span class="badge ${actionClass}">${escapeHtml(log.action)}</span></td>
|
||||
<td><code>${escapeHtml(log.target || '-')}</code></td>
|
||||
<td style="color:var(--text-secondary); font-size:0.83rem;">${escapeHtml(log.ip_address || '-')}</td>
|
||||
<td style="font-size:0.85rem;">${escapeHtml(log.details || '-')}</td>
|
||||
</tr>
|
||||
`;
|
||||
}).join('');
|
||||
} catch (err) {
|
||||
tbody.innerHTML = `<tr><td colspan="6" style="text-align:center; color:var(--accent-danger); padding:32px;">Failed to load logs</td></tr>`;
|
||||
}
|
||||
}
|
||||
|
||||
function debounceAuditSearch() {
|
||||
clearTimeout(searchTimeout);
|
||||
searchTimeout = setTimeout(loadAuditLogs, 300);
|
||||
}
|
||||
|
||||
function getActionBadgeClass(action) {
|
||||
if (action.includes('LOGIN_SUCCESS')) return 'badge-login';
|
||||
if (action.includes('LOGIN_FAILED')) return 'badge-danger';
|
||||
if (action.includes('SAVED')) return 'badge-save';
|
||||
if (action.includes('OPENED')) return 'badge-open';
|
||||
if (action.includes('CREATED')) return 'badge-save';
|
||||
if (action.includes('DELETED')) return 'badge-danger';
|
||||
return 'badge-docx';
|
||||
}
|
||||
|
||||
async function loadUsers() {
|
||||
const tbody = document.getElementById('users-tbody');
|
||||
try {
|
||||
const res = await fetch('/api/admin/users');
|
||||
const data = await res.json();
|
||||
tbody.innerHTML = data.users.map(u => `
|
||||
<tr>
|
||||
<td>#${u.id}</td>
|
||||
<td><strong>${escapeHtml(u.username)}</strong></td>
|
||||
<td>${escapeHtml(u.display_name)}</td>
|
||||
<td><span class="role-tag">${escapeHtml(u.role)}</span></td>
|
||||
<td style="color:var(--text-secondary); font-size:0.85rem;">${new Date(u.created_at).toLocaleDateString()}</td>
|
||||
<td style="text-align: right;">
|
||||
${u.username === 'vignesh' ? '<span style="color:var(--text-secondary); font-size:0.8rem;">Protected</span>' : `
|
||||
<button class="btn btn-danger btn-sm" onclick="deleteUser('${escapeHtml(u.username)}')">Delete</button>
|
||||
`}
|
||||
</td>
|
||||
</tr>
|
||||
`).join('');
|
||||
} catch (err) {
|
||||
tbody.innerHTML = `<tr><td colspan="6" style="text-align:center; color:var(--accent-danger); padding:32px;">Failed to load users</td></tr>`;
|
||||
}
|
||||
}
|
||||
|
||||
function openAddUserModal() {
|
||||
document.getElementById('add-user-modal').style.display = 'flex';
|
||||
document.getElementById('new-user-username').focus();
|
||||
}
|
||||
|
||||
function closeUserModal() {
|
||||
document.getElementById('add-user-modal').style.display = 'none';
|
||||
document.getElementById('add-user-form').reset();
|
||||
}
|
||||
|
||||
document.getElementById('add-user-form').addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
const username = document.getElementById('new-user-username').value.trim();
|
||||
const displayName = document.getElementById('new-user-displayname').value.trim();
|
||||
const password = document.getElementById('new-user-password').value;
|
||||
const role = document.getElementById('new-user-role').value;
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/admin/users', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username, displayName, password, role })
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
alert(data.error || 'Failed to add user');
|
||||
} else {
|
||||
closeUserModal();
|
||||
loadUsers();
|
||||
}
|
||||
} catch (err) {
|
||||
alert('Server error adding user');
|
||||
}
|
||||
});
|
||||
|
||||
async function deleteUser(username) {
|
||||
if (!confirm(`Are you sure you want to delete user "${username}"?`)) return;
|
||||
try {
|
||||
const res = await fetch(`/api/admin/users/${encodeURIComponent(username)}`, { method: 'DELETE' });
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
alert(data.error || 'Failed to delete user');
|
||||
} else {
|
||||
loadUsers();
|
||||
}
|
||||
} catch (err) {
|
||||
alert('Error deleting user');
|
||||
}
|
||||
}
|
||||
|
||||
document.getElementById('logout-btn').addEventListener('click', async () => {
|
||||
await fetch('/api/logout', { method: 'POST' });
|
||||
window.location.href = '/login';
|
||||
});
|
||||
|
||||
function escapeHtml(str) {
|
||||
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
||||
}
|
||||
|
||||
checkAuth();
|
||||
loadAuditLogs();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
357
portal/public/css/style.css
Normal file
357
portal/public/css/style.css
Normal file
|
|
@ -0,0 +1,357 @@
|
|||
:root {
|
||||
--bg-primary: #0f172a;
|
||||
--bg-surface: #1e293b;
|
||||
--bg-surface-hover: #334155;
|
||||
--border-color: #334155;
|
||||
--text-primary: #f8fafc;
|
||||
--text-secondary: #94a3b8;
|
||||
--accent-primary: #3b82f6;
|
||||
--accent-hover: #2563eb;
|
||||
--accent-success: #10b981;
|
||||
--accent-warning: #f59e0b;
|
||||
--accent-danger: #ef4444;
|
||||
--radius-sm: 6px;
|
||||
--radius-md: 10px;
|
||||
--radius-lg: 16px;
|
||||
--shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.3);
|
||||
--shadow-md: 0 4px 12px rgba(0, 0, 0, 0.4);
|
||||
--font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: var(--font-family);
|
||||
background-color: var(--bg-primary);
|
||||
color: var(--text-primary);
|
||||
line-height: 1.5;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
a {
|
||||
color: var(--accent-primary);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
a:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
/* Header */
|
||||
.app-header {
|
||||
background: rgba(30, 41, 59, 0.85);
|
||||
backdrop-filter: blur(12px);
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
padding: 14px 24px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 100;
|
||||
}
|
||||
|
||||
.brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
font-weight: 700;
|
||||
font-size: 1.15rem;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.brand-badge {
|
||||
background: linear-gradient(135deg, #3b82f6, #6366f1);
|
||||
padding: 4px 8px;
|
||||
border-radius: var(--radius-sm);
|
||||
font-size: 0.75rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
|
||||
.user-nav {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.user-badge {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
background: var(--bg-surface-hover);
|
||||
padding: 6px 12px;
|
||||
border-radius: var(--radius-md);
|
||||
font-size: 0.88rem;
|
||||
border: 1px solid rgba(255, 255, 255, 0.05);
|
||||
}
|
||||
|
||||
.role-tag {
|
||||
background: rgba(59, 130, 246, 0.2);
|
||||
color: #60a5fa;
|
||||
font-size: 0.75rem;
|
||||
padding: 2px 6px;
|
||||
border-radius: var(--radius-sm);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* Buttons */
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 8px 16px;
|
||||
border-radius: var(--radius-md);
|
||||
font-weight: 600;
|
||||
font-size: 0.88rem;
|
||||
cursor: pointer;
|
||||
border: none;
|
||||
transition: all 0.2s ease;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background: var(--accent-primary);
|
||||
color: white;
|
||||
}
|
||||
.btn-primary:hover {
|
||||
background: var(--accent-hover);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background: var(--bg-surface-hover);
|
||||
color: var(--text-primary);
|
||||
border: 1px solid var(--border-color);
|
||||
}
|
||||
.btn-secondary:hover {
|
||||
background: #475569;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.btn-danger {
|
||||
background: rgba(239, 68, 68, 0.15);
|
||||
color: var(--accent-danger);
|
||||
border: 1px solid rgba(239, 68, 68, 0.3);
|
||||
}
|
||||
.btn-danger:hover {
|
||||
background: var(--accent-danger);
|
||||
color: white;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.btn-sm {
|
||||
padding: 4px 10px;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
/* Layout */
|
||||
.container {
|
||||
max-width: 1280px;
|
||||
margin: 0 auto;
|
||||
padding: 32px 24px;
|
||||
}
|
||||
|
||||
/* Toolbar */
|
||||
.toolbar {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 24px;
|
||||
flex-wrap: wrap;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.toolbar-actions {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
/* Tables */
|
||||
.card-table {
|
||||
background: var(--bg-surface);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: var(--radius-lg);
|
||||
overflow: hidden;
|
||||
box-shadow: var(--shadow-md);
|
||||
}
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
th {
|
||||
background: rgba(15, 23, 42, 0.6);
|
||||
padding: 14px 18px;
|
||||
font-size: 0.8rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
color: var(--text-secondary);
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
td {
|
||||
padding: 14px 18px;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
tr:last-child td {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
tr:hover td {
|
||||
background: rgba(255, 255, 255, 0.02);
|
||||
}
|
||||
|
||||
/* Badges */
|
||||
.badge {
|
||||
display: inline-block;
|
||||
padding: 3px 8px;
|
||||
border-radius: var(--radius-sm);
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.badge-docx { background: rgba(59, 130, 246, 0.2); color: #60a5fa; }
|
||||
.badge-xlsx { background: rgba(16, 185, 129, 0.2); color: #34d399; }
|
||||
.badge-pptx { background: rgba(245, 158, 11, 0.2); color: #fbbf24; }
|
||||
|
||||
.badge-login { background: rgba(59, 130, 246, 0.2); color: #60a5fa; }
|
||||
.badge-save { background: rgba(16, 185, 129, 0.2); color: #34d399; }
|
||||
.badge-open { background: rgba(99, 102, 241, 0.2); color: #a5b4fc; }
|
||||
.badge-danger { background: rgba(239, 68, 68, 0.2); color: #f87171; }
|
||||
|
||||
/* Forms */
|
||||
.form-group {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.form-label {
|
||||
display: block;
|
||||
font-size: 0.85rem;
|
||||
font-weight: 600;
|
||||
margin-bottom: 6px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.form-control {
|
||||
width: 100%;
|
||||
padding: 10px 14px;
|
||||
background: var(--bg-primary);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: var(--radius-md);
|
||||
color: var(--text-primary);
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
.form-control:focus {
|
||||
outline: none;
|
||||
border-color: var(--accent-primary);
|
||||
box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.2);
|
||||
}
|
||||
|
||||
/* Modal */
|
||||
.modal-backdrop {
|
||||
display: none;
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0, 0, 0, 0.7);
|
||||
backdrop-filter: blur(4px);
|
||||
z-index: 200;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.modal {
|
||||
background: var(--bg-surface);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: var(--radius-lg);
|
||||
width: 100%;
|
||||
max-width: 480px;
|
||||
padding: 24px;
|
||||
box-shadow: var(--shadow-md);
|
||||
}
|
||||
|
||||
.modal-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
/* Login Page Specific */
|
||||
.login-wrapper {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 100vh;
|
||||
padding: 24px;
|
||||
background: radial-gradient(circle at top, #1e293b 0%, #0f172a 100%);
|
||||
}
|
||||
|
||||
.login-card {
|
||||
width: 100%;
|
||||
max-width: 420px;
|
||||
background: var(--bg-surface);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: var(--radius-lg);
|
||||
padding: 36px;
|
||||
box-shadow: var(--shadow-md);
|
||||
}
|
||||
|
||||
.login-title {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 700;
|
||||
text-align: center;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.login-subtitle {
|
||||
color: var(--text-secondary);
|
||||
font-size: 0.88rem;
|
||||
text-align: center;
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.alert-box {
|
||||
padding: 10px 14px;
|
||||
border-radius: var(--radius-md);
|
||||
margin-bottom: 16px;
|
||||
font-size: 0.88rem;
|
||||
display: none;
|
||||
}
|
||||
.alert-error {
|
||||
background: rgba(239, 68, 68, 0.15);
|
||||
border: 1px solid rgba(239, 68, 68, 0.3);
|
||||
color: #f87171;
|
||||
}
|
||||
|
||||
/* Editor Page Fullscreen */
|
||||
.editor-wrapper {
|
||||
height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.editor-header {
|
||||
background: #1e293b;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
padding: 10px 20px;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
height: 52px;
|
||||
}
|
||||
|
||||
#editor-container {
|
||||
flex: 1;
|
||||
width: 100%;
|
||||
height: calc(100vh - 52px);
|
||||
}
|
||||
95
portal/public/editor.html
Normal file
95
portal/public/editor.html
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Editor — Tradhox Documents</title>
|
||||
<link rel="stylesheet" href="/css/style.css">
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
|
||||
<style>
|
||||
html, body {
|
||||
height: 100%;
|
||||
margin: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="editor-wrapper">
|
||||
<header class="editor-header">
|
||||
<div style="display:flex; align-items:center; gap:16px;">
|
||||
<a href="/" class="btn btn-secondary btn-sm">⬅️ Back to Documents</a>
|
||||
<h2 id="doc-title" style="font-size: 1.05rem; font-weight: 600; color: var(--text-primary);">Loading Document...</h2>
|
||||
</div>
|
||||
|
||||
<div style="display:flex; align-items:center; gap:12px;">
|
||||
<div class="user-badge" style="padding: 4px 10px; font-size: 0.8rem;">
|
||||
<span>👤 Editing as:</span>
|
||||
<strong id="editor-user-name">...</strong>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div id="editor-container">
|
||||
<div id="loading-state" style="display:flex; flex-direction:column; align-items:center; justify-content:center; height:100%; gap:12px; color:var(--text-secondary);">
|
||||
<div style="font-size: 2rem;">⏳</div>
|
||||
<div>Connecting to ONLYOFFICE Document Server...</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
const filename = urlParams.get('file');
|
||||
|
||||
if (!filename) {
|
||||
window.location.href = '/';
|
||||
}
|
||||
|
||||
document.getElementById('doc-title').textContent = decodeURIComponent(filename);
|
||||
|
||||
async function initEditor() {
|
||||
try {
|
||||
const userRes = await fetch('/api/me');
|
||||
if (!userRes.ok) {
|
||||
window.location.href = '/login';
|
||||
return;
|
||||
}
|
||||
const userData = await userRes.json();
|
||||
document.getElementById('editor-user-name').textContent = userData.user.displayName;
|
||||
|
||||
const configRes = await fetch(`/api/editor/config/${encodeURIComponent(filename)}`);
|
||||
if (!configRes.ok) {
|
||||
const errData = await configRes.json();
|
||||
alert(errData.error || 'Failed to load document');
|
||||
window.location.href = '/';
|
||||
return;
|
||||
}
|
||||
|
||||
const { config, docserverUrl } = await configRes.json();
|
||||
|
||||
// Dynamically load ONLYOFFICE Document Server API script
|
||||
const script = document.createElement('script');
|
||||
script.src = docserverUrl;
|
||||
script.onload = () => {
|
||||
document.getElementById('loading-state').remove();
|
||||
new DocsAPI.DocEditor("editor-container", config);
|
||||
};
|
||||
script.onerror = () => {
|
||||
document.getElementById('loading-state').innerHTML = `
|
||||
<div style="color:var(--accent-danger); font-size:1.5rem;">⚠️</div>
|
||||
<div style="color:var(--accent-danger);">Could not connect to ONLYOFFICE API at ${docserverUrl}</div>
|
||||
`;
|
||||
};
|
||||
document.head.appendChild(script);
|
||||
|
||||
} catch (err) {
|
||||
console.error('Init editor error:', err);
|
||||
alert('Error opening editor: ' + err.message);
|
||||
}
|
||||
}
|
||||
|
||||
initEditor();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
230
portal/public/index.html
Normal file
230
portal/public/index.html
Normal file
|
|
@ -0,0 +1,230 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Documents — Tradhox</title>
|
||||
<link rel="stylesheet" href="/css/style.css">
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
|
||||
</head>
|
||||
<body>
|
||||
<header class="app-header">
|
||||
<div class="brand">
|
||||
<span class="brand-badge">Tradhox</span>
|
||||
<span>Document Workspace</span>
|
||||
</div>
|
||||
|
||||
<div class="user-nav">
|
||||
<div id="admin-link-container"></div>
|
||||
<div class="user-badge">
|
||||
<span>👤</span>
|
||||
<strong id="user-display-name">Loading...</strong>
|
||||
<span id="user-role-badge" class="role-tag">user</span>
|
||||
</div>
|
||||
<button id="logout-btn" class="btn btn-secondary btn-sm">Logout</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main class="container">
|
||||
<div class="toolbar">
|
||||
<div>
|
||||
<h1 style="font-size: 1.5rem; font-weight: 700; margin-bottom: 4px;">My Documents</h1>
|
||||
<p style="color: var(--text-secondary); font-size: 0.88rem;">Collaborate and edit files in real time (stored in S3: trypostmedia)</p>
|
||||
</div>
|
||||
|
||||
<div class="toolbar-actions">
|
||||
<button class="btn btn-primary" onclick="openNewModal('docx')">📄 New Document</button>
|
||||
<button class="btn btn-secondary" onclick="openNewModal('xlsx')">📊 New Sheet</button>
|
||||
<button class="btn btn-secondary" onclick="openNewModal('pptx')">📑 New Slides</button>
|
||||
<label class="btn btn-secondary" style="cursor:pointer; margin-bottom:0;">
|
||||
📤 Upload File
|
||||
<input type="file" id="file-upload-input" style="display:none;" onchange="handleFileUpload(event)">
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card-table">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Document Name</th>
|
||||
<th>Type</th>
|
||||
<th>Created By</th>
|
||||
<th>Last Modified</th>
|
||||
<th style="text-align: right;">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="documents-tbody">
|
||||
<tr>
|
||||
<td colspan="5" style="text-align: center; color: var(--text-secondary); padding: 32px;">Loading documents...</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<!-- Create Document Modal -->
|
||||
<div id="new-doc-modal" class="modal-backdrop">
|
||||
<div class="modal">
|
||||
<div class="modal-header">
|
||||
<h3 id="modal-title" style="font-weight: 700;">Create Document</h3>
|
||||
<button onclick="closeModal()" style="background:none; border:none; color:var(--text-secondary); font-size:1.2rem; cursor:pointer;">×</button>
|
||||
</div>
|
||||
<form id="create-doc-form">
|
||||
<input type="hidden" id="modal-doc-type" value="docx">
|
||||
<div class="form-group">
|
||||
<label class="form-label">File Name</label>
|
||||
<input type="text" id="modal-doc-name" class="form-control" placeholder="e.g. Project Plan" required>
|
||||
</div>
|
||||
<div style="display:flex; justify-content:flex-end; gap:8px; margin-top: 20px;">
|
||||
<button type="button" class="btn btn-secondary" onclick="closeModal()">Cancel</button>
|
||||
<button type="submit" class="btn btn-primary">Create & Open</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
let currentUser = null;
|
||||
|
||||
async function loadUser() {
|
||||
try {
|
||||
const res = await fetch('/api/me');
|
||||
if (!res.ok) {
|
||||
window.location.href = '/login';
|
||||
return;
|
||||
}
|
||||
const data = await res.json();
|
||||
currentUser = data.user;
|
||||
document.getElementById('user-display-name').textContent = currentUser.displayName;
|
||||
document.getElementById('user-role-badge').textContent = currentUser.role;
|
||||
|
||||
if (currentUser.role === 'admin') {
|
||||
document.getElementById('admin-link-container').innerHTML = `
|
||||
<a href="/admin" class="btn btn-secondary btn-sm" style="color: #60a5fa; border-color: rgba(59, 130, 246, 0.3);">
|
||||
🛡️ Admin Dashboard
|
||||
</a>
|
||||
`;
|
||||
}
|
||||
} catch (err) {
|
||||
window.location.href = '/login';
|
||||
}
|
||||
}
|
||||
|
||||
async function loadDocuments() {
|
||||
const tbody = document.getElementById('documents-tbody');
|
||||
try {
|
||||
const res = await fetch('/api/documents');
|
||||
const data = await res.json();
|
||||
if (!data.documents || data.documents.length === 0) {
|
||||
tbody.innerHTML = `
|
||||
<tr>
|
||||
<td colspan="5" style="text-align: center; color: var(--text-secondary); padding: 48px;">
|
||||
No documents found. Click "New Document" to create your first file!
|
||||
</td>
|
||||
</tr>
|
||||
`;
|
||||
return;
|
||||
}
|
||||
|
||||
tbody.innerHTML = data.documents.map(doc => `
|
||||
<tr>
|
||||
<td>
|
||||
<strong style="color: var(--text-primary); cursor: pointer;" onclick="openEditor('${encodeURIComponent(doc.filename)}')">
|
||||
${escapeHtml(doc.filename)}
|
||||
</strong>
|
||||
</td>
|
||||
<td><span class="badge badge-${doc.file_type}">${doc.file_type.toUpperCase()}</span></td>
|
||||
<td>${escapeHtml(doc.created_by)}</td>
|
||||
<td style="color: var(--text-secondary); font-size: 0.85rem;">
|
||||
${new Date(doc.updated_at).toLocaleString()}
|
||||
</td>
|
||||
<td style="text-align: right;">
|
||||
<button class="btn btn-primary btn-sm" onclick="openEditor('${encodeURIComponent(doc.filename)}')">✏️ Edit</button>
|
||||
<a href="/api/documents/download/${encodeURIComponent(doc.filename)}" class="btn btn-secondary btn-sm" style="margin-left:6px;">⬇️ Download</a>
|
||||
</td>
|
||||
</tr>
|
||||
`).join('');
|
||||
} catch (err) {
|
||||
tbody.innerHTML = `<tr><td colspan="5" style="text-align:center; color:var(--accent-danger); padding:32px;">Failed to load documents</td></tr>`;
|
||||
}
|
||||
}
|
||||
|
||||
function openEditor(filename) {
|
||||
window.location.href = `/editor?file=${filename}`;
|
||||
}
|
||||
|
||||
function openNewModal(type) {
|
||||
document.getElementById('modal-doc-type').value = type;
|
||||
const typeNames = { docx: 'Document (.docx)', xlsx: 'Spreadsheet (.xlsx)', pptx: 'Presentation (.pptx)' };
|
||||
document.getElementById('modal-title').textContent = `New ${typeNames[type]}`;
|
||||
document.getElementById('modal-doc-name').value = '';
|
||||
document.getElementById('new-doc-modal').style.display = 'flex';
|
||||
document.getElementById('modal-doc-name').focus();
|
||||
}
|
||||
|
||||
function closeModal() {
|
||||
document.getElementById('new-doc-modal').style.display = 'none';
|
||||
}
|
||||
|
||||
document.getElementById('create-doc-form').addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
const filename = document.getElementById('modal-doc-name').value.trim();
|
||||
const fileType = document.getElementById('modal-doc-type').value;
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/documents/create', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ filename, fileType })
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
alert(data.error || 'Failed to create document');
|
||||
} else {
|
||||
closeModal();
|
||||
openEditor(encodeURIComponent(data.filename));
|
||||
}
|
||||
} catch (err) {
|
||||
alert('Server error creating document');
|
||||
}
|
||||
});
|
||||
|
||||
async function handleFileUpload(event) {
|
||||
const file = event.target.files[0];
|
||||
if (!file) return;
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/documents/upload', {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
});
|
||||
const data = await res.json();
|
||||
if (res.ok) {
|
||||
loadDocuments();
|
||||
} else {
|
||||
alert(data.error || 'Upload failed');
|
||||
}
|
||||
} catch (err) {
|
||||
alert('Upload failed due to connection error');
|
||||
}
|
||||
event.target.value = '';
|
||||
}
|
||||
|
||||
document.getElementById('logout-btn').addEventListener('click', async () => {
|
||||
await fetch('/api/logout', { method: 'POST' });
|
||||
window.location.href = '/login';
|
||||
});
|
||||
|
||||
function escapeHtml(str) {
|
||||
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
||||
}
|
||||
|
||||
loadUser();
|
||||
loadDocuments();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
71
portal/public/login.html
Normal file
71
portal/public/login.html
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Login — Tradhox Documents</title>
|
||||
<link rel="stylesheet" href="/css/style.css">
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
|
||||
</head>
|
||||
<body>
|
||||
<div class="login-wrapper">
|
||||
<div class="login-card">
|
||||
<div style="text-align:center; margin-bottom: 16px;">
|
||||
<span class="brand-badge" style="font-size: 0.85rem; padding: 6px 12px;">TRADHOX</span>
|
||||
</div>
|
||||
<h1 class="login-title">Documents Portal</h1>
|
||||
<p class="login-subtitle">Sign in to access and edit team documents</p>
|
||||
|
||||
<div id="error-alert" class="alert-box alert-error"></div>
|
||||
|
||||
<form id="login-form">
|
||||
<div class="form-group">
|
||||
<label class="form-label" for="username">Username</label>
|
||||
<input type="text" id="username" class="form-control" placeholder="e.g. vignesh or vivek" required autofocus>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label class="form-label" for="password">Password</label>
|
||||
<input type="password" id="password" class="form-control" placeholder="••••••••••••" required>
|
||||
</div>
|
||||
|
||||
<button type="submit" class="btn btn-primary" style="width: 100%; justify-content: center; margin-top: 8px; padding: 12px;">
|
||||
Sign In
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const form = document.getElementById('login-form');
|
||||
const errorAlert = document.getElementById('error-alert');
|
||||
|
||||
form.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
errorAlert.style.display = 'none';
|
||||
|
||||
const username = document.getElementById('username').value.trim();
|
||||
const password = document.getElementById('password').value;
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username, password })
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
errorAlert.textContent = data.error || 'Login failed';
|
||||
errorAlert.style.display = 'block';
|
||||
} else {
|
||||
window.location.href = '/';
|
||||
}
|
||||
} catch (err) {
|
||||
errorAlert.textContent = 'Server connection error';
|
||||
errorAlert.style.display = 'block';
|
||||
}
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
524
portal/server.js
Normal file
524
portal/server.js
Normal file
|
|
@ -0,0 +1,524 @@
|
|||
const express = require('express');
|
||||
const cookieParser = require('cookie-parser');
|
||||
const jwt = require('jsonwebtoken');
|
||||
const crypto = require('crypto');
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const http = require('http');
|
||||
const https = require('https');
|
||||
const { Pool } = require('pg');
|
||||
const multer = require('multer');
|
||||
const { S3Client, PutObjectCommand, GetObjectCommand, ListObjectsV2Command } = require('@aws-sdk/client-s3');
|
||||
const { getSignedUrl } = require('@aws-sdk/s3-request-presigner');
|
||||
|
||||
const app = express();
|
||||
const PORT = process.env.PORT || 8084;
|
||||
const JWT_SECRET = process.env.JWT_SECRET || 'vignesh_onlyoffice_secret_key_2026';
|
||||
const DOCSERVER_PUBLIC_URL = process.env.DOCSERVER_PUBLIC_URL || 'https://documents.tradhox.com';
|
||||
const S3_BUCKET = process.env.AWS_S3_BUCKET || 'trypostmedia';
|
||||
const S3_PREFIX = process.env.AWS_S3_PREFIX || 'documents/';
|
||||
const S3_REGION = process.env.AWS_REGION || 'ap-south-2';
|
||||
|
||||
// PostgreSQL Pool
|
||||
const pool = new Pool({
|
||||
host: process.env.PGHOST || 'host.docker.internal',
|
||||
port: parseInt(process.env.PGPORT || '5432', 10),
|
||||
database: process.env.PGDATABASE || 'onlyoffice',
|
||||
user: process.env.PGUSER || 'vignesh',
|
||||
password: process.env.PGPASSWORD || 'vtechnosoft@123A',
|
||||
max: 10,
|
||||
idleTimeoutMillis: 30000,
|
||||
});
|
||||
|
||||
// S3 Client (IAM Role authentication automatically via AWS SDK v3)
|
||||
const s3 = new S3Client({ region: S3_REGION });
|
||||
|
||||
// Password hashing helpers
|
||||
function hashPassword(password) {
|
||||
const salt = crypto.randomBytes(16).toString('hex');
|
||||
const hash = crypto.pbkdf2Sync(password, salt, 100000, 64, 'sha512').toString('hex');
|
||||
return `${salt}:${hash}`;
|
||||
}
|
||||
|
||||
function verifyPassword(password, stored) {
|
||||
if (!stored || !stored.includes(':')) return false;
|
||||
const [salt, originalHash] = stored.split(':');
|
||||
const hash = crypto.pbkdf2Sync(password, salt, 100000, 64, 'sha512').toString('hex');
|
||||
return hash === originalHash;
|
||||
}
|
||||
|
||||
// Audit Logger
|
||||
async function auditLog(req, username, action, target, details) {
|
||||
const ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress || 'unknown';
|
||||
try {
|
||||
await pool.query(
|
||||
'INSERT INTO app_audit_logs (username, action, target, details, ip_address) VALUES ($1, $2, $3, $4, $5)',
|
||||
[username || 'anonymous', action, target || '', details || '', ip.toString().split(',')[0].trim()]
|
||||
);
|
||||
} catch (err) {
|
||||
console.error('Failed to write audit log:', err.message);
|
||||
}
|
||||
}
|
||||
|
||||
// Middlewares
|
||||
app.use(express.json({ limit: '100mb' }));
|
||||
app.use(express.urlencoded({ extended: true, limit: '100mb' }));
|
||||
app.use(cookieParser());
|
||||
app.use(express.static(path.join(__dirname, 'public')));
|
||||
|
||||
// Upload setup (memory storage)
|
||||
const upload = multer({ limits: { fileSize: 100 * 1024 * 1024 } });
|
||||
|
||||
// Auth Middleware
|
||||
function authMiddleware(req, res, next) {
|
||||
const token = req.cookies.auth_token;
|
||||
if (!token) {
|
||||
if (req.path.startsWith('/api/')) {
|
||||
return res.status(401).json({ error: 'Authentication required' });
|
||||
}
|
||||
return res.redirect('/login');
|
||||
}
|
||||
|
||||
try {
|
||||
const decoded = jwt.verify(token, JWT_SECRET);
|
||||
req.user = decoded;
|
||||
next();
|
||||
} catch (err) {
|
||||
res.clearCookie('auth_token');
|
||||
if (req.path.startsWith('/api/')) {
|
||||
return res.status(401).json({ error: 'Invalid or expired session' });
|
||||
}
|
||||
return res.redirect('/login');
|
||||
}
|
||||
}
|
||||
|
||||
function requireAdmin(req, res, next) {
|
||||
if (!req.user || req.user.role !== 'admin') {
|
||||
return res.status(403).json({ error: 'Access denied: Admin role required' });
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
// Page Routes
|
||||
app.get('/login', (req, res) => {
|
||||
res.sendFile(path.join(__dirname, 'public', 'login.html'));
|
||||
});
|
||||
|
||||
app.get('/', authMiddleware, (req, res) => {
|
||||
res.sendFile(path.join(__dirname, 'public', 'index.html'));
|
||||
});
|
||||
|
||||
app.get('/editor', authMiddleware, (req, res) => {
|
||||
res.sendFile(path.join(__dirname, 'public', 'editor.html'));
|
||||
});
|
||||
|
||||
app.get('/admin', authMiddleware, (req, res) => {
|
||||
if (req.user.role !== 'admin') {
|
||||
return res.redirect('/');
|
||||
}
|
||||
res.sendFile(path.join(__dirname, 'public', 'admin.html'));
|
||||
});
|
||||
|
||||
// Authentication APIs
|
||||
app.post('/api/login', async (req, res) => {
|
||||
const { username, password } = req.body;
|
||||
if (!username || !password) {
|
||||
return res.status(400).json({ error: 'Username and password are required' });
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await pool.query('SELECT * FROM app_users WHERE username = $1', [username.toLowerCase().trim()]);
|
||||
if (result.rows.length === 0) {
|
||||
await auditLog(req, username, 'LOGIN_FAILED', username, 'User not found');
|
||||
return res.status(401).json({ error: 'Invalid username or password' });
|
||||
}
|
||||
|
||||
const user = result.rows[0];
|
||||
if (!verifyPassword(password, user.password_hash)) {
|
||||
await auditLog(req, username, 'LOGIN_FAILED', username, 'Incorrect password');
|
||||
return res.status(401).json({ error: 'Invalid username or password' });
|
||||
}
|
||||
|
||||
const token = jwt.sign(
|
||||
{ id: user.id, username: user.username, displayName: user.display_name, role: user.role },
|
||||
JWT_SECRET,
|
||||
{ expiresIn: '7d' }
|
||||
);
|
||||
|
||||
res.cookie('auth_token', token, {
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
sameSite: 'lax',
|
||||
maxAge: 7 * 24 * 60 * 60 * 1000,
|
||||
});
|
||||
|
||||
await auditLog(req, user.username, 'LOGIN_SUCCESS', user.username, `Successful login (${user.role})`);
|
||||
res.json({ success: true, user: { username: user.username, displayName: user.display_name, role: user.role } });
|
||||
} catch (err) {
|
||||
console.error('Login error:', err);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/logout', authMiddleware, async (req, res) => {
|
||||
await auditLog(req, req.user.username, 'LOGOUT', req.user.username, 'User logged out');
|
||||
res.clearCookie('auth_token');
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
app.get('/api/me', authMiddleware, (req, res) => {
|
||||
res.json({ user: req.user });
|
||||
});
|
||||
|
||||
// Document APIs
|
||||
app.get('/api/documents', authMiddleware, async (req, res) => {
|
||||
try {
|
||||
const result = await pool.query('SELECT * FROM app_documents ORDER BY updated_at DESC');
|
||||
res.json({ documents: result.rows });
|
||||
} catch (err) {
|
||||
console.error('Fetch docs error:', err);
|
||||
res.status(500).json({ error: 'Failed to fetch documents' });
|
||||
}
|
||||
});
|
||||
|
||||
// Create new blank document
|
||||
app.post('/api/documents/create', authMiddleware, async (req, res) => {
|
||||
const { filename, fileType } = req.body;
|
||||
if (!filename || !fileType) {
|
||||
return res.status(400).json({ error: 'Filename and fileType are required' });
|
||||
}
|
||||
|
||||
const ext = fileType.toLowerCase();
|
||||
const validExts = ['docx', 'xlsx', 'pptx'];
|
||||
if (!validExts.includes(ext)) {
|
||||
return res.status(400).json({ error: 'Invalid file type. Supported: docx, xlsx, pptx' });
|
||||
}
|
||||
|
||||
let finalName = filename.endsWith(`.${ext}`) ? filename : `${filename}.${ext}`;
|
||||
finalName = finalName.replace(/[^a-zA-Z0-9._-]/g, '_');
|
||||
const s3Key = `${S3_PREFIX}${finalName}`;
|
||||
|
||||
try {
|
||||
// Generate minimal valid OOXML empty zip structure or fetch template
|
||||
const templatePath = path.join(__dirname, 'templates', `new.${ext}`);
|
||||
let buffer;
|
||||
if (fs.existsSync(templatePath)) {
|
||||
buffer = fs.readFileSync(templatePath);
|
||||
} else {
|
||||
buffer = Buffer.from(''); // fallback
|
||||
}
|
||||
|
||||
await s3.send(new PutObjectCommand({
|
||||
Bucket: S3_BUCKET,
|
||||
Key: s3Key,
|
||||
Body: buffer,
|
||||
ContentType: getMimeType(ext),
|
||||
}));
|
||||
|
||||
await pool.query(
|
||||
`INSERT INTO app_documents (filename, s3_key, file_type, created_by, updated_at)
|
||||
VALUES ($1, $2, $3, $4, CURRENT_TIMESTAMP)
|
||||
ON CONFLICT (filename) DO UPDATE SET updated_at = CURRENT_TIMESTAMP`,
|
||||
[finalName, s3Key, ext, req.user.username]
|
||||
);
|
||||
|
||||
await auditLog(req, req.user.username, 'DOCUMENT_CREATED', finalName, `Created blank ${ext.toUpperCase()} document`);
|
||||
res.json({ success: true, filename: finalName });
|
||||
} catch (err) {
|
||||
console.error('Create document error:', err);
|
||||
res.status(500).json({ error: 'Failed to create document: ' + err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Upload document
|
||||
app.post('/api/documents/upload', authMiddleware, upload.single('file'), async (req, res) => {
|
||||
if (!req.file) {
|
||||
return res.status(400).json({ error: 'No file uploaded' });
|
||||
}
|
||||
|
||||
let filename = req.file.originalname.replace(/[^a-zA-Z0-9._-]/g, '_');
|
||||
const ext = path.extname(filename).replace('.', '').toLowerCase();
|
||||
const s3Key = `${S3_PREFIX}${filename}`;
|
||||
|
||||
try {
|
||||
await s3.send(new PutObjectCommand({
|
||||
Bucket: S3_BUCKET,
|
||||
Key: s3Key,
|
||||
Body: req.file.buffer,
|
||||
ContentType: req.file.mimetype || getMimeType(ext),
|
||||
}));
|
||||
|
||||
await pool.query(
|
||||
`INSERT INTO app_documents (filename, s3_key, file_type, created_by, updated_at)
|
||||
VALUES ($1, $2, $3, $4, CURRENT_TIMESTAMP)
|
||||
ON CONFLICT (filename) DO UPDATE SET updated_at = CURRENT_TIMESTAMP`,
|
||||
[filename, s3Key, ext, req.user.username]
|
||||
);
|
||||
|
||||
await auditLog(req, req.user.username, 'DOCUMENT_UPLOADED', filename, `Uploaded ${filename} (${req.file.size} bytes)`);
|
||||
res.json({ success: true, filename });
|
||||
} catch (err) {
|
||||
console.error('Upload error:', err);
|
||||
res.status(500).json({ error: 'Failed to upload document' });
|
||||
}
|
||||
});
|
||||
|
||||
// Download / Stream document
|
||||
app.get('/api/documents/download/:filename', async (req, res) => {
|
||||
const { filename } = req.params;
|
||||
const s3Key = `${S3_PREFIX}${filename}`;
|
||||
|
||||
try {
|
||||
const s3Res = await s3.send(new GetObjectCommand({
|
||||
Bucket: S3_BUCKET,
|
||||
Key: s3Key,
|
||||
}));
|
||||
|
||||
const ext = path.extname(filename).replace('.', '').toLowerCase();
|
||||
res.setHeader('Content-Type', getMimeType(ext));
|
||||
res.setHeader('Content-Disposition', `inline; filename="${filename}"`);
|
||||
s3Res.Body.pipe(res);
|
||||
} catch (err) {
|
||||
console.error('Download error:', err);
|
||||
res.status(404).send('Document not found in S3');
|
||||
}
|
||||
});
|
||||
|
||||
// Get ONLYOFFICE editor configuration for logged-in user
|
||||
app.get('/api/editor/config/:filename', authMiddleware, async (req, res) => {
|
||||
const { filename } = req.params;
|
||||
const docResult = await pool.query('SELECT * FROM app_documents WHERE filename = $1', [filename]);
|
||||
if (docResult.rows.length === 0) {
|
||||
return res.status(404).json({ error: 'Document not found' });
|
||||
}
|
||||
|
||||
const doc = docResult.rows[0];
|
||||
const ext = doc.file_type.toLowerCase();
|
||||
const documentType = getDocumentType(ext);
|
||||
|
||||
// Generate deterministic key for collaboration session based on filename + last updated
|
||||
const docKey = crypto.createHash('sha256')
|
||||
.update(`${doc.filename}_${doc.updated_at.getTime()}`)
|
||||
.digest('hex')
|
||||
.substring(0, 20);
|
||||
|
||||
const docUrl = `${DOCSERVER_PUBLIC_URL}/api/documents/download/${encodeURIComponent(filename)}`;
|
||||
const callbackUrl = `${DOCSERVER_PUBLIC_URL}/api/callback?file=${encodeURIComponent(filename)}&user=${encodeURIComponent(req.user.username)}`;
|
||||
|
||||
const config = {
|
||||
document: {
|
||||
fileType: ext,
|
||||
key: docKey,
|
||||
title: filename,
|
||||
url: docUrl,
|
||||
permissions: {
|
||||
comment: true,
|
||||
download: true,
|
||||
edit: true,
|
||||
fillForms: true,
|
||||
modifyContentControl: true,
|
||||
modifyFilter: true,
|
||||
print: true,
|
||||
review: true,
|
||||
},
|
||||
},
|
||||
documentType: documentType,
|
||||
editorConfig: {
|
||||
actionLink: null,
|
||||
mode: 'edit',
|
||||
lang: 'en',
|
||||
coEditing: {
|
||||
mode: 'fast',
|
||||
change: true,
|
||||
},
|
||||
user: {
|
||||
id: req.user.username,
|
||||
name: req.user.displayName,
|
||||
},
|
||||
customization: {
|
||||
autosave: true,
|
||||
chat: true,
|
||||
comments: true,
|
||||
forcesave: true,
|
||||
zoom: 100,
|
||||
compactHeader: false,
|
||||
toolbarNoTabs: false,
|
||||
feedback: false,
|
||||
},
|
||||
callbackUrl: callbackUrl,
|
||||
},
|
||||
};
|
||||
|
||||
// Sign ONLYOFFICE config with JWT
|
||||
config.token = jwt.sign(config, JWT_SECRET, { expiresIn: '12h' });
|
||||
|
||||
await auditLog(req, req.user.username, 'DOCUMENT_OPENED', filename, `Opened ${filename} in ONLYOFFICE editor`);
|
||||
res.json({ config, docserverUrl: `${DOCSERVER_PUBLIC_URL}/web-apps/apps/api/documents/api.js` });
|
||||
});
|
||||
|
||||
// ONLYOFFICE Document Server Callback Handler
|
||||
app.post('/api/callback', async (req, res) => {
|
||||
const filename = req.query.file;
|
||||
const initiatingUser = req.query.user || 'system';
|
||||
const { status, url, users, changesurl } = req.body;
|
||||
|
||||
console.log(`[ONLYOFFICE Callback] File: ${filename}, Status: ${status}, Users:`, users);
|
||||
|
||||
// Status 2 = document ready for saving, Status 6 = forcesave document
|
||||
if (status === 2 || status === 6) {
|
||||
if (url) {
|
||||
try {
|
||||
const fileBuffer = await downloadFile(url);
|
||||
const s3Key = `${S3_PREFIX}${filename}`;
|
||||
|
||||
await s3.send(new PutObjectCommand({
|
||||
Bucket: S3_BUCKET,
|
||||
Key: s3Key,
|
||||
Body: fileBuffer,
|
||||
ContentType: getMimeType(path.extname(filename).replace('.', '')),
|
||||
}));
|
||||
|
||||
await pool.query(
|
||||
'UPDATE app_documents SET updated_at = CURRENT_TIMESTAMP WHERE filename = $1',
|
||||
[filename]
|
||||
);
|
||||
|
||||
const editingUsers = users && users.length > 0 ? users.join(', ') : initiatingUser;
|
||||
await auditLog(
|
||||
req,
|
||||
editingUsers,
|
||||
'DOCUMENT_SAVED',
|
||||
filename,
|
||||
`Saved edited version to S3 (collaborators: ${editingUsers})`
|
||||
);
|
||||
} catch (err) {
|
||||
console.error('Failed to save document from ONLYOFFICE callback:', err);
|
||||
return res.json({ error: 1 });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
res.json({ error: 0 });
|
||||
});
|
||||
|
||||
// Admin User Management APIs
|
||||
app.get('/api/admin/users', authMiddleware, requireAdmin, async (req, res) => {
|
||||
try {
|
||||
const result = await pool.query(
|
||||
'SELECT id, username, display_name, role, created_at FROM app_users ORDER BY id ASC'
|
||||
);
|
||||
res.json({ users: result.rows });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: 'Failed to fetch users' });
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/admin/users', authMiddleware, requireAdmin, async (req, res) => {
|
||||
const { username, displayName, password, role } = req.body;
|
||||
if (!username || !displayName || !password) {
|
||||
return res.status(400).json({ error: 'Username, display name, and password are required' });
|
||||
}
|
||||
|
||||
const cleanUser = username.toLowerCase().trim();
|
||||
const userRole = role === 'admin' ? 'admin' : 'user';
|
||||
|
||||
try {
|
||||
const check = await pool.query('SELECT id FROM app_users WHERE username = $1', [cleanUser]);
|
||||
if (check.rows.length > 0) {
|
||||
return res.status(400).json({ error: 'User already exists' });
|
||||
}
|
||||
|
||||
const hashed = hashPassword(password);
|
||||
await pool.query(
|
||||
'INSERT INTO app_users (username, display_name, password_hash, role) VALUES ($1, $2, $3, $4)',
|
||||
[cleanUser, displayName.trim(), hashed, userRole]
|
||||
);
|
||||
|
||||
await auditLog(req, req.user.username, 'USER_CREATED', cleanUser, `Created new user ${cleanUser} (${userRole})`);
|
||||
res.json({ success: true });
|
||||
} catch (err) {
|
||||
console.error('Create user error:', err);
|
||||
res.status(500).json({ error: 'Failed to create user' });
|
||||
}
|
||||
});
|
||||
|
||||
app.delete('/api/admin/users/:username', authMiddleware, requireAdmin, async (req, res) => {
|
||||
const targetUser = req.params.username.toLowerCase();
|
||||
if (targetUser === 'vignesh' || targetUser === req.user.username) {
|
||||
return res.status(400).json({ error: 'Cannot delete primary admin or current logged in user' });
|
||||
}
|
||||
|
||||
try {
|
||||
await pool.query('DELETE FROM app_users WHERE username = $1', [targetUser]);
|
||||
await auditLog(req, req.user.username, 'USER_DELETED', targetUser, `Deleted user ${targetUser}`);
|
||||
res.json({ success: true });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: 'Failed to delete user' });
|
||||
}
|
||||
});
|
||||
|
||||
// Admin Audit Logs API
|
||||
app.get('/api/admin/audit-logs', authMiddleware, requireAdmin, async (req, res) => {
|
||||
const limit = Math.min(parseInt(req.query.limit || '100', 10), 500);
|
||||
const search = req.query.search ? `%${req.query.search}%` : null;
|
||||
|
||||
try {
|
||||
let query = 'SELECT * FROM app_audit_logs ';
|
||||
const params = [];
|
||||
|
||||
if (search) {
|
||||
query += 'WHERE username ILIKE $1 OR action ILIKE $1 OR target ILIKE $1 OR details ILIKE $1 ';
|
||||
params.push(search);
|
||||
}
|
||||
|
||||
query += `ORDER BY created_at DESC LIMIT $${params.length + 1}`;
|
||||
params.push(limit);
|
||||
|
||||
const result = await pool.query(query, params);
|
||||
res.json({ logs: result.rows });
|
||||
} catch (err) {
|
||||
console.error('Audit log fetch error:', err);
|
||||
res.status(500).json({ error: 'Failed to fetch audit logs' });
|
||||
}
|
||||
});
|
||||
|
||||
// Helper utilities
|
||||
function getMimeType(ext) {
|
||||
const types = {
|
||||
docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
||||
pdf: 'application/pdf',
|
||||
txt: 'text/plain',
|
||||
};
|
||||
return types[ext] || 'application/octet-stream';
|
||||
}
|
||||
|
||||
function getDocumentType(ext) {
|
||||
if (['doc', 'docx', 'rtf', 'txt', 'odt'].includes(ext)) return 'word';
|
||||
if (['xls', 'xlsx', 'csv', 'ods'].includes(ext)) return 'cell';
|
||||
if (['ppt', 'pptx', 'odp'].includes(ext)) return 'slide';
|
||||
return 'word';
|
||||
}
|
||||
|
||||
function downloadFile(fileUrl) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const protocol = fileUrl.startsWith('https') ? https : http;
|
||||
protocol.get(fileUrl, (res) => {
|
||||
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
|
||||
return resolve(downloadFile(res.headers.location));
|
||||
}
|
||||
if (res.statusCode !== 200) {
|
||||
return reject(new Error(`Failed to download file, status: ${res.statusCode}`));
|
||||
}
|
||||
const data = [];
|
||||
res.on('data', chunk => data.push(chunk));
|
||||
res.on('end', () => resolve(Buffer.concat(data)));
|
||||
}).on('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
// Start Server
|
||||
app.listen(PORT, '0.0.0.0', () => {
|
||||
console.log(`Document Management Portal running on http://0.0.0.0:${PORT}`);
|
||||
});
|
||||
BIN
portal/templates/new.docx
Normal file
BIN
portal/templates/new.docx
Normal file
Binary file not shown.
BIN
portal/templates/new.pptx
Normal file
BIN
portal/templates/new.pptx
Normal file
Binary file not shown.
BIN
portal/templates/new.xlsx
Normal file
BIN
portal/templates/new.xlsx
Normal file
Binary file not shown.
Loading…
Reference in a new issue