Skip to content

Commit

Permalink
implemented routes and middleware for auth and shopitems
Browse files Browse the repository at this point in the history
  • Loading branch information
21stPhenom committed Oct 3, 2023
1 parent 15ea8ad commit f7ebaf4
Show file tree
Hide file tree
Showing 3 changed files with 147 additions and 0 deletions.
46 changes: 46 additions & 0 deletions routes/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
const express = require("express");
const router = express.Router();
const bcrypt = require("bcryptjs");
const jwt = require('jsonwebtoken');
require("dotenv").config();

const users = require("../schema/userSchema");
const {isUserLoggedIn} = require("./middlewares");

router.post("/register", async (req, res) => {
const salt = bcrypt.genSaltSync(10);
const hashedPassword = bcrypt.hashSync(req.body.password, salt);

await users.create({
fullName: req.body.fullName,
username: req.body.username,
role: req.body.role,
password: hashedPassword
});
res.status(201).send("User created.");
});

router.post("/login", async (req, res) => {
const {username, password} = req.body;
const user = await users.findOne({username});

if (!user) return res.status(404).send('user-not-found');
const passwordMatches = bcrypt.compareSync(password, user.password);

if (!passwordMatches) return res.status(400).send('invalid-credentials');
const {username: userName, _id, role} = user;

const token = jwt.sign({
username: username,
userId: _id,
role: role
}, process.env.secret);

res.send({
message: "Signed in.",
token
});

});

module.exports = router;
34 changes: 34 additions & 0 deletions routes/middlewares.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
require("dotenv").config();
const jwt = require("jsonwebtoken");

function isUserLoggedIn(req, res, next) {
const authHeader = req.headers.authorization;

if (!authHeader) {
res.status(401).send('no-authorization-header');
return;
}

const authHeaderVal = authHeader.split(" ");
const tokenType = authHeaderVal[0];
const tokenValue = authHeaderVal[1];

if (tokenType == "Bearer") {
const decoded = jwt.verify(tokenValue, process.env.secret);
req.decoded = decoded;
next();
return;
}

res.status(401).send('not-authorized');
}

function isAdmin(req, res, next) {
if (req.decoded.role == 'admin') {
next();
} else {
res.status(403).send("action-not-allowed");
}
}

module.exports = {isUserLoggedIn, isAdmin};
67 changes: 67 additions & 0 deletions routes/shopItems.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
const express = require("express");
const router = express.Router();
const jwt = require("jsonwebtoken");

const authRoute = require("./auth");
const items = require("../schema/shopItems");
const { isUserLoggedIn, isAdmin} = require("./middlewares");

router.use(isUserLoggedIn); // ensure that only logged in users can access the API

// general operations for both admin and default users.
router.get("/", async (req, res) => {
const allShopItems = await items.find();
res.json(allShopItems);
});

router.get("/item/:id", async (req, res) => {
const item = await items.findById(req.params.id);
if (item == null) {
res.status(404).send('item-not-found');
}
res.json({item});
});


// Admin-only operations
router.post("/", isAdmin, async (req, res) => {
try {
const {name, description, price, isInStock} = req.body;
const {userId} = req.decoded;

const newShopItem = await items.create({
name, description, price, isInStock, userId: userId
});
res.json({
itemAdded: true,
newShopItem
});
} catch (error) {
console.log(error);
res.status(500).send("internal server error");
}
});

router.patch("/item/:id", isAdmin, async (req, res) => {
const updatedItem = await items.findByIdAndUpdate(req.params.id, {
name: req.body.name,
description: req.body.description,
price: req.body.price,
isInStock: req.body.isInStock,
}, {new: true});

res.json({
message: "Item updated",
updatedItem
});
});

router.delete("/item/:id", isAdmin, async (req, res) => {
const item = await items.findByIdAndDelete(req.params.id);

res.status(204).json({
message: "Item removed"
});
});

module.exports = router;

0 comments on commit f7ebaf4

Please sign in to comment.