mirror of
https://github.com/Alvin-Zilverstand/challenge-11.git
synced 2026-03-06 11:06:21 +01:00
Add create-admin script to package.json and set up /api/users route in server.js for user management functionality.
This commit is contained in:
69
routes/auth.js
Normal file
69
routes/auth.js
Normal file
@@ -0,0 +1,69 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const bcrypt = require('bcryptjs');
|
||||
const jwt = require('jsonwebtoken');
|
||||
const User = require('../models/User');
|
||||
|
||||
// Login route
|
||||
router.post('/login', async (req, res) => {
|
||||
try {
|
||||
const { username, password } = req.body;
|
||||
|
||||
// Find user
|
||||
const user = await User.findOne({ username });
|
||||
if (!user) {
|
||||
return res.status(400).json({ message: 'Invalid credentials' });
|
||||
}
|
||||
|
||||
// Check password
|
||||
const isMatch = await bcrypt.compare(password, user.password);
|
||||
if (!isMatch) {
|
||||
return res.status(400).json({ message: 'Invalid credentials' });
|
||||
}
|
||||
|
||||
// Create token
|
||||
const token = jwt.sign(
|
||||
{ id: user._id, role: user.role },
|
||||
process.env.JWT_SECRET || 'your-secret-key',
|
||||
{ expiresIn: '1d' }
|
||||
);
|
||||
|
||||
res.json({ token });
|
||||
} catch (error) {
|
||||
console.error('Login error:', error);
|
||||
res.status(500).json({ message: 'Server error' });
|
||||
}
|
||||
});
|
||||
|
||||
// Register route (for admin use only)
|
||||
router.post('/register', async (req, res) => {
|
||||
try {
|
||||
const { username, password, role } = req.body;
|
||||
|
||||
// Check if user exists
|
||||
let user = await User.findOne({ username });
|
||||
if (user) {
|
||||
return res.status(400).json({ message: 'User already exists' });
|
||||
}
|
||||
|
||||
// Create new user
|
||||
user = new User({
|
||||
username,
|
||||
password,
|
||||
role: role || 'staff',
|
||||
});
|
||||
|
||||
// Hash password
|
||||
const salt = await bcrypt.genSalt(10);
|
||||
user.password = await bcrypt.hash(password, salt);
|
||||
|
||||
await user.save();
|
||||
|
||||
res.status(201).json({ message: 'User created successfully' });
|
||||
} catch (error) {
|
||||
console.error('Registration error:', error);
|
||||
res.status(500).json({ message: 'Server error' });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
65
routes/contacts.js
Normal file
65
routes/contacts.js
Normal file
@@ -0,0 +1,65 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const Contact = require('../models/Contact');
|
||||
|
||||
// Get all contacts for a customer
|
||||
router.get('/customer/:customerId', async (req, res) => {
|
||||
try {
|
||||
const contacts = await Contact.find({ customer: req.params.customerId })
|
||||
.sort({ createdAt: -1 })
|
||||
.populate('user', 'username');
|
||||
res.json(contacts);
|
||||
} catch (error) {
|
||||
console.error('Error fetching contacts:', error);
|
||||
res.status(500).json({ message: 'Server error' });
|
||||
}
|
||||
});
|
||||
|
||||
// Create new contact
|
||||
router.post('/', async (req, res) => {
|
||||
try {
|
||||
const contact = new Contact({
|
||||
...req.body,
|
||||
user: req.user.id, // This will be set by the auth middleware
|
||||
});
|
||||
await contact.save();
|
||||
res.status(201).json(contact);
|
||||
} catch (error) {
|
||||
console.error('Error creating contact:', error);
|
||||
res.status(500).json({ message: 'Server error' });
|
||||
}
|
||||
});
|
||||
|
||||
// Update contact
|
||||
router.put('/:id', async (req, res) => {
|
||||
try {
|
||||
const contact = await Contact.findByIdAndUpdate(
|
||||
req.params.id,
|
||||
req.body,
|
||||
{ new: true }
|
||||
);
|
||||
if (!contact) {
|
||||
return res.status(404).json({ message: 'Contact not found' });
|
||||
}
|
||||
res.json(contact);
|
||||
} catch (error) {
|
||||
console.error('Error updating contact:', error);
|
||||
res.status(500).json({ message: 'Server error' });
|
||||
}
|
||||
});
|
||||
|
||||
// Delete contact
|
||||
router.delete('/:id', async (req, res) => {
|
||||
try {
|
||||
const contact = await Contact.findByIdAndDelete(req.params.id);
|
||||
if (!contact) {
|
||||
return res.status(404).json({ message: 'Contact not found' });
|
||||
}
|
||||
res.json({ message: 'Contact deleted successfully' });
|
||||
} catch (error) {
|
||||
console.error('Error deleting contact:', error);
|
||||
res.status(500).json({ message: 'Server error' });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
74
routes/customers.js
Normal file
74
routes/customers.js
Normal file
@@ -0,0 +1,74 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const Customer = require('../models/Customer');
|
||||
|
||||
// Get all customers
|
||||
router.get('/', async (req, res) => {
|
||||
try {
|
||||
const customers = await Customer.find().sort({ name: 1 });
|
||||
res.json(customers);
|
||||
} catch (error) {
|
||||
console.error('Error fetching customers:', error);
|
||||
res.status(500).json({ message: 'Server error' });
|
||||
}
|
||||
});
|
||||
|
||||
// Get single customer
|
||||
router.get('/:id', async (req, res) => {
|
||||
try {
|
||||
const customer = await Customer.findById(req.params.id);
|
||||
if (!customer) {
|
||||
return res.status(404).json({ message: 'Customer not found' });
|
||||
}
|
||||
res.json(customer);
|
||||
} catch (error) {
|
||||
console.error('Error fetching customer:', error);
|
||||
res.status(500).json({ message: 'Server error' });
|
||||
}
|
||||
});
|
||||
|
||||
// Create customer
|
||||
router.post('/', async (req, res) => {
|
||||
try {
|
||||
const customer = new Customer(req.body);
|
||||
await customer.save();
|
||||
res.status(201).json(customer);
|
||||
} catch (error) {
|
||||
console.error('Error creating customer:', error);
|
||||
res.status(500).json({ message: 'Server error' });
|
||||
}
|
||||
});
|
||||
|
||||
// Update customer
|
||||
router.put('/:id', async (req, res) => {
|
||||
try {
|
||||
const customer = await Customer.findByIdAndUpdate(
|
||||
req.params.id,
|
||||
{ ...req.body, updatedAt: Date.now() },
|
||||
{ new: true }
|
||||
);
|
||||
if (!customer) {
|
||||
return res.status(404).json({ message: 'Customer not found' });
|
||||
}
|
||||
res.json(customer);
|
||||
} catch (error) {
|
||||
console.error('Error updating customer:', error);
|
||||
res.status(500).json({ message: 'Server error' });
|
||||
}
|
||||
});
|
||||
|
||||
// Delete customer
|
||||
router.delete('/:id', async (req, res) => {
|
||||
try {
|
||||
const customer = await Customer.findByIdAndDelete(req.params.id);
|
||||
if (!customer) {
|
||||
return res.status(404).json({ message: 'Customer not found' });
|
||||
}
|
||||
res.json({ message: 'Customer deleted successfully' });
|
||||
} catch (error) {
|
||||
console.error('Error deleting customer:', error);
|
||||
res.status(500).json({ message: 'Server error' });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
118
routes/users.js
Normal file
118
routes/users.js
Normal file
@@ -0,0 +1,118 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const bcrypt = require('bcryptjs');
|
||||
const User = require('../models/User');
|
||||
const auth = require('../middleware/auth');
|
||||
|
||||
// Get all users (admin only)
|
||||
router.get('/', auth, async (req, res) => {
|
||||
try {
|
||||
// Check if user is admin
|
||||
if (req.user.role !== 'admin') {
|
||||
return res.status(403).json({ message: 'Not authorized' });
|
||||
}
|
||||
|
||||
const users = await User.find().select('-password');
|
||||
res.json(users);
|
||||
} catch (error) {
|
||||
console.error('Error fetching users:', error);
|
||||
res.status(500).json({ message: 'Server error' });
|
||||
}
|
||||
});
|
||||
|
||||
// Create new user (admin only)
|
||||
router.post('/', auth, async (req, res) => {
|
||||
try {
|
||||
// Check if user is admin
|
||||
if (req.user.role !== 'admin') {
|
||||
return res.status(403).json({ message: 'Not authorized' });
|
||||
}
|
||||
|
||||
const { username, password, role } = req.body;
|
||||
|
||||
// Check if user exists
|
||||
let user = await User.findOne({ username });
|
||||
if (user) {
|
||||
return res.status(400).json({ message: 'User already exists' });
|
||||
}
|
||||
|
||||
// Create new user
|
||||
user = new User({
|
||||
username,
|
||||
password,
|
||||
role: role || 'staff',
|
||||
});
|
||||
|
||||
// Hash password
|
||||
const salt = await bcrypt.genSalt(10);
|
||||
user.password = await bcrypt.hash(password, salt);
|
||||
|
||||
await user.save();
|
||||
|
||||
// Return user without password
|
||||
const userResponse = user.toObject();
|
||||
delete userResponse.password;
|
||||
|
||||
res.status(201).json(userResponse);
|
||||
} catch (error) {
|
||||
console.error('Error creating user:', error);
|
||||
res.status(500).json({ message: 'Server error' });
|
||||
}
|
||||
});
|
||||
|
||||
// Update user (admin only)
|
||||
router.put('/:id', auth, async (req, res) => {
|
||||
try {
|
||||
// Check if user is admin
|
||||
if (req.user.role !== 'admin') {
|
||||
return res.status(403).json({ message: 'Not authorized' });
|
||||
}
|
||||
|
||||
const { username, password, role } = req.body;
|
||||
const updateData = {};
|
||||
|
||||
if (username) updateData.username = username;
|
||||
if (role) updateData.role = role;
|
||||
if (password) {
|
||||
const salt = await bcrypt.genSalt(10);
|
||||
updateData.password = await bcrypt.hash(password, salt);
|
||||
}
|
||||
|
||||
const user = await User.findByIdAndUpdate(
|
||||
req.params.id,
|
||||
updateData,
|
||||
{ new: true }
|
||||
).select('-password');
|
||||
|
||||
if (!user) {
|
||||
return res.status(404).json({ message: 'User not found' });
|
||||
}
|
||||
|
||||
res.json(user);
|
||||
} catch (error) {
|
||||
console.error('Error updating user:', error);
|
||||
res.status(500).json({ message: 'Server error' });
|
||||
}
|
||||
});
|
||||
|
||||
// Delete user (admin only)
|
||||
router.delete('/:id', auth, async (req, res) => {
|
||||
try {
|
||||
// Check if user is admin
|
||||
if (req.user.role !== 'admin') {
|
||||
return res.status(403).json({ message: 'Not authorized' });
|
||||
}
|
||||
|
||||
const user = await User.findByIdAndDelete(req.params.id);
|
||||
if (!user) {
|
||||
return res.status(404).json({ message: 'User not found' });
|
||||
}
|
||||
|
||||
res.json({ message: 'User deleted successfully' });
|
||||
} catch (error) {
|
||||
console.error('Error deleting user:', error);
|
||||
res.status(500).json({ message: 'Server error' });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
Reference in New Issue
Block a user