Spaces:
Running

xopro1 / server.js
xoproject1's picture
create complete working backend with database for product management + writing- + add/remove product +all other features a web apps's backend must have - Follow Up Deployment
0819992 verified
Raw History Blame Contribute Delete
12.4 kB
```javascript
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const app = express();
const PORT = process.env.PORT || 5000;
const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key-here';
// Middleware
app.use(cors());
app.use(express.json());
app.use('/uploads', express.static('uploads'));
// MongoDB Connection
mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/mindbloom', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
// Database Schemas
const UserSchema = new mongoose.Schema({
username: { type: String, required: true, unique: true },
password: { type: String, required: true },
role: { type: String, enum: ['admin', 'editor'], default: 'editor' },
createdAt: { type: Date, default: Date.now }
});
const ProductSchema = new mongoose.Schema({
name: { type: String, required: true },
description: { type: String, required: true },
price: { type: Number, required: true },
category: { type: String, required: true },
sku: { type: String, required: true, unique: true },
image: { type: String },
status: { type: String, enum: ['active', 'inactive'], default: 'active' },
stock: { type: Number, default: 0 },
features: [String],
createdAt: { type: Date, default: Date.now },
updatedAt: { type: Date, default: Date.now }
});
const ArticleSchema = new mongoose.Schema({
title: { type: String, required: true },
content: { type: String, required: true },
author: { type: String, required: true },
category: { type: String, required: true },
tags: [String],
featuredImage: { type: String },
status: { type: String, enum: ['published', 'draft'], default: 'draft' },
views: { type: Number, default: 0 },
createdAt: { type: Date, default: Date.now },
updatedAt: { type: Date, default: Date.now }
});
const User = mongoose.model('User', UserSchema);
const Product = mongoose.model('Product', ProductSchema);
const Article = mongoose.model('Article', ArticleSchema);
// Create uploads directory if it doesn't exist
if (!fs.existsSync('uploads')) {
fs.mkdirSync('uploads');
}
// Multer configuration for file uploads
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/');
},
filename: function (req, file, cb) {
cb(null, Date.now() + '-' + file.originalname);
}
});
const upload = multer({
storage: storage,
limits: {
fileSize: 5 * 1024 * 1024 // 5MB limit
},
fileFilter: function (req, file, cb) {
if (file.mimetype.startsWith('image/')) {
cb(null, true);
} else {
cb(new Error('Only image files are allowed!'), false);
}
}
});
// Authentication middleware
const authenticateToken = (req, res, next) => {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (!token) {
return res.status(401).json({ error: 'Access token required' });
}
jwt.verify(token, JWT_SECRET, (err, user) => {
if (err) {
return res.status(403).json({ error: 'Invalid token' });
}
req.user = user;
next();
});
};
// Admin middleware
const requireAdmin = (req, res, next) => {
if (req.user.role !== 'admin') {
return res.status(403).json({ error: 'Admin access required' });
}
next();
};
// Routes
// Authentication routes
app.post('/api/auth/login', async (req, res) => {
try {
const { username, password } = req.body;
const user = await User.findOne({ username });
if (!user) {
return res.status(401).json({ error: 'Invalid credentials' });
}
const validPassword = await bcrypt.compare(password, user.password);
if (!validPassword) {
return res.status(401).json({ error: 'Invalid credentials' });
}
const token = jwt.sign(
{ id: user._id, username: user.username, role: user.role },
JWT_SECRET,
{ expiresIn: '24h' }
);
res.json({ token, user: { username: user.username, role: user.role } });
} catch (error) {
res.status(500).json({ error: 'Server error' });
}
});
// Product routes
app.get('/api/products', async (req, res) => {
try {
const { page = 1, limit = 10, category, status } = req.query;
const filter = {};
if (category) filter.category = category;
if (status) filter.status = status;
const products = await Product.find(filter)
.sort({ createdAt: -1 })
.limit(limit * 1)
.skip((page - 1) * limit);
const total = await Product.countDocuments(filter);
res.json({
products,
totalPages: Math.ceil(total / limit),
currentPage: page,
total
});
} catch (error) {
res.status(500).json({ error: 'Server error' });
}
});
app.get('/api/products/:id', async (req, res) => {
try {
const product = await Product.findById(req.params.id);
if (!product) {
return res.status(404).json({ error: 'Product not found' });
}
res.json(product);
} catch (error) {
res.status(500).json({ error: 'Server error' });
}
});
app.post('/api/products', authenticateToken, upload.single('image'), async (req, res) => {
try {
const productData = {
...req.body,
price: parseFloat(req.body.price),
stock: parseInt(req.body.stock)
};
if (req.file) {
productData.image = `/uploads/${req.file.filename}`;
}
const product = new Product(productData);
await product.save();
res.status(201).json(product);
} catch (error) {
if (error.code === 11000) {
res.status(400).json({ error: 'SKU already exists' });
} else {
res.status(500).json({ error: 'Server error' });
}
}
});
app.put('/api/products/:id', authenticateToken, upload.single('image'), async (req, res) => {
try {
const productData = {
...req.body,
price: parseFloat(req.body.price),
stock: parseInt(req.body.stock),
updatedAt: new Date()
};
if (req.file) {
productData.image = `/uploads/${req.file.filename}`;
}
const product = await Product.findByIdAndUpdate(
req.params.id,
productData,
{ new: true, runValidators: true }
);
if (!product) {
return res.status(404).json({ error: 'Product not found' });
}
res.json(product);
} catch (error) {
res.status(500).json({ error: 'Server error' });
}
});
app.delete('/api/products/:id', authenticateToken, async (req, res) => {
try {
const product = await Product.findByIdAndDelete(req.params.id);
if (!product) {
return res.status(404).json({ error: 'Product not found' });
}
// Delete associated image if exists
if (product.image) {
const imagePath = path.join(__dirname, product.image);
if (fs.existsSync(imagePath)) {
fs.unlinkSync(imagePath);
}
}
res.json({ message: 'Product deleted successfully' });
} catch (error) {
res.status(500).json({ error: 'Server error' });
}
});
// Article routes
app.get('/api/articles', async (req, res) => {
try {
const { page = 1, limit = 10, status, category } = req.query;
const filter = {};
if (status) filter.status = status;
if (category) filter.category = category;
const articles = await Article.find(filter)
.sort({ createdAt: -1 })
.limit(limit * 1)
.skip((page - 1) * limit);
const total = await Article.countDocuments(filter);
res.json({
articles,
totalPages: Math.ceil(total / limit),
currentPage: page,
total
});
} catch (error) {
res.status(500).json({ error: 'Server error' });
}
});
app.post('/api/articles', authenticateToken, upload.single('featuredImage'), async (req, res) => {
try {
const articleData = req.body;
if (req.file) {
articleData.featuredImage = `/uploads/${req.file.filename}`;
}
const article = new Article(articleData);
await article.save();
res.status(201).json(article);
} catch (error) {
res.status(500).json({ error: 'Server error' });
}
});
app.put('/api/articles/:id', authenticateToken, upload.single('featuredImage'), async (req, res) => {
try {
const articleData = {
...req.body,
updatedAt: new Date()
};
if (req.file) {
articleData.featuredImage = `/uploads/${req.file.filename}`;
}
const article = await Article.findByIdAndUpdate(
req.params.id,
articleData,
{ new: true, runValidators: true }
);
if (!article) {
return res.status(404).json({ error: 'Article not found' });
}
res.json(article);
} catch (error) {
res.status(500).json({ error: 'Server error' });
}
});
app.delete('/api/articles/:id', authenticateToken, async (req, res) => {
try {
const article = await Article.findByIdAndDelete(req.params.id);
if (!article) {
return res.status(404).json({ error: 'Article not found' });
}
if (article.featuredImage) {
const imagePath = path.join(__dirname, article.featuredImage);
if (fs.existsSync(imagePath)) {
fs.unlinkSync(imagePath);
}
}
res.json({ message: 'Article deleted successfully' });
} catch (error) {
res.status(500).json({ error: 'Server error' });
}
});
// Admin routes
app.get('/api/admin/stats', authenticateToken, requireAdmin, async (req, res) => {
try {
const totalProducts = await Product.countDocuments();
const totalArticles = await Article.countDocuments();
const totalUsers = await User.countDocuments();
const activeProducts = await Product.countDocuments({ status: 'active' });
const publishedArticles = await Article.countDocuments({ status: 'published' });
res.json({
totalProducts,
totalArticles,
totalUsers,
activeProducts,
publishedArticles
});
} catch (error) {
res.status(500).json({ error: 'Server error' });
}
});
app.post('/api/admin/users', authenticateToken, requireAdmin, async (req, res) => {
try {
const { username, password, role } = req.body;
const hashedPassword = await bcrypt.hash(password, 12);
const user = new User({
username,
password: hashedPassword,
role
});
await user.save();
res.status(201).json({ message: 'User created successfully' });
} catch (error) {
if (error.code === 11000) {
res.status(400).json({ error: 'Username already exists' });
} else {
res.status(500).json({ error: 'Server error' });
}
}
});
// Initialize admin user if not exists
async function initializeAdmin() {
try {
const adminExists = await User.findOne({ username: 'admin' });
if (!adminExists) {
const hashedPassword = await bcrypt.hash('admin123', 12);
const admin = new User({
username: 'admin',
password: hashedPassword,
role: 'admin'
});
await admin.save();
console.log('Default admin user created: admin/admin123');
}
} catch (error) {
console.error('Error initializing admin:', error);
}
}
// Start server
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
initializeAdmin();
});
module.exports = app;
```