Backend is here. Default admin is created if needed.
This commit is contained in:
52
server/src/routes/ai.ts
Normal file
52
server/src/routes/ai.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import express from 'express';
|
||||
import { GoogleGenerativeAI } from '@google/generative-ai';
|
||||
import jwt from 'jsonwebtoken';
|
||||
|
||||
const router = express.Router();
|
||||
const JWT_SECRET = process.env.JWT_SECRET || 'secret';
|
||||
const API_KEY = process.env.API_KEY;
|
||||
const MODEL_ID = 'gemini-1.5-flash';
|
||||
|
||||
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);
|
||||
|
||||
router.post('/chat', async (req, res) => {
|
||||
try {
|
||||
const { history, message } = req.body;
|
||||
|
||||
if (!API_KEY) {
|
||||
return res.status(500).json({ error: 'AI service not configured' });
|
||||
}
|
||||
|
||||
const ai = new GoogleGenerativeAI(API_KEY);
|
||||
|
||||
const { systemInstruction, userMessage } = req.body;
|
||||
|
||||
const model = ai.getGenerativeModel({
|
||||
model: MODEL_ID,
|
||||
systemInstruction
|
||||
});
|
||||
|
||||
const result = await model.generateContent(userMessage);
|
||||
const response = result.response.text();
|
||||
|
||||
res.json({ response });
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
res.status(500).json({ error: String(error) });
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
50
server/src/routes/auth.ts
Normal file
50
server/src/routes/auth.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
import express from 'express';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import bcrypt from 'bcryptjs';
|
||||
|
||||
const router = express.Router();
|
||||
const prisma = new PrismaClient();
|
||||
const JWT_SECRET = process.env.JWT_SECRET || 'secret';
|
||||
|
||||
|
||||
|
||||
// Login
|
||||
router.post('/login', async (req, res) => {
|
||||
try {
|
||||
const { email, password } = req.body;
|
||||
|
||||
// Admin check (hardcoded for now as per original logic, or we can seed it)
|
||||
// For now, let's stick to DB users, but maybe seed admin if needed.
|
||||
// The original code had hardcoded admin. Let's support that via a special check or just rely on DB.
|
||||
// Let's rely on DB for consistency, but if the user wants the specific admin account, they should register it.
|
||||
// However, to match original behavior, I'll add a check or just let them register 'admin@gymflow.ai'.
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { email },
|
||||
include: { profile: true }
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
return res.status(400).json({ error: 'Invalid credentials' });
|
||||
}
|
||||
|
||||
if (user.isBlocked) {
|
||||
return res.status(403).json({ error: 'Account is blocked' });
|
||||
}
|
||||
|
||||
const isMatch = await bcrypt.compare(password, user.password);
|
||||
if (!isMatch) {
|
||||
return res.status(400).json({ error: 'Invalid credentials' });
|
||||
}
|
||||
|
||||
const token = jwt.sign({ userId: user.id, role: user.role }, JWT_SECRET);
|
||||
const { password: _, ...userSafe } = user;
|
||||
|
||||
res.json({ success: true, user: userSafe, token });
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: 'Server error' });
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
82
server/src/routes/exercises.ts
Normal file
82
server/src/routes/exercises.ts
Normal 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;
|
||||
82
server/src/routes/plans.ts
Normal file
82
server/src/routes/plans.ts
Normal 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';
|
||||
|
||||
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 plans
|
||||
router.get('/', async (req: any, res) => {
|
||||
try {
|
||||
const userId = req.user.userId;
|
||||
const plans = await prisma.workoutPlan.findMany({
|
||||
where: { userId }
|
||||
});
|
||||
res.json(plans);
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: 'Server error' });
|
||||
}
|
||||
});
|
||||
|
||||
// Save plan
|
||||
router.post('/', async (req: any, res) => {
|
||||
try {
|
||||
const userId = req.user.userId;
|
||||
const { id, name, description, exercises } = req.body;
|
||||
|
||||
const existing = await prisma.workoutPlan.findUnique({ where: { id } });
|
||||
|
||||
if (existing) {
|
||||
const updated = await prisma.workoutPlan.update({
|
||||
where: { id },
|
||||
data: { name, description, exercises }
|
||||
});
|
||||
return res.json(updated);
|
||||
} else {
|
||||
const created = await prisma.workoutPlan.create({
|
||||
data: {
|
||||
id,
|
||||
userId,
|
||||
name,
|
||||
description,
|
||||
exercises
|
||||
}
|
||||
});
|
||||
return res.json(created);
|
||||
}
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: 'Server error' });
|
||||
}
|
||||
});
|
||||
|
||||
// Delete plan
|
||||
router.delete('/:id', async (req: any, res) => {
|
||||
try {
|
||||
const userId = req.user.userId;
|
||||
const { id } = req.params;
|
||||
await prisma.workoutPlan.delete({
|
||||
where: { id, userId }
|
||||
});
|
||||
res.json({ success: true });
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: 'Server error' });
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
121
server/src/routes/sessions.ts
Normal file
121
server/src/routes/sessions.ts
Normal file
@@ -0,0 +1,121 @@
|
||||
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';
|
||||
|
||||
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 sessions
|
||||
router.get('/', async (req: any, res) => {
|
||||
try {
|
||||
const userId = req.user.userId;
|
||||
const sessions = await prisma.workoutSession.findMany({
|
||||
where: { userId },
|
||||
include: { sets: { include: { exercise: true } } },
|
||||
orderBy: { startTime: 'desc' }
|
||||
});
|
||||
res.json(sessions);
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: 'Server error' });
|
||||
}
|
||||
});
|
||||
|
||||
// Save session (create or update)
|
||||
router.post('/', async (req: any, res) => {
|
||||
try {
|
||||
const userId = req.user.userId;
|
||||
const { id, startTime, endTime, userBodyWeight, note, sets } = req.body;
|
||||
|
||||
// Check if session exists
|
||||
const existing = await prisma.workoutSession.findUnique({ where: { id } });
|
||||
|
||||
if (existing) {
|
||||
// Update
|
||||
// First delete existing sets to replace them (simplest strategy for now)
|
||||
await prisma.workoutSet.deleteMany({ where: { sessionId: id } });
|
||||
|
||||
const updated = await prisma.workoutSession.update({
|
||||
where: { id },
|
||||
data: {
|
||||
startTime,
|
||||
endTime,
|
||||
userBodyWeight,
|
||||
note,
|
||||
sets: {
|
||||
create: sets.map((s: any, idx: number) => ({
|
||||
exerciseId: s.exerciseId,
|
||||
order: idx,
|
||||
weight: s.weight,
|
||||
reps: s.reps,
|
||||
distanceMeters: s.distanceMeters,
|
||||
durationSeconds: s.durationSeconds,
|
||||
completed: s.completed
|
||||
}))
|
||||
}
|
||||
},
|
||||
include: { sets: true }
|
||||
});
|
||||
return res.json(updated);
|
||||
} else {
|
||||
// Create
|
||||
const created = await prisma.workoutSession.create({
|
||||
data: {
|
||||
id, // Use provided ID or let DB gen? Frontend usually generates UUIDs.
|
||||
userId,
|
||||
startTime,
|
||||
endTime,
|
||||
userBodyWeight,
|
||||
note,
|
||||
sets: {
|
||||
create: sets.map((s: any, idx: number) => ({
|
||||
exerciseId: s.exerciseId,
|
||||
order: idx,
|
||||
weight: s.weight,
|
||||
reps: s.reps,
|
||||
distanceMeters: s.distanceMeters,
|
||||
durationSeconds: s.durationSeconds,
|
||||
completed: s.completed
|
||||
}))
|
||||
}
|
||||
},
|
||||
include: { sets: true }
|
||||
});
|
||||
return res.json(created);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
res.status(500).json({ error: 'Server error' });
|
||||
}
|
||||
});
|
||||
|
||||
// Delete session
|
||||
router.delete('/:id', async (req: any, res) => {
|
||||
try {
|
||||
const userId = req.user.userId;
|
||||
const { id } = req.params;
|
||||
await prisma.workoutSession.delete({
|
||||
where: { id, userId } // Ensure user owns it
|
||||
});
|
||||
res.json({ success: true });
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: 'Server error' });
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
Reference in New Issue
Block a user