Backend is here. Default admin is created if needed.

This commit is contained in:
aodulov
2025-11-19 10:48:37 +02:00
parent 10819cc6f5
commit bb705c8a63
25 changed files with 3662 additions and 944 deletions

View File

@@ -0,0 +1,82 @@
import express from 'express';
import { PrismaClient } from '@prisma/client';
import jwt from 'jsonwebtoken';
const router = express.Router();
const prisma = new PrismaClient();
const JWT_SECRET = process.env.JWT_SECRET || 'secret';
// Middleware to check auth
const authenticate = (req: any, res: any, next: any) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).json({ error: 'Unauthorized' });
try {
const decoded = jwt.verify(token, JWT_SECRET) as any;
req.user = decoded;
next();
} catch {
res.status(401).json({ error: 'Invalid token' });
}
};
router.use(authenticate);
// Get all exercises (system default + user custom)
router.get('/', async (req: any, res) => {
try {
const userId = req.user.userId;
const exercises = await prisma.exercise.findMany({
where: {
OR: [
{ userId: null }, // System default
{ userId } // User custom
],
isArchived: false
}
});
res.json(exercises);
} catch (error) {
res.status(500).json({ error: 'Server error' });
}
});
// Create/Update exercise
router.post('/', async (req: any, res) => {
try {
const userId = req.user.userId;
const { id, name, type, bodyWeightPercentage } = req.body;
// If id exists and belongs to user, update. Else create.
// Note: We can't update system exercises directly. If user edits a system exercise,
// we should probably create a copy or handle it as a user override.
// For simplicity, let's assume we are creating/updating user exercises.
if (id) {
// Check if it exists and belongs to user
const existing = await prisma.exercise.findUnique({ where: { id } });
if (existing && existing.userId === userId) {
const updated = await prisma.exercise.update({
where: { id },
data: { name, type, bodyWeightPercentage }
});
return res.json(updated);
}
}
// Create new
const newExercise = await prisma.exercise.create({
data: {
userId,
name,
type,
bodyWeightPercentage
}
});
res.json(newExercise);
} catch (error) {
res.status(500).json({ error: 'Server error' });
}
});
export default router;