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:
Maxim Dolgolyov
2026-04-12 10:10:37 +03:00
commit be4d43105e
204 changed files with 118117 additions and 0 deletions
+154
View File
@@ -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 };