-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
implemented routes and middleware for auth and shopitems
- Loading branch information
1 parent
15ea8ad
commit f7ebaf4
Showing
3 changed files
with
147 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |