chore: replace hand-rolled layout() with @fastify/view + EJS
Convert all src/views/*.ts template-literal modules to .ejs templates under views/. Register @fastify/view plugin in server.ts with EJS engine and _layout.ejs as the layout file. Update route handlers to use reply.view() instead of reply.send(layout(...)). Delete the old TypeScript view modules and layout.ts. Closes #19
This commit is contained in:
@@ -7,16 +7,17 @@ import type { Config } from '../config.ts';
|
||||
import type { Logger } from '../middleware/logging.ts';
|
||||
import type { JwtPayload } from '../types.ts';
|
||||
import type { LockoutService } from '../services/lockout.ts';
|
||||
import { createFile, getFileById, getFilesByUserId, deleteFile } from '../db/files.ts';
|
||||
import { createFile, getFileById, getFilesByUserId, deleteFile, type FileRow } from '../db/files.ts';
|
||||
import { saveFile, deleteStoredFile, getFilePath } from '../services/storage.ts';
|
||||
import { attemptLogin } from '../services/login-handler.ts';
|
||||
import { makeRequireAuth, issueSessionCookie } from '../middleware/auth.ts';
|
||||
import { SESSION_COOKIE_NAME } from '../constants.ts';
|
||||
import { loginPage } from '../views/login.ts';
|
||||
import { uploadPage, uploadResultPage } from '../views/upload.ts';
|
||||
import { fileListPage } from '../views/file-list.ts';
|
||||
import { fileViewPage } from '../views/file-view.ts';
|
||||
import { notFoundPage } from '../views/not-found.ts';
|
||||
|
||||
function formatBytes(bytes: number): string {
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
||||
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
||||
}
|
||||
|
||||
interface Deps {
|
||||
db: Database.Database;
|
||||
@@ -65,7 +66,7 @@ export const pageRoutes: FastifyPluginAsync<{ deps: Deps }> = async (app, { deps
|
||||
await request.jwtVerify();
|
||||
return reply.redirect('/upload');
|
||||
} catch {
|
||||
return reply.type('text/html').send(loginPage());
|
||||
return reply.view('login.ejs', { title: 'Login', error: null });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -85,13 +86,12 @@ export const pageRoutes: FastifyPluginAsync<{ deps: Deps }> = async (app, { deps
|
||||
|
||||
if (result.kind === 'locked') {
|
||||
return reply
|
||||
.type('text/html')
|
||||
.header('Retry-After', String(result.retryAfterSeconds))
|
||||
.send(loginPage({ error: 'Invalid username or password' }));
|
||||
.view('login.ejs', { title: 'Login', error: 'Invalid username or password' });
|
||||
}
|
||||
|
||||
if (result.kind !== 'success') {
|
||||
return reply.type('text/html').send(loginPage({ error: 'Invalid username or password' }));
|
||||
return reply.view('login.ejs', { title: 'Login', error: 'Invalid username or password' });
|
||||
}
|
||||
|
||||
issueSessionCookie(
|
||||
@@ -111,7 +111,7 @@ export const pageRoutes: FastifyPluginAsync<{ deps: Deps }> = async (app, { deps
|
||||
|
||||
// GET /upload
|
||||
app.get('/upload', { preHandler: requireAuth }, async (_request, reply) => {
|
||||
reply.type('text/html').send(uploadPage());
|
||||
return reply.view('upload.ejs', { title: 'Upload', authed: true, error: null });
|
||||
});
|
||||
|
||||
// POST /upload
|
||||
@@ -120,7 +120,7 @@ export const pageRoutes: FastifyPluginAsync<{ deps: Deps }> = async (app, { deps
|
||||
|
||||
const data = await request.file();
|
||||
if (!data) {
|
||||
return reply.type('text/html').send(uploadPage({ error: 'No file selected' }));
|
||||
return reply.view('upload.ejs', { title: 'Upload', authed: true, error: 'No file selected' });
|
||||
}
|
||||
|
||||
const fileBuffer = await data.toBuffer();
|
||||
@@ -141,14 +141,15 @@ export const pageRoutes: FastifyPluginAsync<{ deps: Deps }> = async (app, { deps
|
||||
});
|
||||
|
||||
const shareUrl = `${config.baseUrl}/f/${id}`;
|
||||
reply.type('text/html').send(uploadResultPage(shareUrl, data.filename));
|
||||
return reply.view('upload-result.ejs', { title: 'File uploaded', authed: true, shareUrl, filename: data.filename });
|
||||
});
|
||||
|
||||
// GET /files
|
||||
app.get('/files', { preHandler: requireAuth }, async (request, reply) => {
|
||||
const { sub: userId } = request.user as JwtPayload;
|
||||
const files = getFilesByUserId(db, userId);
|
||||
reply.type('text/html').send(fileListPage(files, config.baseUrl));
|
||||
const filesWithSize = files.map((f: FileRow) => ({ ...f, sizeFormatted: formatBytes(f.size) }));
|
||||
return reply.view('file-list.ejs', { title: 'My files', authed: true, files: filesWithSize, baseUrl: config.baseUrl });
|
||||
});
|
||||
|
||||
// POST /files/:id/delete
|
||||
@@ -182,11 +183,17 @@ export const pageRoutes: FastifyPluginAsync<{ deps: Deps }> = async (app, { deps
|
||||
|
||||
if (!file) {
|
||||
await logger.fileNotFound({ ip: request.ip, userAgent: request.headers['user-agent'] ?? '', fileId: id });
|
||||
return reply.status(404).type('text/html').send(notFoundPage());
|
||||
return reply.status(404).view('not-found.ejs', { title: 'Not found' });
|
||||
}
|
||||
|
||||
const isOwner = userId !== null && userId === file.user_id;
|
||||
reply.type('text/html').send(fileViewPage(file, isOwner));
|
||||
return reply.view('file-view.ejs', {
|
||||
title: file.original_name,
|
||||
authed: isOwner,
|
||||
hideHeader: !isOwner,
|
||||
file,
|
||||
isOwner,
|
||||
});
|
||||
});
|
||||
|
||||
// GET /f/:id/raw — serve raw file with range request support
|
||||
@@ -235,6 +242,6 @@ export const pageRoutes: FastifyPluginAsync<{ deps: Deps }> = async (app, { deps
|
||||
|
||||
// 404 handler
|
||||
app.setNotFoundHandler((_request, reply) => {
|
||||
reply.status(404).type('text/html').send(notFoundPage());
|
||||
return reply.status(404).view('not-found.ejs', { title: 'Not found' });
|
||||
});
|
||||
};
|
||||
|
||||
@@ -5,6 +5,8 @@ import fastifyMultipart from '@fastify/multipart';
|
||||
import fastifyFormbody from '@fastify/formbody';
|
||||
import fastifyStatic from '@fastify/static';
|
||||
import fastifyRateLimit from '@fastify/rate-limit';
|
||||
import fastifyView from '@fastify/view';
|
||||
import ejs from 'ejs';
|
||||
import { join } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import type Database from 'better-sqlite3';
|
||||
@@ -39,6 +41,12 @@ export function createServer({ config, db }: ServerDeps) {
|
||||
root: join(__dirname, '..', 'public'),
|
||||
prefix: '/public/',
|
||||
});
|
||||
app.register(fastifyView, {
|
||||
engine: { ejs },
|
||||
root: join(__dirname, '..', 'views'),
|
||||
layout: '_layout.ejs',
|
||||
defaultContext: { authed: false, hideHeader: false },
|
||||
});
|
||||
app.register(fastifyRateLimit, {
|
||||
global: false,
|
||||
keyGenerator: (req) => req.ip,
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
import { layout, escHtml } from './layout.ts';
|
||||
import type { FileRow } from '../db/files.ts';
|
||||
|
||||
export function fileListPage(files: FileRow[], baseUrl: string): string {
|
||||
const rows = files.length === 0
|
||||
? '<tr><td colspan="5">No files yet. <a href="/upload">Upload one.</a></td></tr>'
|
||||
: files.map((f) => {
|
||||
const shareUrl = `${baseUrl}/f/${escHtml(f.id)}`;
|
||||
return `
|
||||
<tr>
|
||||
<td><a href="/f/${escHtml(f.id)}">${escHtml(f.original_name)}</a></td>
|
||||
<td>${escHtml(f.mime_type)}</td>
|
||||
<td>${formatBytes(f.size)}</td>
|
||||
<td>${escHtml(f.created_at)}</td>
|
||||
<td>
|
||||
<button class="copy-link" onclick="navigator.clipboard.writeText('${shareUrl}')">Copy link</button>
|
||||
<form method="POST" action="/files/${escHtml(f.id)}/delete" style="display:inline">
|
||||
<button type="submit" class="danger">Delete</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>`;
|
||||
}).join('');
|
||||
|
||||
return layout('My files', `
|
||||
<h1>My files</h1>
|
||||
<p><a href="/upload">Upload new file</a></p>
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Name</th><th>Type</th><th>Size</th><th>Uploaded</th><th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>${rows}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
`, { authed: true });
|
||||
}
|
||||
|
||||
function formatBytes(bytes: number): string {
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
||||
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
import { layout, escHtml } from './layout.ts';
|
||||
import type { FileRow } from '../db/files.ts';
|
||||
|
||||
export function fileViewPage(file: FileRow, isOwner: boolean): string {
|
||||
const rawUrl = escHtml(`/f/${file.id}/raw`);
|
||||
const safeName = escHtml(file.original_name);
|
||||
const actions = `
|
||||
<div class="file-actions">
|
||||
<a href="${rawUrl}" download="${safeName}" class="btn">Download</a>
|
||||
<a href="${rawUrl}" target="_blank" class="btn">Open</a>
|
||||
</div>`;
|
||||
|
||||
const deleteForm = isOwner
|
||||
? `<form method="POST" action="/files/${escHtml(file.id)}/delete">
|
||||
<button type="submit" class="danger">Delete</button>
|
||||
</form>`
|
||||
: '';
|
||||
|
||||
let media = '';
|
||||
if (file.mime_type.startsWith('image/')) {
|
||||
media = `<img src="${rawUrl}" alt="${safeName}">`;
|
||||
} else if (file.mime_type.startsWith('video/')) {
|
||||
media = `<video controls src="${rawUrl}" preload="metadata"></video>`;
|
||||
} else if (file.mime_type.startsWith('audio/')) {
|
||||
media = `<audio controls src="${rawUrl}" preload="metadata"></audio>`;
|
||||
}
|
||||
|
||||
const layoutOpts = isOwner ? { authed: true } : { hideHeader: true };
|
||||
|
||||
return layout(file.original_name, `
|
||||
<div class="file-view">
|
||||
<h1>${safeName}</h1>
|
||||
${media}
|
||||
${actions}
|
||||
${deleteForm}
|
||||
</div>
|
||||
`, layoutOpts);
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
export function layout(title: string, body: string, opts: { authed?: boolean; hideHeader?: boolean } = {}): string {
|
||||
const { authed = false, hideHeader = false } = opts;
|
||||
const nav = authed
|
||||
? `<nav>
|
||||
<a href="/upload">Upload</a>
|
||||
<a href="/files">My Files</a>
|
||||
<form method="POST" action="/logout" style="display:inline">
|
||||
<button type="submit">Logout</button>
|
||||
</form>
|
||||
</nav>`
|
||||
: '';
|
||||
|
||||
const header = hideHeader
|
||||
? ''
|
||||
: ` <header>
|
||||
<a href="/" class="logo">Nanodrop</a>
|
||||
${nav}
|
||||
</header>`;
|
||||
|
||||
return `<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta name="color-scheme" content="light dark">
|
||||
<title>${escHtml(title)} — Nanodrop</title>
|
||||
<link rel="stylesheet" href="/public/style.css">
|
||||
</head>
|
||||
<body>
|
||||
${header}
|
||||
<main>
|
||||
${body}
|
||||
</main>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
|
||||
export function escHtml(str: string): string {
|
||||
return str
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
import { layout } from './layout.ts';
|
||||
|
||||
export function loginPage(opts: { error?: string } = {}): string {
|
||||
const errorHtml = opts.error
|
||||
? `<p class="error">${opts.error}</p>`
|
||||
: '';
|
||||
|
||||
return layout('Login', `
|
||||
<div class="form-container">
|
||||
<h1>Sign in</h1>
|
||||
${errorHtml}
|
||||
<form method="POST" action="/login">
|
||||
<label>
|
||||
Username
|
||||
<input type="text" name="username" required autofocus>
|
||||
</label>
|
||||
<label>
|
||||
Password
|
||||
<input type="password" name="password" required>
|
||||
</label>
|
||||
<button type="submit">Login</button>
|
||||
</form>
|
||||
</div>
|
||||
`);
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
import { layout } from './layout.ts';
|
||||
|
||||
export function notFoundPage(): string {
|
||||
return layout('Not found', `
|
||||
<div class="form-container">
|
||||
<h1>404 — Not found</h1>
|
||||
<p>The page or file you requested does not exist.</p>
|
||||
<p><a href="/">Go home</a></p>
|
||||
</div>
|
||||
`);
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
import { layout, escHtml } from './layout.ts';
|
||||
|
||||
export function uploadPage(opts: { error?: string } = {}): string {
|
||||
const errorHtml = opts.error ? `<p class="error">${opts.error}</p>` : '';
|
||||
|
||||
return layout('Upload', `
|
||||
<div class="form-container">
|
||||
<h1>Upload a file</h1>
|
||||
${errorHtml}
|
||||
<form method="POST" action="/upload" enctype="multipart/form-data">
|
||||
<label>
|
||||
File
|
||||
<input type="file" name="file" required>
|
||||
</label>
|
||||
<button type="submit">Upload</button>
|
||||
</form>
|
||||
</div>
|
||||
`, { authed: true });
|
||||
}
|
||||
|
||||
export function uploadResultPage(shareUrl: string, filename: string): string {
|
||||
const safeUrl = escHtml(shareUrl);
|
||||
const safeName = escHtml(filename);
|
||||
|
||||
return layout('File uploaded', `
|
||||
<div class="form-container">
|
||||
<h1>File uploaded</h1>
|
||||
<p><strong>${safeName}</strong> is ready to share.</p>
|
||||
<div class="share-box">
|
||||
<input type="text" id="share-url" value="${safeUrl}" readonly>
|
||||
<button onclick="navigator.clipboard.writeText(document.getElementById('share-url').value)">Copy link</button>
|
||||
</div>
|
||||
<p><a href="/upload">Upload another</a> · <a href="/files">My files</a></p>
|
||||
</div>
|
||||
`, { authed: true });
|
||||
}
|
||||
Reference in New Issue
Block a user