Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
105 changes: 104 additions & 1 deletion app/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');
const swaggerDocument = YAML.load('./swagger.yaml'); // Replace './swagger.yaml' with the path to your Swagger file
const swaggerDocument = YAML.load('./swagger.yaml');
const app = express();
require("dotenv").config();

app.use(bodyParser.json());

Expand All @@ -13,6 +14,8 @@ const users = require('../initial-data/users.json');
const brands = require('../initial-data/brands.json');
const products = require('../initial-data/products.json');

const jwtSecret = process.env.jwtSecret;

// Error handling
app.use((err, req, res, next) => {
console.error(err.stack);
Expand All @@ -28,4 +31,104 @@ app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});

// Middleware for authentication
const authenticateToken = (req, res, next) => {
const token = req.headers['authorization'];
if (!token) return res.status(401).json({ error: 'Unauthorized' });

jwt.verify(token, jwtSecret, (err, user) => {
if (err) return res.status(401).json({ error: 'Unauthorized' });
req.user = user;
next();
Comment on lines +40 to +42
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

beware your code alignment

});
};

// Routes
app.get('/brands', (req, res) => {
res.json(brands);
});

app.get('/brands/:id/products', (req, res) => {
const brandId = req.params.id;
const brandProducts = products.filter(product => product.categoryId === brandId);
if (brandProducts.length === 0) {
return res.status(404).json({ error: 'Brand not found' });
}
res.json(brandProducts);
});

app.get('/products', (req, res) => {
res.json(products);
});

app.post('/login', (req, res) => {
if (req.body.username === undefined || req.body.password === undefined) {
return res.status(400).json({ error: "Username and password are required" });
}
const { username, password } = req.body;
const user = users.find(
(u) => u.login.username === username && u.login.password === password
);
if (!user) {
return res.status(401).json({ error: "Invalid credentials" });
}
const token = jwt.sign({ username: user.login.username }, jwtSecret, {
expiresIn: "1h",
});
res.json({ token });
});

app.get('/me/cart', authenticateToken, (req, res) => {
const userCart = users.find(u => u.login.username === req.user.username).cart;
if (!userCart) {
return res.status(401).json({ error: "Unauthorized" });
}
res.json(userCart);
});

app.post('/me/cart', authenticateToken, (req, res) => {
const { id } = req.body;
const userCart = users.find((u) => u.login.username === req.user.username).cart;
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the user isn’t found, your code will throw an error on .cart access.

if (!userCart) {
return res.status(401).json({ error: "Unauthorized" });
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is 404, not 401.
401 Unauthorized is a bit misleading if the cart doesn’t exist — if users.find() returns undefined, that’s more of a 404 Not Found or 403 Forbidden.

}
const product = products.find((item) => item.id === id);
const existingProduct = userCart.find((item) => item.id === id);
if (existingProduct) {
existingProduct.quantity += 1;
} else {
userCart.push({ ...product, quantity: 1 });
}
res.json(userCart);
});

app.delete('/me/cart/:productId', authenticateToken, (req, res) => {
const productId = req.params.productId;
const user = users.find(u => u.id === req.user.id);
if (!user) {
return res.status(401).json({ error: 'Unauthorized' });
}
const productIndex = user.cart.findIndex(item => item.id === productId);
if (productIndex === -1) {
return res.status(404).json({ error: 'Product not found in cart' });
}
user.cart.splice(productIndex, 1);
res.json(user.cart);
});

app.post('/me/cart/:productId', authenticateToken, (req, res) => {
const productId = req.params.id;
const { quantity } = req.body;
const user = users.find(u => u.id === req.user.id);
if (!user) {
return res.status(401).json({ error: 'Unauthorized' });
}
const product = user.cart.find(item => item.productId === productId);
if (!product) {
return res.status(404).json({ error: 'Product not found in cart' });
}
product.quantity = quantity;
res.json(user.cart);
});

module.exports = app;
18 changes: 18 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"license": "ISC",
"dependencies": {
"body-parser": "^1.18.2",
"dotenv": "^16.5.0",
"express": "^4.18.2",
"finalhandler": "latest",
"http": "latest",
Expand Down
Loading