File size: 5,680 Bytes
55f89e1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 | ```javascript
require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const path = require('path');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { v4: uuidv4 } = require('uuid');
const app = express();
const PORT = process.env.PORT || 5000;
// Middleware
app.use(cors());
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));
// Database Connection
mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost/tasksphere', {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
}).then(() => console.log('MongoDB connected'))
.catch(err => console.log(err));
// Models
const User = require('./models/User');
const Department = require('./models/Department');
const Task = require('./models/Task');
// Authentication Middleware
const authenticate = (req, res, next) => {
const token = req.header('x-auth-token');
if (!token) return res.status(401).json({ message: 'No token, authorization denied' });
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = decoded.user;
next();
} catch (err) {
res.status(401).json({ message: 'Token is not valid' });
}
};
// Routes
// Auth Routes
app.post('/api/auth/register', async (req, res) => {
const { name, email, password, role } = req.body;
try {
let user = await User.findOne({ email });
if (user) return res.status(400).json({ message: 'User already exists' });
user = new User({ name, email, password, role });
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(password, salt);
await user.save();
const payload = { user: { id: user.id } };
jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: '5h' }, (err, token) => {
if (err) throw err;
res.json({ token });
});
} catch (err) {
console.error(err.message);
res.status(500).send('Server error');
}
});
app.post('/api/auth/login', async (req, res) => {
const { email, password } = req.body;
try {
let user = await User.findOne({ email });
if (!user) return res.status(400).json({ message: 'Invalid credentials' });
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) return res.status(400).json({ message: 'Invalid credentials' });
const payload = { user: { id: user.id } };
jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: '5h' }, (err, token) => {
if (err) throw err;
res.json({ token });
});
} catch (err) {
console.error(err.message);
res.status(500).send('Server error');
}
});
// Department Routes
app.get('/api/departments', authenticate, async (req, res) => {
try {
const departments = await Department.find().populate('manager', 'name');
res.json(departments);
} catch (err) {
console.error(err.message);
res.status(500).send('Server error');
}
});
app.post('/api/departments', authenticate, async (req, res) => {
const { name, description, manager } = req.body;
try {
const department = new Department({ name, description, manager });
await department.save();
res.json(department);
} catch (err) {
console.error(err.message);
res.status(500).send('Server error');
}
});
// Task Routes
app.get('/api/tasks', authenticate, async (req, res) => {
try {
const tasks = await Task.find()
.populate('department', 'name')
.populate('assignedTo', 'name')
.populate('createdBy', 'name');
res.json(tasks);
} catch (err) {
console.error(err.message);
res.status(500).send('Server error');
}
});
app.post('/api/tasks', authenticate, async (req, res) => {
const { title, description, department, assignedTo, dueDate, priority } = req.body;
try {
const task = new Task({
title,
description,
department,
assignedTo,
dueDate,
priority,
status: 'pending',
createdBy: req.user.id
});
await task.save();
res.json(task);
} catch (err) {
console.error(err.message);
res.status(500).send('Server error');
}
});
app.put('/api/tasks/:id', authenticate, async (req, res) => {
const { status, completedDate } = req.body;
try {
let task = await Task.findById(req.params.id);
if (!task) return res.status(404).json({ message: 'Task not found' });
task.status = status || task.status;
if (status === 'completed') {
task.completedDate = completedDate || new Date();
}
await task.save();
res.json(task);
} catch (err) {
console.error(err.message);
res.status(500).send('Server error');
}
});
// User Routes
app.get('/api/users', authenticate, async (req, res) => {
try {
const users = await User.find().select('-password');
res.json(users);
} catch (err) {
console.error(err.message);
res.status(500).send('Server error');
}
});
// Serve static assets in production
if (process.env.NODE_ENV === 'production') {
app.use(express.static('client/build'));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
});
}
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
``` |