feat: public v1 API + token management + OpenAPI docs (#322)
Adds a long-lived bearer-token mechanism + scoped REST surface designed
for n8n-style automation: create a gallery, upload photos, fetch the
share URL — all via documented HTTPS endpoints instead of poking at the
admin UI's internal routes.
API
- Migration 081 adds `api_tokens` (hashed_token, scopes, owner FK,
last_used/expires/revoked timestamps).
- New apiTokenAuth middleware: parses `Authorization: Bearer pp_live_…`,
resolves to the owner admin user, attaches `req.admin` so existing
permission decorators (events.create etc.) still work. Token-level
scope check (read/write/admin) layers on top as defence in depth —
a leaked read-only token cannot mutate even if its owner is super_admin.
- adminApiTokens route exposes list/create/revoke for admins (cookie-
authed). Plaintext token is returned exactly once on creation.
- v1 surface mounted at /api/v1: POST/GET /events, GET /events/:id,
POST /events/:id/photos (multipart, single file), GET
/events/:id/share-link. Each endpoint annotated with @openapi JSDoc.
Documentation
- swagger-jsdoc + swagger-ui-express produce a live spec at
/api/openapi.json and a Swagger UI at /api/docs (admin-gated).
- backend/scripts/generate-openapi.js writes docs/openapi.{json,yaml}
to the repo so the spec is versioned.
- scripts/sync-api-docs.sh runs in pre-push: regenerates the spec and
copies it into the picpeak-docs Nextra site at app/api/. Writes only,
never commits or pushes the docs repo (PUSH_SKIP_DOCS=1 to bypass).
Frontend
- New Settings → API Tokens tab: generate, list, revoke. Plaintext
tokens are shown once with a copy-to-clipboard control.
This commit is contained in:
@@ -0,0 +1,123 @@
|
||||
const crypto = require('crypto');
|
||||
const { db } = require('../database/db');
|
||||
const logger = require('../utils/logger');
|
||||
|
||||
const TOKEN_PREFIX = 'pp_live_';
|
||||
const VALID_SCOPES = ['read', 'write', 'admin'];
|
||||
|
||||
function hashToken(plaintext) {
|
||||
return crypto.createHash('sha256').update(plaintext).digest('hex');
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a new API token. Returns the plaintext (return once, never
|
||||
* stored) plus the row payload to insert. Caller persists.
|
||||
*/
|
||||
function generateApiToken() {
|
||||
const random = crypto.randomBytes(24).toString('base64url'); // 32 chars
|
||||
const plaintext = `${TOKEN_PREFIX}${random}`;
|
||||
return {
|
||||
plaintext,
|
||||
hashed: hashToken(plaintext),
|
||||
preview: random.slice(0, 8)
|
||||
};
|
||||
}
|
||||
|
||||
function parseScopes(raw) {
|
||||
if (!raw) return [];
|
||||
return String(raw)
|
||||
.split(',')
|
||||
.map((s) => s.trim().toLowerCase())
|
||||
.filter((s) => VALID_SCOPES.includes(s));
|
||||
}
|
||||
|
||||
/**
|
||||
* Middleware: authenticate via API token. Maps the token to its owner
|
||||
* admin user, attaches { req.admin, req.apiToken }, then defers to the
|
||||
* regular permission machinery on top.
|
||||
*
|
||||
* Mount this *instead* of `adminAuth` on /api/v1/* routes. Existing
|
||||
* permission decorators (`requirePermission('events.create')`) still
|
||||
* work because they read `req.admin.id`.
|
||||
*/
|
||||
async function apiTokenAuth(req, res, next) {
|
||||
try {
|
||||
const header = req.headers?.authorization || '';
|
||||
if (!header.startsWith('Bearer ')) {
|
||||
return res.status(401).json({ error: 'Missing API token', code: 'NO_TOKEN' });
|
||||
}
|
||||
const token = header.slice(7).trim();
|
||||
if (!token.startsWith(TOKEN_PREFIX)) {
|
||||
return res.status(401).json({ error: 'Invalid token format', code: 'INVALID_TOKEN' });
|
||||
}
|
||||
|
||||
const hashed = hashToken(token);
|
||||
const row = await db('api_tokens').where({ hashed_token: hashed }).first();
|
||||
if (!row) {
|
||||
return res.status(401).json({ error: 'Invalid token', code: 'INVALID_TOKEN' });
|
||||
}
|
||||
if (row.revoked_at) {
|
||||
return res.status(401).json({ error: 'Token revoked', code: 'TOKEN_REVOKED' });
|
||||
}
|
||||
if (row.expires_at && new Date(row.expires_at) <= new Date()) {
|
||||
return res.status(401).json({ error: 'Token expired', code: 'TOKEN_EXPIRED' });
|
||||
}
|
||||
|
||||
const admin = await db('admin_users')
|
||||
.where({ id: row.created_by, is_active: true })
|
||||
.select('id', 'username', 'email', 'role_id')
|
||||
.first();
|
||||
if (!admin) {
|
||||
return res.status(401).json({ error: 'Token owner unavailable', code: 'OWNER_INACTIVE' });
|
||||
}
|
||||
|
||||
// Touch last_used_at — async, don't block the request.
|
||||
db('api_tokens').where({ id: row.id }).update({ last_used_at: new Date() })
|
||||
.catch((err) => logger.debug('api_tokens last_used update failed', { err: err.message }));
|
||||
|
||||
req.admin = admin;
|
||||
req.apiToken = {
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
scopes: parseScopes(row.scopes)
|
||||
};
|
||||
return next();
|
||||
} catch (error) {
|
||||
logger.error('apiTokenAuth error', { error: error.message });
|
||||
return res.status(500).json({ error: 'Authentication error' });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Middleware factory: require a specific scope on the API token. Use
|
||||
* after apiTokenAuth — `requireApiScope('write')` rejects read-only
|
||||
* tokens trying to mutate.
|
||||
*/
|
||||
function requireApiScope(scope) {
|
||||
return (req, res, next) => {
|
||||
const have = req.apiToken?.scopes || [];
|
||||
// 'admin' implies write/read; 'write' implies read.
|
||||
const expanded = new Set(have);
|
||||
if (have.includes('admin')) ['write', 'read'].forEach((s) => expanded.add(s));
|
||||
if (have.includes('write')) expanded.add('read');
|
||||
if (!expanded.has(scope)) {
|
||||
return res.status(403).json({
|
||||
error: `Token lacks required scope: ${scope}`,
|
||||
code: 'INSUFFICIENT_SCOPE',
|
||||
required: scope,
|
||||
granted: have
|
||||
});
|
||||
}
|
||||
next();
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
apiTokenAuth,
|
||||
requireApiScope,
|
||||
generateApiToken,
|
||||
hashToken,
|
||||
parseScopes,
|
||||
TOKEN_PREFIX,
|
||||
VALID_SCOPES
|
||||
};
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* OpenAPI 3.1 spec for /api/v1/* (#322). Source of truth for the
|
||||
* picpeak-docs reference page. Built from JSDoc `@openapi` blocks
|
||||
* scattered through src/routes/v1 — those stay co-located with the
|
||||
* routes they describe so the spec can't drift in isolation.
|
||||
*/
|
||||
|
||||
const swaggerJSDoc = require('swagger-jsdoc');
|
||||
const path = require('path');
|
||||
|
||||
const baseDoc = {
|
||||
openapi: '3.0.3',
|
||||
info: {
|
||||
title: 'PicPeak API',
|
||||
version: 'v1',
|
||||
description:
|
||||
'Public REST API for PicPeak — create gallery events, upload photos, fetch share links. ' +
|
||||
'Authenticate with a Bearer token issued via the admin **Settings → API Tokens** tab.'
|
||||
},
|
||||
servers: [
|
||||
{ url: '/api/v1', description: 'Same-origin (production)' }
|
||||
],
|
||||
components: {
|
||||
securitySchemes: {
|
||||
bearerAuth: {
|
||||
type: 'http',
|
||||
scheme: 'bearer',
|
||||
bearerFormat: 'pp_live_*',
|
||||
description:
|
||||
'Long-lived API token. Issue via Settings → API Tokens. ' +
|
||||
'Token format: `pp_live_<random>`. Scopes: `read`, `write`, `admin`.'
|
||||
}
|
||||
},
|
||||
schemas: {
|
||||
EventSummary: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
id: { type: 'integer' },
|
||||
slug: { type: 'string' },
|
||||
event_name: { type: 'string' },
|
||||
event_type: { type: 'string' },
|
||||
event_date: { type: 'string', format: 'date', nullable: true },
|
||||
expires_at: { type: 'string', format: 'date-time', nullable: true },
|
||||
is_active: { type: 'boolean' },
|
||||
is_archived: { type: 'boolean' },
|
||||
is_draft: { type: 'boolean' },
|
||||
created_at: { type: 'string', format: 'date-time' }
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
security: [{ bearerAuth: [] }]
|
||||
};
|
||||
|
||||
const options = {
|
||||
definition: baseDoc,
|
||||
// Pull @openapi blocks from every v1 route file.
|
||||
apis: [path.join(__dirname, '../routes/v1/**/*.js')]
|
||||
};
|
||||
|
||||
let cached = null;
|
||||
|
||||
function getOpenApiSpec() {
|
||||
if (!cached) {
|
||||
cached = swaggerJSDoc(options);
|
||||
}
|
||||
return cached;
|
||||
}
|
||||
|
||||
module.exports = { getOpenApiSpec };
|
||||
@@ -0,0 +1,117 @@
|
||||
/**
|
||||
* Admin endpoints for managing API tokens (#322). Tokens are issued to
|
||||
* an admin user; subsequent /api/v1/* calls authenticate via the token
|
||||
* and act as the user that minted it (intersected with the token's
|
||||
* scope set). Plaintext tokens are returned ONCE on creation.
|
||||
*/
|
||||
|
||||
const express = require('express');
|
||||
const { body, validationResult } = require('express-validator');
|
||||
const { db, logActivity } = require('../database/db');
|
||||
const { adminAuth } = require('./../middleware/auth');
|
||||
const { requirePermission } = require('./../middleware/permissions');
|
||||
const { generateApiToken, VALID_SCOPES } = require('./../middleware/apiTokenAuth');
|
||||
const logger = require('../utils/logger');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// List tokens for the current admin (or all, if super_admin) — without
|
||||
// the plaintext, never recoverable after creation.
|
||||
router.get('/', adminAuth, requirePermission('settings.view'), async (req, res) => {
|
||||
try {
|
||||
const tokens = await db('api_tokens')
|
||||
.leftJoin('admin_users', 'admin_users.id', 'api_tokens.created_by')
|
||||
.select(
|
||||
'api_tokens.id',
|
||||
'api_tokens.name',
|
||||
'api_tokens.scopes',
|
||||
'api_tokens.preview',
|
||||
'api_tokens.created_at',
|
||||
'api_tokens.expires_at',
|
||||
'api_tokens.last_used_at',
|
||||
'api_tokens.revoked_at',
|
||||
'admin_users.username as owner_username'
|
||||
)
|
||||
.orderBy('api_tokens.created_at', 'desc');
|
||||
res.json(tokens);
|
||||
} catch (error) {
|
||||
logger.error('Failed to list API tokens', { error: error.message });
|
||||
res.status(500).json({ error: 'Failed to list tokens' });
|
||||
}
|
||||
});
|
||||
|
||||
// Create a token. Returns plaintext exactly once.
|
||||
router.post(
|
||||
'/',
|
||||
adminAuth,
|
||||
requirePermission('settings.edit'),
|
||||
[
|
||||
body('name').isString().trim().isLength({ min: 1, max: 100 }),
|
||||
body('scopes').isArray({ min: 1 }).custom((arr) => {
|
||||
const ok = arr.every((s) => VALID_SCOPES.includes(s));
|
||||
if (!ok) throw new Error(`Scopes must be a subset of: ${VALID_SCOPES.join(', ')}`);
|
||||
return true;
|
||||
}),
|
||||
body('expires_at').optional({ nullable: true, checkFalsy: true }).isISO8601()
|
||||
],
|
||||
async (req, res) => {
|
||||
try {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
return res.status(400).json({ errors: errors.array() });
|
||||
}
|
||||
const { name, scopes, expires_at } = req.body;
|
||||
const { plaintext, hashed, preview } = generateApiToken();
|
||||
|
||||
const insertResult = await db('api_tokens').insert({
|
||||
name,
|
||||
hashed_token: hashed,
|
||||
scopes: scopes.join(','),
|
||||
preview,
|
||||
created_by: req.admin.id,
|
||||
expires_at: expires_at || null
|
||||
}).returning('id');
|
||||
const id = insertResult[0]?.id || insertResult[0];
|
||||
|
||||
await logActivity('api_token_created', { name, scopes }, null, {
|
||||
type: 'admin', id: req.admin.id, name: req.admin.username
|
||||
});
|
||||
|
||||
// Return the plaintext exactly once.
|
||||
res.status(201).json({
|
||||
id,
|
||||
name,
|
||||
scopes,
|
||||
token: plaintext,
|
||||
preview,
|
||||
expires_at: expires_at || null,
|
||||
created_at: new Date().toISOString(),
|
||||
notice: 'Save this token now — it will not be shown again.'
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error('Failed to create API token', { error: error.message });
|
||||
res.status(500).json({ error: 'Failed to create token' });
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// Revoke a token (soft-delete; lookups still find it but reject).
|
||||
router.delete('/:id', adminAuth, requirePermission('settings.edit'), async (req, res) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const row = await db('api_tokens').where({ id }).first();
|
||||
if (!row) return res.status(404).json({ error: 'Token not found' });
|
||||
if (row.revoked_at) return res.status(400).json({ error: 'Token already revoked' });
|
||||
|
||||
await db('api_tokens').where({ id }).update({ revoked_at: new Date() });
|
||||
await logActivity('api_token_revoked', { name: row.name }, null, {
|
||||
type: 'admin', id: req.admin.id, name: req.admin.username
|
||||
});
|
||||
res.json({ id: Number(id), revoked: true });
|
||||
} catch (error) {
|
||||
logger.error('Failed to revoke API token', { error: error.message });
|
||||
res.status(500).json({ error: 'Failed to revoke token' });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,447 @@
|
||||
/**
|
||||
* Public v1 API — events + photo upload + share link.
|
||||
*
|
||||
* Surface chosen for the n8n / automation use case (#322): create gallery,
|
||||
* upload photos, get a share URL. Intentionally narrow — update/delete
|
||||
* are admin-only via the UI for v1. Mounts under /api/v1 with apiTokenAuth.
|
||||
*
|
||||
* Each route is annotated with @openapi JSDoc that swagger-jsdoc picks
|
||||
* up to generate docs/openapi.yaml — the source of truth for picpeak-docs.
|
||||
*/
|
||||
|
||||
const express = require('express');
|
||||
const path = require('path');
|
||||
const fs = require('fs').promises;
|
||||
const fsSync = require('fs');
|
||||
const crypto = require('crypto');
|
||||
const multer = require('multer');
|
||||
const sharp = require('sharp');
|
||||
const { body, query, validationResult } = require('express-validator');
|
||||
const { db, logActivity } = require('../../database/db');
|
||||
const { apiTokenAuth, requireApiScope } = require('../../middleware/apiTokenAuth');
|
||||
const { buildShareLinkVariants } = require('../../services/shareLinkService');
|
||||
const { generateThumbnail } = require('../../services/imageProcessor');
|
||||
const logger = require('../../utils/logger');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
const getStoragePath = () => process.env.STORAGE_PATH || path.join(__dirname, '../../../../storage');
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────────────
|
||||
// Multer for single-photo upload. Lean — no replace-by-name, no batching.
|
||||
// ──────────────────────────────────────────────────────────────────────────
|
||||
const photoStorage = multer.diskStorage({
|
||||
destination: async (_req, _file, cb) => {
|
||||
const tempDir = path.join(getStoragePath(), 'temp');
|
||||
await fs.mkdir(tempDir, { recursive: true });
|
||||
cb(null, tempDir);
|
||||
},
|
||||
filename: (_req, file, cb) => {
|
||||
const ext = path.extname(file.originalname);
|
||||
cb(null, `v1_${Date.now()}_${crypto.randomBytes(4).toString('hex')}${ext}`);
|
||||
}
|
||||
});
|
||||
const photoUpload = multer({
|
||||
storage: photoStorage,
|
||||
limits: { fileSize: 100 * 1024 * 1024 }, // 100MB per file for v1
|
||||
fileFilter: (_req, file, cb) => {
|
||||
if (/^image\//.test(file.mimetype)) cb(null, true);
|
||||
else cb(new Error('Only image uploads are accepted on this endpoint'));
|
||||
}
|
||||
});
|
||||
|
||||
const slugify = (s) =>
|
||||
String(s).toLowerCase().replace(/[^a-z0-9]/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '');
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────────────
|
||||
// POST /events — create event
|
||||
// ──────────────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /events:
|
||||
* post:
|
||||
* tags: [Events]
|
||||
* summary: Create a gallery event
|
||||
* description: Returns the new event's id, slug, and absolute share URL.
|
||||
* security: [{ bearerAuth: [] }]
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* required: [event_name, event_type]
|
||||
* properties:
|
||||
* event_name: { type: string }
|
||||
* event_type:
|
||||
* type: string
|
||||
* enum: [wedding, birthday, corporate, other, family]
|
||||
* event_date: { type: string, format: date, nullable: true }
|
||||
* customer_name: { type: string, nullable: true }
|
||||
* customer_email: { type: string, format: email, nullable: true }
|
||||
* customer_phone: { type: string, nullable: true, description: "Only persisted when the global phone-field setting is enabled." }
|
||||
* admin_email: { type: string, format: email, nullable: true }
|
||||
* require_password: { type: boolean, default: true }
|
||||
* password: { type: string, nullable: true, description: "Required when require_password is true." }
|
||||
* expires_at: { type: string, format: date-time, nullable: true }
|
||||
* responses:
|
||||
* 201:
|
||||
* description: Event created
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* id: { type: integer }
|
||||
* slug: { type: string }
|
||||
* share_url: { type: string, format: uri }
|
||||
* share_token: { type: string }
|
||||
* 400: { description: Validation error }
|
||||
* 401: { description: Missing/invalid token }
|
||||
* 403: { description: Token lacks admin scope }
|
||||
*/
|
||||
router.post(
|
||||
'/events',
|
||||
apiTokenAuth,
|
||||
requireApiScope('admin'),
|
||||
[
|
||||
body('event_name').isString().trim().notEmpty(),
|
||||
body('event_type').isIn(['wedding', 'birthday', 'corporate', 'other', 'family']),
|
||||
body('event_date').optional({ nullable: true, checkFalsy: true }).isISO8601(),
|
||||
body('customer_name').optional({ nullable: true }).isString(),
|
||||
body('customer_email').optional({ nullable: true, checkFalsy: true }).isEmail(),
|
||||
body('customer_phone').optional({ nullable: true, checkFalsy: true }).isString().isLength({ max: 32 }),
|
||||
body('admin_email').optional({ nullable: true, checkFalsy: true }).isEmail(),
|
||||
body('require_password').optional().isBoolean(),
|
||||
body('password').optional({ nullable: true }).isString().isLength({ min: 6 }),
|
||||
body('expires_at').optional({ nullable: true, checkFalsy: true }).isISO8601()
|
||||
],
|
||||
async (req, res) => {
|
||||
try {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) return res.status(400).json({ errors: errors.array() });
|
||||
const {
|
||||
event_name, event_type, event_date,
|
||||
customer_name = null, customer_email = null, customer_phone = null,
|
||||
admin_email = null, require_password = true, password,
|
||||
expires_at = null
|
||||
} = req.body;
|
||||
|
||||
if (require_password && (!password || password.length < 6)) {
|
||||
return res.status(400).json({ error: 'Password is required when require_password is true (min 6 chars)' });
|
||||
}
|
||||
|
||||
// Honour global phone-field toggle (#322).
|
||||
let persistPhone = null;
|
||||
if (customer_phone) {
|
||||
const setting = await db('app_settings').where('setting_key', 'event_phone_field_enabled').first();
|
||||
const enabled = setting ? JSON.parse(setting.setting_value) === true : false;
|
||||
persistPhone = enabled ? customer_phone : null;
|
||||
}
|
||||
|
||||
// Generate unique slug.
|
||||
const baseSlug = `${event_type}-${slugify(event_name)}-${event_date || crypto.randomBytes(3).toString('hex')}`;
|
||||
let slug = baseSlug;
|
||||
let counter = 1;
|
||||
while (await db('events').where({ slug }).first()) slug = `${baseSlug}-${counter++}`;
|
||||
|
||||
const shareToken = crypto.randomBytes(16).toString('hex');
|
||||
const { shareUrl, shareLinkToStore } = await buildShareLinkVariants({ slug, shareToken });
|
||||
|
||||
// password_hash is NOT NULL; use a random placeholder when no
|
||||
// password is required so the column constraint is satisfied.
|
||||
const bcrypt = require('bcrypt');
|
||||
const passwordHash = require_password
|
||||
? await bcrypt.hash(password, 10)
|
||||
: await bcrypt.hash(crypto.randomBytes(32).toString('hex'), 10);
|
||||
|
||||
const insertResult = await db('events').insert({
|
||||
slug,
|
||||
event_type,
|
||||
event_name,
|
||||
event_date: event_date || null,
|
||||
host_name: customer_name,
|
||||
host_email: customer_email,
|
||||
admin_email,
|
||||
password_hash: passwordHash,
|
||||
require_password,
|
||||
share_link: shareLinkToStore,
|
||||
share_token: shareToken,
|
||||
expires_at: expires_at || null,
|
||||
created_at: new Date().toISOString(),
|
||||
created_by: req.admin.id,
|
||||
is_draft: false,
|
||||
...(customer_name ? { customer_name } : {}),
|
||||
...(customer_email ? { customer_email } : {}),
|
||||
...(persistPhone ? { customer_phone: persistPhone } : {})
|
||||
}).returning('id');
|
||||
const id = insertResult[0]?.id || insertResult[0];
|
||||
|
||||
await logActivity('event_created', { via: 'api_v1', event_type }, id, {
|
||||
type: 'admin', id: req.admin.id, name: req.admin.username
|
||||
});
|
||||
|
||||
res.status(201).json({ id, slug, share_url: shareUrl, share_token: shareToken });
|
||||
} catch (error) {
|
||||
logger.error('v1 POST /events failed', { error: error.message, stack: error.stack });
|
||||
res.status(500).json({ error: 'Failed to create event', detail: error.message });
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────────────
|
||||
// GET /events — list
|
||||
// ──────────────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /events:
|
||||
* get:
|
||||
* tags: [Events]
|
||||
* summary: List gallery events (paginated)
|
||||
* security: [{ bearerAuth: [] }]
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: page
|
||||
* schema: { type: integer, minimum: 1, default: 1 }
|
||||
* - in: query
|
||||
* name: limit
|
||||
* schema: { type: integer, minimum: 1, maximum: 100, default: 25 }
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Paginated list
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* events:
|
||||
* type: array
|
||||
* items: { $ref: '#/components/schemas/EventSummary' }
|
||||
* pagination:
|
||||
* type: object
|
||||
* properties:
|
||||
* page: { type: integer }
|
||||
* limit: { type: integer }
|
||||
* total: { type: integer }
|
||||
*/
|
||||
router.get(
|
||||
'/events',
|
||||
apiTokenAuth,
|
||||
requireApiScope('read'),
|
||||
[
|
||||
query('page').optional().isInt({ min: 1 }).toInt(),
|
||||
query('limit').optional().isInt({ min: 1, max: 100 }).toInt()
|
||||
],
|
||||
async (req, res) => {
|
||||
try {
|
||||
const page = req.query.page || 1;
|
||||
const limit = req.query.limit || 25;
|
||||
const offset = (page - 1) * limit;
|
||||
|
||||
const [events, totalRow] = await Promise.all([
|
||||
db('events')
|
||||
.select('id', 'slug', 'event_name', 'event_type', 'event_date', 'expires_at',
|
||||
'is_active', 'is_archived', 'is_draft', 'created_at')
|
||||
.orderBy('created_at', 'desc')
|
||||
.limit(limit)
|
||||
.offset(offset),
|
||||
db('events').count('id as count').first()
|
||||
]);
|
||||
const total = parseInt(totalRow?.count || 0, 10);
|
||||
res.json({ events, pagination: { page, limit, total } });
|
||||
} catch (error) {
|
||||
logger.error('v1 GET /events failed', { error: error.message });
|
||||
res.status(500).json({ error: 'Failed to list events' });
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────────────
|
||||
// GET /events/:id — read
|
||||
// ──────────────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /events/{id}:
|
||||
* get:
|
||||
* tags: [Events]
|
||||
* summary: Get a single event
|
||||
* security: [{ bearerAuth: [] }]
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema: { type: integer }
|
||||
* responses:
|
||||
* 200: { description: Event details }
|
||||
* 404: { description: Not found }
|
||||
*/
|
||||
router.get('/events/:id', apiTokenAuth, requireApiScope('read'), async (req, res) => {
|
||||
try {
|
||||
const event = await db('events').where({ id: req.params.id }).first();
|
||||
if (!event) return res.status(404).json({ error: 'Event not found' });
|
||||
delete event.password_hash;
|
||||
delete event.client_password_hash;
|
||||
res.json(event);
|
||||
} catch (error) {
|
||||
logger.error('v1 GET /events/:id failed', { error: error.message });
|
||||
res.status(500).json({ error: 'Failed to fetch event' });
|
||||
}
|
||||
});
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────────────
|
||||
// POST /events/:id/photos — upload one photo
|
||||
// ──────────────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /events/{id}/photos:
|
||||
* post:
|
||||
* tags: [Photos]
|
||||
* summary: Upload a single photo to an event
|
||||
* security: [{ bearerAuth: [] }]
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema: { type: integer }
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* multipart/form-data:
|
||||
* schema:
|
||||
* type: object
|
||||
* required: [photo]
|
||||
* properties:
|
||||
* photo: { type: string, format: binary }
|
||||
* responses:
|
||||
* 201:
|
||||
* description: Photo uploaded
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* id: { type: integer }
|
||||
* filename: { type: string }
|
||||
* path: { type: string }
|
||||
* thumbnail_path: { type: string, nullable: true }
|
||||
* size_bytes: { type: integer }
|
||||
* 400: { description: No file or invalid type }
|
||||
* 404: { description: Event not found }
|
||||
*/
|
||||
router.post(
|
||||
'/events/:id/photos',
|
||||
apiTokenAuth,
|
||||
requireApiScope('write'),
|
||||
photoUpload.single('photo'),
|
||||
async (req, res) => {
|
||||
let tempPath = null;
|
||||
try {
|
||||
if (!req.file) return res.status(400).json({ error: 'No file uploaded under field "photo"' });
|
||||
tempPath = req.file.path;
|
||||
|
||||
const event = await db('events').where({ id: req.params.id }).first();
|
||||
if (!event) return res.status(404).json({ error: 'Event not found' });
|
||||
|
||||
const finalDir = path.join(getStoragePath(), 'events/active', event.slug);
|
||||
await fs.mkdir(finalDir, { recursive: true });
|
||||
const ext = path.extname(req.file.originalname);
|
||||
const finalName = `${Date.now()}_${crypto.randomBytes(4).toString('hex')}${ext}`;
|
||||
const finalPath = path.join(finalDir, finalName);
|
||||
await fs.rename(tempPath, finalPath);
|
||||
tempPath = null;
|
||||
|
||||
const stat = fsSync.statSync(finalPath);
|
||||
const relPath = path.relative(path.join(getStoragePath(), 'events/active'), finalPath);
|
||||
|
||||
let thumbRel = null;
|
||||
try {
|
||||
const thumbPath = await generateThumbnail(finalPath);
|
||||
thumbRel = path.relative(getStoragePath(), thumbPath);
|
||||
} catch (err) {
|
||||
logger.warn('v1 thumbnail generation failed', { err: err.message });
|
||||
}
|
||||
|
||||
// Detect image dimensions for masonry layouts.
|
||||
let width = null;
|
||||
let height = null;
|
||||
try {
|
||||
const meta = await sharp(finalPath).metadata();
|
||||
width = meta.width || null;
|
||||
height = meta.height || null;
|
||||
} catch { /* non-fatal */ }
|
||||
|
||||
const insertResult = await db('photos').insert({
|
||||
event_id: event.id,
|
||||
filename: finalName,
|
||||
original_filename: req.file.originalname,
|
||||
path: relPath,
|
||||
thumbnail_path: thumbRel,
|
||||
type: 'individual',
|
||||
size_bytes: stat.size,
|
||||
width,
|
||||
height,
|
||||
media_type: 'image',
|
||||
mime_type: req.file.mimetype,
|
||||
uploaded_at: new Date().toISOString()
|
||||
}).returning('id');
|
||||
const id = insertResult[0]?.id || insertResult[0];
|
||||
|
||||
await logActivity('photo_uploaded', { via: 'api_v1', filename: finalName }, event.id, {
|
||||
type: 'admin', id: req.admin.id, name: req.admin.username
|
||||
});
|
||||
|
||||
res.status(201).json({ id, filename: finalName, path: relPath, thumbnail_path: thumbRel, size_bytes: stat.size });
|
||||
} catch (error) {
|
||||
logger.error('v1 POST /events/:id/photos failed', { error: error.message });
|
||||
if (tempPath) await fs.unlink(tempPath).catch(() => {});
|
||||
res.status(500).json({ error: 'Failed to upload photo' });
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────────────
|
||||
// GET /events/:id/share-link — full URL for sending to guests
|
||||
// ──────────────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /events/{id}/share-link:
|
||||
* get:
|
||||
* tags: [Events]
|
||||
* summary: Get the absolute share URL for an event
|
||||
* security: [{ bearerAuth: [] }]
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema: { type: integer }
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Share URL
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* slug: { type: string }
|
||||
* share_token: { type: string }
|
||||
* share_url: { type: string, format: uri }
|
||||
* 404: { description: Not found }
|
||||
*/
|
||||
router.get('/events/:id/share-link', apiTokenAuth, requireApiScope('read'), async (req, res) => {
|
||||
try {
|
||||
const event = await db('events').where({ id: req.params.id }).first();
|
||||
if (!event) return res.status(404).json({ error: 'Event not found' });
|
||||
const { shareUrl } = await buildShareLinkVariants({ slug: event.slug, shareToken: event.share_token });
|
||||
res.json({ slug: event.slug, share_token: event.share_token, share_url: shareUrl });
|
||||
} catch (error) {
|
||||
logger.error('v1 GET /events/:id/share-link failed', { error: error.message });
|
||||
res.status(500).json({ error: 'Failed to build share link' });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
Reference in New Issue
Block a user