798 lines
24 KiB
JavaScript
798 lines
24 KiB
JavaScript
require('dotenv').config();
|
|
const express = require('express');
|
|
const cors = require('cors');
|
|
const bcrypt = require('bcryptjs');
|
|
const jwt = require('jsonwebtoken');
|
|
const bodyParser = require('body-parser');
|
|
const { Sequelize, DataTypes } = require('sequelize');
|
|
const path = require('path');
|
|
const multer = require('multer');
|
|
const fs = require('fs');
|
|
|
|
const app = express();
|
|
app.use(cors());
|
|
app.use(bodyParser.json());
|
|
app.use(express.static('public'));
|
|
|
|
|
|
const authenticateToken = (req, res, next) => {
|
|
const authHeader = req.headers['authorization'];
|
|
const token = authHeader && authHeader.split(' ')[1];
|
|
console.log('Received token:', token);
|
|
if (!token) {
|
|
console.log('No token provided');
|
|
return res.sendStatus(401);
|
|
}
|
|
|
|
jwt.verify(token, process.env.JWT_SECRET, (err, user) => {
|
|
if (err) {
|
|
console.log('Token verification failed:', err);
|
|
return res.sendStatus(403);
|
|
}
|
|
console.log('Token verified, user:', user);
|
|
req.user = user;
|
|
next();
|
|
});
|
|
};
|
|
// Middleware to check admin role
|
|
const authenticateAdmin = async (req, res, next) => {
|
|
console.log('Checking admin role for user:', req.user);
|
|
try {
|
|
const user = await User.findByPk(req.user.id);
|
|
if (user && user.role === 'Admin') {
|
|
console.log('User is admin');
|
|
next();
|
|
} else {
|
|
console.log('User is not admin');
|
|
return res.sendStatus(403); // Forbidden
|
|
}
|
|
} catch (error) {
|
|
console.log('Error verifying admin role:', error);
|
|
return res.sendStatus(500);
|
|
}
|
|
};
|
|
|
|
|
|
const sequelize = new Sequelize({
|
|
dialect: 'sqlite',
|
|
storage: path.join(__dirname, 'database.sqlite'),
|
|
retry: {
|
|
match: [
|
|
/SQLITE_BUSY/,
|
|
],
|
|
name: 'query',
|
|
max: 5
|
|
}
|
|
});
|
|
|
|
const User = sequelize.define('User', {
|
|
username: {
|
|
type: DataTypes.STRING,
|
|
allowNull: false,
|
|
unique: true
|
|
},
|
|
password: {
|
|
type: DataTypes.STRING,
|
|
allowNull: false
|
|
},
|
|
role: {
|
|
type: DataTypes.ENUM('Admin', 'Coach'),
|
|
allowNull: false,
|
|
defaultValue: 'Coach'
|
|
}
|
|
});
|
|
|
|
const Video = sequelize.define('Video', {
|
|
filename: {
|
|
type: DataTypes.STRING,
|
|
allowNull: false
|
|
},
|
|
description: {
|
|
type: DataTypes.STRING,
|
|
allowNull: true
|
|
},
|
|
category: {
|
|
type: DataTypes.STRING,
|
|
allowNull: true
|
|
}
|
|
});
|
|
|
|
const Category = sequelize.define('Category', {
|
|
name: {
|
|
type: DataTypes.STRING,
|
|
allowNull: false,
|
|
unique: true
|
|
}
|
|
});
|
|
|
|
const Workout = sequelize.define('Workout', {
|
|
video1: {
|
|
type: DataTypes.INTEGER,
|
|
allowNull: false,
|
|
references: {
|
|
model: Video,
|
|
key: 'id'
|
|
}
|
|
},
|
|
video2: {
|
|
type: DataTypes.INTEGER,
|
|
allowNull: true, // Allow null values
|
|
references: {
|
|
model: Video,
|
|
key: 'id'
|
|
}
|
|
},
|
|
video3: {
|
|
type: DataTypes.INTEGER,
|
|
allowNull: true,
|
|
references: {
|
|
model: Video,
|
|
key: 'id'
|
|
}
|
|
},
|
|
video4: {
|
|
type: DataTypes.INTEGER,
|
|
allowNull: true,
|
|
references: {
|
|
model: Video,
|
|
key: 'id'
|
|
}
|
|
},
|
|
number1: {
|
|
type: DataTypes.INTEGER,
|
|
allowNull: false
|
|
},
|
|
number2: {
|
|
type: DataTypes.INTEGER,
|
|
allowNull: true // Allow null values
|
|
},
|
|
number3: {
|
|
type: DataTypes.INTEGER,
|
|
allowNull: true
|
|
},
|
|
number4: {
|
|
type: DataTypes.INTEGER,
|
|
allowNull: true
|
|
},
|
|
name: {
|
|
type: DataTypes.STRING,
|
|
allowNull: false
|
|
},
|
|
workoutDate: {
|
|
type: DataTypes.DATE,
|
|
allowNull: false
|
|
},
|
|
createdAt: {
|
|
type: DataTypes.DATE,
|
|
allowNull: false,
|
|
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP')
|
|
}
|
|
}, {
|
|
timestamps: true,
|
|
updatedAt: false
|
|
});
|
|
|
|
const Timer = sequelize.define('Timer', {
|
|
totalTime: {
|
|
type: DataTypes.INTEGER,
|
|
allowNull: false
|
|
},
|
|
setTime: {
|
|
type: DataTypes.INTEGER,
|
|
allowNull: false
|
|
},
|
|
restTime: {
|
|
type: DataTypes.INTEGER,
|
|
allowNull: false
|
|
},
|
|
moveTime: {
|
|
type: DataTypes.INTEGER,
|
|
allowNull: false
|
|
},
|
|
setCount: {
|
|
type: DataTypes.INTEGER,
|
|
allowNull: false
|
|
},
|
|
exerciseCount: {
|
|
type: DataTypes.INTEGER,
|
|
allowNull: false
|
|
},
|
|
lapCount: {
|
|
type: DataTypes.INTEGER,
|
|
allowNull: false
|
|
},
|
|
createdAt: {
|
|
type: DataTypes.DATE,
|
|
allowNull: false,
|
|
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP')
|
|
}
|
|
}, {
|
|
timestamps: true,
|
|
updatedAt: false
|
|
});
|
|
|
|
Workout.belongsTo(Video, { as: 'video1Details', foreignKey: 'video1' });
|
|
Workout.belongsTo(Video, { as: 'video2Details', foreignKey: 'video2' });
|
|
Workout.belongsTo(Video, { as: 'video3Details', foreignKey: 'video3' });
|
|
Workout.belongsTo(Video, { as: 'video4Details', foreignKey: 'video4' });
|
|
|
|
//Crossfit DB
|
|
const CrossfitWorkout = sequelize.define('CrossfitWorkout', {
|
|
name: {
|
|
type: DataTypes.STRING,
|
|
allowNull: false
|
|
},
|
|
workoutDate: {
|
|
type: DataTypes.DATE,
|
|
allowNull: false
|
|
},
|
|
workoutItems: {
|
|
type: DataTypes.JSON, // Storing as JSON to handle ordered lists
|
|
allowNull: false
|
|
},
|
|
createdAt: {
|
|
type: DataTypes.DATE,
|
|
allowNull: false,
|
|
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP')
|
|
}
|
|
}, {
|
|
timestamps: true,
|
|
updatedAt: false
|
|
});
|
|
|
|
sequelize.sync().then(() => {
|
|
console.log('Database synchronized!');
|
|
const initialCategories = [
|
|
'Arm Exercises',
|
|
'Leg Exercises',
|
|
'Push Exercises',
|
|
'Pull Exercises',
|
|
'Cardio Exercises',
|
|
'Core Exercises'
|
|
];
|
|
initialCategories.forEach(async (name) => {
|
|
try {
|
|
const [category, created] = await Category.findOrCreate({ where: { name } });
|
|
if (created) {
|
|
console.log(`Category '${name}' created`);
|
|
}
|
|
} catch (error) {
|
|
console.error(`Failed to create initial category '${name}':`, error);
|
|
}
|
|
});
|
|
});
|
|
|
|
const storage = multer.diskStorage({
|
|
destination: './public/uploads/',
|
|
filename: (req, file, cb) => {
|
|
cb(null, Date.now() + path.extname(file.originalname));
|
|
}
|
|
});
|
|
const upload = multer({ storage: storage });
|
|
|
|
// Route definitions...
|
|
app.get('/', (req, res) => {
|
|
res.sendFile(path.join(__dirname, 'public', 'index.html'));
|
|
});
|
|
|
|
app.get('/register', (req, res) => {
|
|
res.sendFile(path.join(__dirname, 'public', 'register.html'));
|
|
});
|
|
|
|
app.get('/dashboard.html', authenticateToken, (req, res) => {
|
|
res.sendFile(path.join(__dirname, 'public', 'dashboard.html'));
|
|
});
|
|
|
|
app.get('/upload.html', authenticateToken, (req, res) => {
|
|
res.sendFile(path.join(__dirname, 'public', 'upload.html'));
|
|
});
|
|
|
|
app.get('/create-workout.html', authenticateToken, (req, res) => {
|
|
res.sendFile(path.join(__dirname, 'public', 'create-workout.html'));
|
|
});
|
|
|
|
app.get('/videos.html', authenticateToken, (req, res) => {
|
|
res.sendFile(path.join(__dirname, 'public', 'videos.html'));
|
|
});
|
|
|
|
app.get('/workouts.html', authenticateToken, (req, res) => {
|
|
res.sendFile(path.join(__dirname, 'public', 'workouts.html'));
|
|
});
|
|
|
|
app.get('/categories.html', authenticateToken, (req, res) => {
|
|
res.sendFile(path.join(__dirname, 'public', 'categories.html'));
|
|
});
|
|
|
|
app.get('/create-timer.html', authenticateToken, (req, res) => {
|
|
res.sendFile(path.join(__dirname, 'public', 'create-timer.html'));
|
|
});
|
|
|
|
app.get('/manage-timers.html', authenticateToken, (req, res) => {
|
|
res.sendFile(path.join(__dirname, 'public', 'manage-timers.html'));
|
|
});
|
|
|
|
app.get('/timer.html', authenticateToken, (req, res) => {
|
|
res.sendFile(path.join(__dirname, 'public', 'timer.html'));
|
|
});
|
|
|
|
app.get('/workout/:id', authenticateToken, (req, res) => {
|
|
res.sendFile(path.join(__dirname, 'public', 'workout.html'));
|
|
});
|
|
|
|
app.get('/create-crossfit-workout.html', authenticateToken, (req, res) => {
|
|
res.sendFile(path.join(__dirname, 'public', 'create-crossfit-workout.html'));
|
|
});
|
|
|
|
app.get('/crossfit-workouts.html', authenticateToken, (req, res) => {
|
|
res.sendFile(path.join(__dirname, 'public', 'crossfit-workouts.html'));
|
|
});
|
|
|
|
// Route to fetch all users
|
|
app.get('/users', authenticateToken, authenticateAdmin, async (req, res) => {
|
|
try {
|
|
const users = await User.findAll({ attributes: ['id', 'username', 'role'] });
|
|
res.json(users);
|
|
} catch (error) {
|
|
console.error('Error fetching users:', error);
|
|
res.status(500).send('Internal Server Error');
|
|
}
|
|
});
|
|
|
|
// Create user endpoint
|
|
app.post('/users', authenticateToken, authenticateAdmin, async (req, res) => {
|
|
const { username, password, role } = req.body;
|
|
const hashedPassword = await bcrypt.hash(password, 10);
|
|
try {
|
|
const user = await User.create({ username, password: hashedPassword, role });
|
|
res.json(user);
|
|
} catch (error) {
|
|
console.error('Error creating user:', error);
|
|
res.status(400).send('Username already taken');
|
|
}
|
|
});
|
|
|
|
// Delete user endpoint
|
|
app.delete('/users/:id', authenticateToken, authenticateAdmin, async (req, res) => {
|
|
try {
|
|
const user = await User.findByPk(req.params.id);
|
|
if (user) {
|
|
await user.destroy();
|
|
res.send('User deleted');
|
|
} else {
|
|
res.status(404).send('User not found');
|
|
}
|
|
} catch (error) {
|
|
console.error('Error deleting user:', error);
|
|
res.status(500).send('Internal Server Error');
|
|
}
|
|
});
|
|
|
|
// Change role endpoint
|
|
app.put('/users/:id/role', authenticateToken, authenticateAdmin, async (req, res) => {
|
|
const { role } = req.body;
|
|
try {
|
|
const user = await User.findByPk(req.params.id);
|
|
if (user) {
|
|
user.role = role;
|
|
await user.save();
|
|
res.json(user);
|
|
} else {
|
|
res.status(404).send('User not found');
|
|
}
|
|
} catch (error) {
|
|
console.error('Error changing role:', error);
|
|
res.status(500).send('Internal Server Error');
|
|
}
|
|
});
|
|
|
|
// Reset password endpoint
|
|
app.put('/users/:id/password', authenticateToken, authenticateAdmin, async (req, res) => {
|
|
const { password } = req.body;
|
|
const hashedPassword = await bcrypt.hash(password, 10);
|
|
try {
|
|
const user = await User.findByPk(req.params.id);
|
|
if (user) {
|
|
user.password = hashedPassword;
|
|
await user.save();
|
|
res.json(user);
|
|
} else {
|
|
res.status(404).send('User not found');
|
|
}
|
|
} catch (error) {
|
|
console.error('Error resetting password:', error);
|
|
res.status(500).send('Internal Server Error');
|
|
}
|
|
});
|
|
app.get('/workout-data/:id', authenticateToken, async (req, res) => {
|
|
try {
|
|
const workout = await Workout.findByPk(req.params.id, {
|
|
include: [
|
|
{ model: Video, as: 'video1Details', attributes: ['filename'] },
|
|
{ model: Video, as: 'video2Details', attributes: ['filename'] },
|
|
{ model: Video, as: 'video3Details', attributes: ['filename'] },
|
|
{ model: Video, as: 'video4Details', attributes: ['filename'] }
|
|
]
|
|
});
|
|
|
|
if (!workout) {
|
|
return res.status(404).send('Workout not found');
|
|
}
|
|
|
|
// Respond with the workout and its associated videos
|
|
res.json({
|
|
video1: workout.video1Details ? workout.video1Details.filename : null,
|
|
video2: workout.video2Details ? workout.video2Details.filename : null,
|
|
video3: workout.video3Details ? workout.video3Details.filename : null,
|
|
video4: workout.video4Details ? workout.video4Details.filename : null,
|
|
number1: workout.number1,
|
|
number2: workout.number2,
|
|
number3: workout.number3,
|
|
number4: workout.number4
|
|
});
|
|
} catch (error) {
|
|
console.error('Error fetching workout data:', error);
|
|
res.status(500).send('Internal Server Error');
|
|
}
|
|
});
|
|
// Profile route to return user info
|
|
app.get('/profile', authenticateToken, async (req, res) => {
|
|
const user = await User.findByPk(req.user.id);
|
|
if (user) {
|
|
console.log('User fetched:', user);
|
|
res.json({ id: user.id, username: user.username, role: user.role });
|
|
} else {
|
|
res.status(404).send('User not found');
|
|
}
|
|
});
|
|
|
|
|
|
app.get('/workouts-details', authenticateToken, async (req, res) => {
|
|
try {
|
|
const page = parseInt(req.query.page) || 1; // Default to page 1
|
|
const limit = parseInt(req.query.limit) || 50; // Default to 20 items per page
|
|
const offset = (page - 1) * limit;
|
|
|
|
const { count, rows: workouts } = await Workout.findAndCountAll({
|
|
include: [
|
|
{ model: Video, as: 'video1Details', attributes: ['filename', 'description', 'category'] },
|
|
{ model: Video, as: 'video2Details', attributes: ['filename', 'description', 'category'] },
|
|
{ model: Video, as: 'video3Details', attributes: ['filename', 'description', 'category'] },
|
|
{ model: Video, as: 'video4Details', attributes: ['filename', 'description', 'category'] }
|
|
],
|
|
attributes: ['id', 'name', 'createdAt'],
|
|
offset,
|
|
limit
|
|
});
|
|
|
|
res.json({
|
|
workouts,
|
|
total: count,
|
|
totalPages: Math.ceil(count / limit),
|
|
currentPage: page
|
|
});
|
|
} catch (error) {
|
|
console.error('Error fetching workouts:', error);
|
|
res.status(500).send('Internal Server Error');
|
|
}
|
|
});
|
|
app.get('/today-workouts', authenticateToken, async (req, res) => {
|
|
try {
|
|
const today = new Date();
|
|
today.setHours(0, 0, 0, 0);
|
|
const tomorrow = new Date(today);
|
|
tomorrow.setDate(today.getDate() + 1);
|
|
|
|
const workouts = await Workout.findAll({
|
|
where: {
|
|
workoutDate: {
|
|
[Sequelize.Op.gte]: today,
|
|
[Sequelize.Op.lt]: tomorrow
|
|
}
|
|
},
|
|
include: [
|
|
{ model: Video, as: 'video1Details', attributes: ['filename', 'description', 'category'] },
|
|
{ model: Video, as: 'video2Details', attributes: ['filename', 'description', 'category'] },
|
|
{ model: Video, as: 'video3Details', attributes: ['filename', 'description', 'category'] },
|
|
{ model: Video, as: 'video4Details', attributes: ['filename', 'description', 'category'] }
|
|
]
|
|
});
|
|
res.json(workouts);
|
|
} catch (error) {
|
|
console.error('Error fetching workouts:', error);
|
|
res.status(500).send('Internal Server Error');
|
|
}
|
|
});
|
|
app.get('/total-workouts', authenticateToken, async (req, res) => {
|
|
try {
|
|
const totalWorkouts = await Workout.count();
|
|
res.json({ count: totalWorkouts });
|
|
} catch (error) {
|
|
console.error('Error fetching total workouts:', error);
|
|
res.status(500).send('Internal Server Error');
|
|
}
|
|
});
|
|
|
|
app.get('/videos', authenticateToken, async (req, res) => {
|
|
try {
|
|
const { category } = req.query;
|
|
const whereClause = category && category !== 'All' ? { category } : {};
|
|
const videos = await Video.findAll({
|
|
where: whereClause,
|
|
attributes: ['id', 'filename', 'description', 'category'],
|
|
order: [['category', 'ASC']]
|
|
});
|
|
res.json(videos);
|
|
} catch (error) {
|
|
console.error('Error fetching videos:', error);
|
|
res.status(500).send('Internal Server Error');
|
|
}
|
|
});
|
|
|
|
app.get('/categories', authenticateToken, async (req, res) => {
|
|
try {
|
|
const categories = await Category.findAll({ attributes: ['id', 'name'] });
|
|
res.json(categories);
|
|
} catch (error) {
|
|
console.error('Error fetching categories:', error);
|
|
res.status(500).send('Internal Server Error');
|
|
}
|
|
});
|
|
|
|
app.post('/categories', authenticateToken, async (req, res) => {
|
|
const { name } = req.body;
|
|
try {
|
|
const category = await Category.create({ name });
|
|
res.json(category);
|
|
} catch (error) {
|
|
console.error('Error adding category:', error);
|
|
res.status(500).send('Internal Server Error');
|
|
}
|
|
});
|
|
|
|
app.delete('/categories/:id', authenticateToken, async (req, res) => {
|
|
try {
|
|
const category = await Category.findByPk(req.params.id);
|
|
if (category) {
|
|
await category.destroy();
|
|
res.send('Category deleted');
|
|
} else {
|
|
res.status(404).send('Category not found');
|
|
}
|
|
} catch (error) {
|
|
console.error('Error deleting category:', error);
|
|
res.status(500).send('Internal Server Error');
|
|
}
|
|
});
|
|
|
|
app.post('/register', async (req, res) => {
|
|
const { username, password } = req.body;
|
|
const hashedPassword = await bcrypt.hash(password, 10);
|
|
try {
|
|
const user = await User.create({ username, password: hashedPassword });
|
|
res.send('User registered');
|
|
} catch (error) {
|
|
console.error('Error registering user:', error);
|
|
res.status(400).send('Username already taken');
|
|
}
|
|
});
|
|
|
|
app.post('/login', async (req, res) => {
|
|
const { username, password } = req.body;
|
|
const user = await User.findOne({ where: { username } });
|
|
if (!user) {
|
|
console.log('User not found');
|
|
return res.status(400).send('User not found');
|
|
}
|
|
const isMatch = await bcrypt.compare(password, user.password);
|
|
if (!isMatch) {
|
|
console.log('Invalid credentials');
|
|
return res.status(400).send('Invalid credentials');
|
|
}
|
|
const token = jwt.sign({ id: user.id }, process.env.JWT_SECRET, {expiresIn: '7d'});
|
|
console.log('Token generated:', token);
|
|
res.json({ token });
|
|
});
|
|
|
|
app.post('/upload', authenticateToken, upload.single('video'), async (req, res) => {
|
|
console.log('Upload attempt');
|
|
console.log('Request body:', req.body);
|
|
console.log('Uploaded file:', req.file);
|
|
|
|
const { description, category } = req.body;
|
|
if (!req.file) {
|
|
return res.status(400).send('No file uploaded');
|
|
}
|
|
|
|
try {
|
|
const video = await Video.create({ filename: req.file.filename, description, category });
|
|
res.send('Video uploaded');
|
|
} catch (error) {
|
|
console.error('Error uploading video:', error);
|
|
res.status(500).send('Internal Server Error');
|
|
}
|
|
});
|
|
|
|
app.post('/create-workout', authenticateToken, async (req, res) => {
|
|
const { name, workoutDate, video1, video2, video3, video4, number1, number2, number3, number4 } = req.body;
|
|
|
|
try {
|
|
const workout = await Workout.create({
|
|
name,
|
|
workoutDate,
|
|
video1,
|
|
number1,
|
|
video2: video2 || null,
|
|
number2: number2 || null,
|
|
video3: video3 || null,
|
|
number3: number3 || null,
|
|
video4: video4 || null,
|
|
number4: number4 || null,
|
|
});
|
|
res.json({ workoutId: workout.id });
|
|
} catch (error) {
|
|
console.error('Error creating workout:', error);
|
|
res.status(500).send('Internal Server Error');
|
|
}
|
|
});
|
|
|
|
// Fetch all CrossFit workouts
|
|
app.get('/crossfit-workouts', authenticateToken, async (req, res) => {
|
|
try {
|
|
const workouts = await CrossfitWorkout.findAll();
|
|
res.json(workouts);
|
|
} catch (error) {
|
|
console.error('Error fetching CrossFit workouts:', error);
|
|
res.status(500).send('Internal Server Error');
|
|
}
|
|
});
|
|
|
|
// Endpoint to handle creation of CrossFit workout
|
|
app.post('/create-crossfit-workout', authenticateToken, async (req, res) => {
|
|
console.log('Received request body:', req.body);
|
|
const { name, workoutDate, rawText } = req.body;
|
|
|
|
try {
|
|
if (!name || !workoutDate || !rawText) {
|
|
console.error('Validation failed: Missing required fields');
|
|
return res.status(400).send('All fields are required');
|
|
}
|
|
|
|
// Convert raw text into an ordered list
|
|
const workoutItems = rawText.split('\n').map(item => item.trim()).filter(item => item);
|
|
|
|
const crossfitWorkout = await CrossfitWorkout.create({
|
|
name,
|
|
workoutDate,
|
|
workoutItems
|
|
});
|
|
|
|
res.json({ workoutId: crossfitWorkout.id });
|
|
} catch (error) {
|
|
console.error('Error creating CrossFit workout:', error.message); // Log the error message
|
|
console.error('Error details:', error); // Log the entire error object
|
|
res.status(500).send('Internal Server Error');
|
|
}
|
|
});
|
|
|
|
|
|
app.post('/create-timer', authenticateToken, async (req, res) => {
|
|
console.log('Create timer request received:', req.body);
|
|
const { totalTime, setTime, restTime, moveTime, setCount, exerciseCount, lapCount } = req.body;
|
|
try {
|
|
const timer = await Timer.create({ totalTime, setTime, restTime, moveTime, setCount, exerciseCount, lapCount });
|
|
console.log('Timer created:', timer);
|
|
res.json(timer);
|
|
} catch (error) {
|
|
console.error('Error creating timer:', error);
|
|
res.status(500).send('Internal Server Error');
|
|
}
|
|
});
|
|
|
|
app.get('/timers', authenticateToken, async (req, res) => {
|
|
try {
|
|
const timers = await Timer.findAll();
|
|
res.json(timers);
|
|
} catch (error) {
|
|
console.error('Error fetching timers:', error);
|
|
res.status(500).send('Internal Server Error');
|
|
}
|
|
});
|
|
|
|
app.get('/timers/:id', authenticateToken, async (req, res) => {
|
|
try {
|
|
const timer = await Timer.findByPk(req.params.id);
|
|
if (!timer) {
|
|
return res.status(404).send('Timer not found');
|
|
}
|
|
res.json(timer);
|
|
} catch (error) {
|
|
console.error('Error fetching timer:', error);
|
|
res.status(500).send('Internal Server Error');
|
|
}
|
|
});
|
|
|
|
app.delete('/timers/:id', authenticateToken, async (req, res) => {
|
|
try {
|
|
const timer = await Timer.findByPk(req.params.id);
|
|
if (timer) {
|
|
await timer.destroy();
|
|
res.send('Timer deleted');
|
|
} else {
|
|
res.status(404).send('Timer not found');
|
|
}
|
|
} catch (error) {
|
|
console.error('Error deleting timer:', error);
|
|
res.status(500).send('Internal Server Error');
|
|
}
|
|
});
|
|
|
|
app.delete('/videos/:id', authenticateToken, async (req, res) => {
|
|
try {
|
|
const video = await Video.findByPk(req.params.id);
|
|
if (video) {
|
|
await video.destroy();
|
|
res.send('Video deleted');
|
|
} else {
|
|
res.status(404).send('Video not found');
|
|
}
|
|
} catch (error) {
|
|
console.error('Error deleting video:', error);
|
|
res.status(500).send('Internal Server Error');
|
|
}
|
|
});
|
|
|
|
app.delete('/workouts/:id', authenticateToken, async (req, res) => {
|
|
try {
|
|
const workout = await Workout.findByPk(req.params.id);
|
|
if (workout) {
|
|
await workout.destroy();
|
|
res.send('Workout deleted');
|
|
} else {
|
|
res.status(404).send('Workout not found');
|
|
}
|
|
} catch (error) {
|
|
console.error('Error deleting workout:', error);
|
|
res.status(500).send('Internal Server Error');
|
|
}
|
|
});
|
|
|
|
// Endpoint to delete a CrossFit workout
|
|
app.delete('/crossfit-workout/:id', authenticateToken, authenticateAdmin, async (req, res) => {
|
|
try {
|
|
const workout = await CrossfitWorkout.findByPk(req.params.id);
|
|
if (!workout) {
|
|
return res.status(404).send('Workout not found');
|
|
}
|
|
await workout.destroy();
|
|
res.send('Workout deleted successfully');
|
|
} catch (error) {
|
|
console.error('Error deleting CrossFit workout:', error);
|
|
res.status(500).send('Internal Server Error');
|
|
}
|
|
});
|
|
|
|
|
|
// Endpoint to handle logo upload
|
|
app.post('/upload-logo', authenticateToken, authenticateAdmin, upload.single('logo'), (req, res) => {
|
|
if (!req.file) {
|
|
return res.status(400).send('No file uploaded');
|
|
}
|
|
|
|
const logoPath = path.join(__dirname, 'public', 'VitLogo.png');
|
|
fs.rename(req.file.path, logoPath, (err) => {
|
|
if (err) {
|
|
console.error('Error replacing logo:', err);
|
|
return res.status(500).send('Internal Server Error');
|
|
}
|
|
res.send('Logo uploaded');
|
|
});
|
|
});
|
|
app.post('/logout', authenticateToken, (req, res) => {
|
|
// Clear the token on the client side
|
|
res.json({ message: 'Logged out successfully' });
|
|
});
|
|
|
|
app.listen(3000, () => {
|
|
console.log('Server running on http://localhost:3000');
|
|
});
|