Example output
Creating a comprehensive JavaScript-based Content Management System (CMS) with user authentication involves several components and technologies. For the sake of scalability and security, we'll use a popular JavaScript runtime environment, Node.js, along with Express.js as the server framework, MongoDB as the database, and JSON Web Tokens (JWT) for authentication. Additionally, we'll use bcrypt for password hashing.
Here's a simplified example to get you started. Note that in a real-world scenario, you should consider more advanced security measures, such as HTTPS, input validation, and more.
### Prerequisites:
- Node.js installed
- MongoDB installed and running
### Dependencies:
- Express.js
- Mongoose (MongoDB ODM)
- Bcrypt.js (for password hashing)
- JSON Web Token (JWT)
- Body-parser
```bash
npm init -y
npm install express mongoose bcryptjs jsonwebtoken body-parser
```
### Project Structure:
```
/project-root
|-- /models
| |-- user.js
|-- /routes
| |-- auth.js
| |-- content.js
|-- app.js
|-- .env
```
### /models/user.js
```javascript
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
username: { type: String, unique: true, required: true },
password: { type: String, required: true }
});
module.exports = mongoose.model('User', userSchema);
```
### /routes/auth.js
```javascript
const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const User = require('../models/user');
router.post('/register', async (req, res) => {
try {
const { username, password } = req.body;
const hashedPassword = await bcrypt.hash(password, 10);
const user = new User({ username, password: hashedPassword });
await user.save();
res.status(201).json({ message: 'User registered successfully' });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
router.post('/login', async (req, res) => {
try {
const { username, password } = req.body;
const user = await User.findOne({ username });
if (!user) {
return res.status(401).json({ message: 'Authentication failed' });
}
const isPasswordValid = await bcrypt.compare(password, user.password);
if (!isPasswordValid) {
return res.status(401).json({ message: 'Authentication failed' });
}
const token = jwt.sign({ userId: user._id }, process.env.JWT_SECRET, { expiresIn: '1h' });
res.status(200).json({ token, expiresIn: 3600 });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
module.exports = router;
```
### /routes/content.js
```javascript
const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const User = require('../models/user');
const authenticateUser = async (req, res, next) => {
try {
const token = req.headers.authorization.split(' ')[1];
const decodedToken = jwt.verify(token, process.env.JWT_SECRET);
req.userData = { userId: decodedToken.userId };
next();
} catch (error) {
res.status(401).json({ message: 'Authentication failed' });
}
};
router.get('/content', authenticateUser, async (req, res) => {
try {
const user = await User.findById(req.userData.userId);
res.status(200).json({ content: 'Your protected content', user });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
module.exports = router;
```
### /app.js
```javascript
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
require('dotenv').config();
const authRoutes = require('./routes/auth');
const contentRoutes = require('./routes/content');
const app = express();
const PORT = process.env.PORT || 3000;
app.use(bodyParser.json());
// Connect to MongoDB
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => {
console.log('Connected to MongoDB');
})
.catch((error) => {
console.error('MongoDB connection failed:', error.message);
});
// Routes
app.use('/auth', authRoutes);
app.use('/api', contentRoutes);
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
```
### /.env
```env
MONGO_URI=mongodb://localhost:27017/your-database
JWT_SECRET=your-secret-key
PORT=3000
```
Replace `"your-database"` and `"your-secret-key"` with your MongoDB database connection URI and a secure JWT secret key.
This is a basic setup to get you started. In a production environment, consider using environment variables for sensitive information, implementing HTTPS, input validation, error handling, and more advanced security measures. Additionally, you might want to explore frameworks like Express.js to structure your application better as it grows.