npm install validator bcrypt jsonwebtoken
models/users.js
const mongoose = require('./database'); // Import the MongoDB connection
const validator = require('validator');
const userSchema = new mongoose.Schema({
username: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
validate: {
validator: validator.isEmail, // Use the isEmail method from the validator library
message: 'Invalid email format',
},
},
password: {
type: String,
required: true,
},
// Add more fields as needed (e.g., profile information)
});
// Create a User model from the schema
const User = mongoose.model('User', userSchema);
module.exports = User;
middleware/authMiddleware.js
// middleware/authMiddleware.js
const jwt = require('jsonwebtoken');
const authenticate = (req, res, next) => {
const token = req.headers.authorization;
if (!token) {
return res.status(401).json({ error: 'Unauthorized' });
}
jwt.verify(token, 'your-secret-key', (err, decoded) => {
if (err) {
return res.status(401).json({ error: 'Unauthorized' });
}
req.userId = decoded.userId;
next();
});
};
module.exports = authenticate;
// Import necessary libraries
const express = require('express');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const User = require('../models/users'); // Import your user model
const router = express.Router();
const authenticate = require('../middleware/authMiddleware'); // Import your authentication middleware
// Register a new user
router.post('/register', async (req, res) => {
try {
const { username, email, password } = req.body;
// Hash the password before saving it to the database
const hashedPassword = await bcrypt.hash(password, 10);
const user = new User({ username, email, password: hashedPassword });
await user.save();
res.status(201).json({ message: 'User registered successfully' });
} catch (error) {
res.status(400).json({ error: 'Registration failed' });
}
});
// User login
router.post('/login', async (req, res) => {
try {
const { email, password } = req.body;
const user = await User.findOne({ email });
if (!user) {
return res.status(401).json({ error: 'Invalid credentials' });
}
// Compare the provided password with the stored hashed password
const isPasswordValid = await bcrypt.compare(password, user.password);
if (!isPasswordValid) {
return res.status(401).json({ error: 'Invalid credentials' });
}
const token = jwt.sign({ userId: user._id }, 'your-secret-key', { expiresIn: '1h' });
res.status(200).json({ token });
} catch (error) {
res.status(400).json({ error: 'Login failed' });
}
});
// GET User Profile Route
router.get('/profile', authenticate, async (req, res) => {
try {
const user = await User.findById(req.userId);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
res.status(200).json(user);
} catch (error) {
res.status(500).json({ error: 'Error fetching user profile' });
}
});
// PUT Update User Profile Route
router.put('/profile', authenticate, async (req, res) => {
try {
const { username, email } = req.body;
const updatedUser = await User.findByIdAndUpdate(
req.userId,
{ username, email },
{ new: true }
);
if (!updatedUser) {
return res.status(404).json({ error: 'User not found' });
}
res.status(200).json(updatedUser);
} catch (error) {
res.status(500).json({ error: 'Error updating user profile' });
}
});
// DELETE User Account Route
router.delete('/profile', authenticate, async (req, res) => {
try {
const deletedUser = await User.findByIdAndRemove(req.userId);
if (!deletedUser) {
return res.status(404).json({ error: 'User not found' });
}
res.status(200).json({ message: 'User account deleted' });
} catch (error) {
res.status(500).json({ error: 'Error deleting user account' });
}
});
module.exports = router;