LearnSpace: full-stack educational whiteboard platform
Node.js/Express backend + vanilla JS frontend. Features: real-time collaborative whiteboard (SSE), multi-page support, LaTeX formulas, shapes/connectors, coordinate systems, number lines, compass, zoom/pan, Catmull-Rom pencil smoothing, ruler/protractor with rotation & resize controls, minimap navigation overlay, auto-measurements, multi-page thumbnails sidebar, PNG export, page templates. Student/teacher workflows: classes, assignments, library, dashboard. Mobile responsive. SQLite (better-sqlite3). Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,154 @@
|
||||
const jwt = require('jsonwebtoken');
|
||||
const db = require('../db/db');
|
||||
|
||||
/* ── Default values for role_permissions (mirrors permissionsController) ── */
|
||||
const PERM_DEFAULTS = {
|
||||
teacher: {
|
||||
'questions.manage': false,
|
||||
'questions.delete': false,
|
||||
'students.invite': false,
|
||||
'sessions.reset': true,
|
||||
'results.export': true,
|
||||
'classes.manage': true,
|
||||
'library.upload': true,
|
||||
'library.folders': true,
|
||||
'schedule.manage': true,
|
||||
'announcements.send': true,
|
||||
'templates.manage': true,
|
||||
'templates.public': false,
|
||||
'courses.manage': true,
|
||||
'courses.interactive': true,
|
||||
'shop.manage': false,
|
||||
'gamification.manage': false,
|
||||
},
|
||||
student: {
|
||||
'tests.free': true,
|
||||
'board.post': true,
|
||||
'profile.edit': true,
|
||||
'shop.purchase': true,
|
||||
'gamification.challenges': true,
|
||||
'theory.access': true,
|
||||
'simulations.access': true,
|
||||
'simulations.quiz': true,
|
||||
},
|
||||
free_student: {
|
||||
'tests.free': true,
|
||||
'board.post': true,
|
||||
'profile.edit': true,
|
||||
'shop.purchase': true,
|
||||
'gamification.challenges': true,
|
||||
'theory.access': true,
|
||||
'simulations.access': true,
|
||||
'simulations.quiz': true,
|
||||
},
|
||||
};
|
||||
|
||||
function authMiddleware(req, res, next) {
|
||||
const header = req.headers.authorization;
|
||||
if (!header || !header.startsWith('Bearer ')) {
|
||||
return res.status(401).json({ error: 'Unauthorized' });
|
||||
}
|
||||
|
||||
const token = header.slice(7);
|
||||
try {
|
||||
const payload = jwt.verify(token, process.env.JWT_SECRET, { algorithms: ['HS256'] });
|
||||
// Re-fetch role + token_version from DB so changes take effect immediately
|
||||
const fresh = db.prepare('SELECT role, token_version, is_banned FROM users WHERE id = ?').get(payload.id);
|
||||
if (!fresh) return res.status(401).json({ error: 'User not found' });
|
||||
if (fresh.is_banned) return res.status(403).json({ error: 'Аккаунт заблокирован' });
|
||||
// Invalidate tokens issued before password change / role change.
|
||||
// If DB has token_version set, token MUST carry matching tv.
|
||||
// (payload.tv === undefined means old token without version — also revoke)
|
||||
if (fresh.token_version != null && payload.tv !== fresh.token_version) {
|
||||
return res.status(401).json({ error: 'Token revoked — please log in again' });
|
||||
}
|
||||
req.user = { ...payload, role: fresh.role };
|
||||
next();
|
||||
} catch {
|
||||
res.status(401).json({ error: 'Token invalid or expired' });
|
||||
}
|
||||
}
|
||||
|
||||
function requireRole(...roles) {
|
||||
return (req, res, next) => {
|
||||
if (!roles.includes(req.user?.role)) {
|
||||
return res.status(403).json({ error: 'Forbidden' });
|
||||
}
|
||||
next();
|
||||
};
|
||||
}
|
||||
|
||||
/* ── Check permission; user override → role override → hardcoded default ── */
|
||||
function requirePermission(key) {
|
||||
return (req, res, next) => {
|
||||
if (req.user?.role === 'admin') return next();
|
||||
const role = req.user?.role;
|
||||
const uid = req.user?.id;
|
||||
if (!role) return res.status(401).json({ error: 'Unauthorized' });
|
||||
|
||||
// 1. User-level override
|
||||
const userRow = db.prepare(
|
||||
'SELECT enabled FROM user_permissions WHERE user_id = ? AND permission = ?'
|
||||
).get(uid, key);
|
||||
if (userRow !== undefined) {
|
||||
return userRow.enabled === 1 ? next() : res.status(403).json({ error: 'Permission denied' });
|
||||
}
|
||||
|
||||
// 2. Role-level
|
||||
const roleRow = db.prepare(
|
||||
'SELECT enabled FROM role_permissions WHERE role = ? AND permission = ?'
|
||||
).get(role, key);
|
||||
const enabled = roleRow !== undefined ? roleRow.enabled === 1 : (PERM_DEFAULTS[role]?.[key] ?? false);
|
||||
if (enabled) return next();
|
||||
return res.status(403).json({ error: 'Permission denied' });
|
||||
};
|
||||
}
|
||||
|
||||
/* ── Parent link JWT auth (separate from user auth) ───────────────────── */
|
||||
function parentAuth(req, res, next) {
|
||||
const header = req.headers.authorization;
|
||||
if (!header || !header.startsWith('Bearer '))
|
||||
return res.status(401).json({ error: 'Unauthorized' });
|
||||
|
||||
const token = header.slice(7);
|
||||
try {
|
||||
const payload = jwt.verify(token, process.env.JWT_SECRET, { algorithms: ['HS256'] });
|
||||
if (payload.type !== 'parent')
|
||||
return res.status(401).json({ error: 'Invalid token type' });
|
||||
|
||||
const link = db.prepare(
|
||||
'SELECT id, student_id, is_active, expires_at FROM parent_links WHERE id = ?'
|
||||
).get(payload.linkId);
|
||||
if (!link || !link.is_active)
|
||||
return res.status(401).json({ error: 'Link revoked' });
|
||||
if (link.expires_at && new Date(link.expires_at) < new Date())
|
||||
return res.status(401).json({ error: 'Link expired' });
|
||||
|
||||
req.parent = { linkId: link.id, studentId: link.student_id };
|
||||
next();
|
||||
} catch {
|
||||
res.status(401).json({ error: 'Token invalid or expired' });
|
||||
}
|
||||
}
|
||||
|
||||
/* Alias: requireAuth = authMiddleware */
|
||||
const requireAuth = authMiddleware;
|
||||
|
||||
/* optionalAuth: попытаться установить req.user, но не блокировать при отсутствии токена */
|
||||
function optionalAuth(req, res, next) {
|
||||
const header = req.headers.authorization || '';
|
||||
if (!header.startsWith('Bearer ')) return next();
|
||||
const token = header.slice(7);
|
||||
try {
|
||||
const payload = jwt.verify(token, process.env.JWT_SECRET, { algorithms: ['HS256'] });
|
||||
const fresh = db.prepare('SELECT role, token_version, is_banned FROM users WHERE id = ?').get(payload.id);
|
||||
if (fresh && !fresh.is_banned) {
|
||||
if (fresh.token_version == null || payload.tv === fresh.token_version) {
|
||||
req.user = { ...payload, role: fresh.role };
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
next();
|
||||
}
|
||||
|
||||
module.exports = { authMiddleware, requireAuth, optionalAuth, requireRole, requirePermission, parentAuth };
|
||||
@@ -0,0 +1,77 @@
|
||||
'use strict';
|
||||
|
||||
/* ── Error handling middleware ─────────────────────────────────────────────
|
||||
requestId — attach X-Request-Id to every request (use early in middleware chain)
|
||||
errorHandler — 4-arg Express error handler (use as last app.use)
|
||||
──────────────────────────────────────────────────────────────────────── */
|
||||
|
||||
const crypto = require('crypto');
|
||||
const logger = require('../utils/logger');
|
||||
let _errorLogStmt = null;
|
||||
function getErrorLogStmt() {
|
||||
if (!_errorLogStmt) {
|
||||
try {
|
||||
const db = require('../db/db');
|
||||
_errorLogStmt = db.prepare(
|
||||
'INSERT INTO error_log (level, message, stack, route, method, user_id) VALUES (?, ?, ?, ?, ?, ?)'
|
||||
);
|
||||
} catch {}
|
||||
}
|
||||
return _errorLogStmt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Attaches a unique request ID to req.requestId and sets X-Request-Id header.
|
||||
* Honour an incoming X-Request-Id from trusted proxies/gateways when present.
|
||||
*/
|
||||
function requestId(req, res, next) {
|
||||
const id = req.headers['x-request-id'] || crypto.randomUUID();
|
||||
req.requestId = id;
|
||||
res.setHeader('X-Request-Id', id);
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Global error handler — must be registered AFTER all routes.
|
||||
*
|
||||
* Classifies errors:
|
||||
* operational (4xx) — expected client errors → warn level, message returned as-is
|
||||
* programmer (5xx) — unexpected bugs → error level, stack logged, message hidden in prod
|
||||
*/
|
||||
function errorHandler(err, req, res, _next) {
|
||||
const status = err.status || err.statusCode || 500;
|
||||
const isOperational = status >= 400 && status < 500;
|
||||
const isProd = process.env.NODE_ENV === 'production';
|
||||
|
||||
const meta = {
|
||||
requestId: req.requestId,
|
||||
method: req.method,
|
||||
path: req.path,
|
||||
status,
|
||||
userId: req.user?.id,
|
||||
role: req.user?.role,
|
||||
};
|
||||
|
||||
if (isOperational) {
|
||||
logger.warn(err.message || 'Client error', meta);
|
||||
} else {
|
||||
logger.error(err.message || 'Unhandled error', {
|
||||
...meta,
|
||||
stack: !isProd ? err.stack : undefined,
|
||||
});
|
||||
// Persist to error_log table for admin dashboard
|
||||
try {
|
||||
const s = getErrorLogStmt();
|
||||
if (s) s.run('error', (err.message || 'Unknown').slice(0, 1000), (err.stack || '').slice(0, 4000), req.path, req.method, req.user?.id || null);
|
||||
} catch {}
|
||||
}
|
||||
|
||||
const message = isProd && !isOperational
|
||||
? 'Internal server error'
|
||||
: (err.message || 'Server error');
|
||||
|
||||
if (res.headersSent) return;
|
||||
res.status(status).json({ error: message, requestId: req.requestId });
|
||||
}
|
||||
|
||||
module.exports = { requestId, errorHandler };
|
||||
@@ -0,0 +1,54 @@
|
||||
'use strict';
|
||||
const db = require('../db/db');
|
||||
|
||||
/**
|
||||
* Factory: returns middleware that loads a resource by req.params[paramKey],
|
||||
* verifies ownership against req.user.id, and attaches the row as req.resource.
|
||||
*
|
||||
* Simple usage (table lookup):
|
||||
* requireOwnership({ table: 'tests', ownerField: 'created_by' })
|
||||
*
|
||||
* Complex usage (JOIN / aliased field):
|
||||
* requireOwnership({
|
||||
* fetchFn: id => db.prepare(`
|
||||
* SELECT a.id, COALESCE(c.teacher_id, a.created_by) AS teacher_id
|
||||
* FROM assignments a LEFT JOIN classes c ON c.id = a.class_id WHERE a.id = ?
|
||||
* `).get(id),
|
||||
* ownerField: 'teacher_id',
|
||||
* })
|
||||
*
|
||||
* Options:
|
||||
* table — DB table name for `SELECT * FROM {table} WHERE id = ?`
|
||||
* fetchFn — (id) => row|undefined (alternative to `table`)
|
||||
* ownerField — row field compared to req.user.id (required)
|
||||
* paramKey — req.params key for the record ID (default: 'id')
|
||||
* adminBypass — admin role always passes (default: true)
|
||||
*/
|
||||
const ALLOWED_TABLES = new Set(['tests','classes','assignments','questions','courses','lessons','files','folders','shop_items','live_sessions']);
|
||||
|
||||
function requireOwnership({ table, fetchFn, ownerField, paramKey = 'id', adminBypass = true }) {
|
||||
if (table && !ALLOWED_TABLES.has(table)) throw new Error(`requireOwnership: unknown table "${table}"`);
|
||||
// Pre-compile statement once at middleware creation (server startup)
|
||||
const stmt = table ? db.prepare(`SELECT * FROM ${table} WHERE id = ?`) : null;
|
||||
const fetch = fetchFn || (id => stmt.get(id));
|
||||
|
||||
return (req, res, next) => {
|
||||
const row = fetch(req.params[paramKey]);
|
||||
|
||||
if (!row) return res.status(404).json({ error: 'Not found' });
|
||||
|
||||
if (adminBypass && req.user?.role === 'admin') {
|
||||
req.resource = row;
|
||||
return next();
|
||||
}
|
||||
|
||||
if (row[ownerField] !== req.user?.id) {
|
||||
return res.status(403).json({ error: 'Forbidden' });
|
||||
}
|
||||
|
||||
req.resource = row;
|
||||
next();
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { requireOwnership };
|
||||
@@ -0,0 +1,40 @@
|
||||
/* Simple in-memory rate limiter — no external dependency needed */
|
||||
|
||||
// Clean stale entries every 5 minutes across all stores
|
||||
const _allStores = new Set();
|
||||
setInterval(() => {
|
||||
const now = Date.now();
|
||||
for (const store of _allStores) {
|
||||
for (const [key, entry] of store) {
|
||||
if (now > entry.resetAt) store.delete(key);
|
||||
}
|
||||
}
|
||||
}, 5 * 60 * 1000).unref();
|
||||
|
||||
module.exports = function rateLimit({ windowMs = 60_000, max = 10, message = 'Too many requests, please try again later' } = {}) {
|
||||
// Skip rate limiting in test environment
|
||||
if (process.env.NODE_ENV === 'test') return (_req, _res, next) => next();
|
||||
|
||||
// Each rateLimit() call gets its own isolated store — counters don't bleed between limiters
|
||||
const store = new Map();
|
||||
_allStores.add(store);
|
||||
|
||||
return (req, res, next) => {
|
||||
const key = req.ip || req.socket?.remoteAddress || 'unknown';
|
||||
const now = Date.now();
|
||||
let entry = store.get(key);
|
||||
|
||||
if (!entry || now > entry.resetAt) {
|
||||
entry = { count: 0, resetAt: now + windowMs };
|
||||
}
|
||||
entry.count++;
|
||||
store.set(key, entry);
|
||||
|
||||
if (entry.count > max) {
|
||||
const retryAfter = Math.ceil((entry.resetAt - now) / 1000);
|
||||
res.set('Retry-After', retryAfter);
|
||||
return res.status(429).json({ error: message });
|
||||
}
|
||||
next();
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,89 @@
|
||||
/* ── Lightweight input validation middleware (no external deps) ─────────── */
|
||||
|
||||
/**
|
||||
* validate(schema) — Express middleware factory.
|
||||
*
|
||||
* Schema format:
|
||||
* { body: { field: { type, required, min, max, minLen, maxLen, match, oneOf, custom } },
|
||||
* params: { ... },
|
||||
* query: { ... } }
|
||||
*
|
||||
* Supported rule keys:
|
||||
* type — 'string' | 'number' | 'boolean' | 'object' | 'array'
|
||||
* required — true/false (default false)
|
||||
* min / max — for numbers
|
||||
* minLen / maxLen — for strings
|
||||
* match — RegExp
|
||||
* oneOf — array of allowed values
|
||||
* custom — fn(value) => string|null (return error string or null)
|
||||
*/
|
||||
function validate(schema) {
|
||||
return (req, res, next) => {
|
||||
const errors = [];
|
||||
|
||||
for (const source of ['body', 'params', 'query']) {
|
||||
const rules = schema[source];
|
||||
if (!rules) continue;
|
||||
const data = req[source] || {};
|
||||
|
||||
for (const [field, rule] of Object.entries(rules)) {
|
||||
const val = data[field];
|
||||
const label = `${source}.${field}`;
|
||||
|
||||
// Required check
|
||||
if (rule.required && (val === undefined || val === null || val === '')) {
|
||||
errors.push(`${label} обязателен`);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Skip optional absent fields
|
||||
if (val === undefined || val === null) continue;
|
||||
|
||||
// Type check
|
||||
if (rule.type) {
|
||||
const t = rule.type;
|
||||
if (t === 'array' && !Array.isArray(val)) {
|
||||
errors.push(`${label} должен быть массивом`);
|
||||
continue;
|
||||
}
|
||||
if (t !== 'array' && typeof val !== t) {
|
||||
errors.push(`${label} должен быть типа ${t}`);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Number constraints
|
||||
if (typeof val === 'number') {
|
||||
if (rule.min !== undefined && val < rule.min) errors.push(`${label} минимум ${rule.min}`);
|
||||
if (rule.max !== undefined && val > rule.max) errors.push(`${label} максимум ${rule.max}`);
|
||||
if (rule.integer && !Number.isInteger(val)) errors.push(`${label} должен быть целым числом`);
|
||||
}
|
||||
|
||||
// String constraints
|
||||
if (typeof val === 'string') {
|
||||
if (rule.minLen !== undefined && val.length < rule.minLen) errors.push(`${label} минимум ${rule.minLen} символов`);
|
||||
if (rule.maxLen !== undefined && val.length > rule.maxLen) errors.push(`${label} максимум ${rule.maxLen} символов`);
|
||||
if (rule.match && !rule.match.test(val)) errors.push(`${label} неверный формат`);
|
||||
}
|
||||
|
||||
// Enum
|
||||
if (rule.oneOf && !rule.oneOf.includes(val)) {
|
||||
errors.push(`${label} должен быть одним из: ${rule.oneOf.join(', ')}`);
|
||||
}
|
||||
|
||||
// Custom validator
|
||||
if (rule.custom) {
|
||||
const err = rule.custom(val);
|
||||
if (err) errors.push(`${label}: ${err}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (errors.length) {
|
||||
return res.status(400).json({ error: errors.join('; ') });
|
||||
}
|
||||
next();
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = validate;
|
||||
Reference in New Issue
Block a user