Skip to content

Commit

Permalink
set up JWT authorazation
Browse files Browse the repository at this point in the history
  • Loading branch information
chiefkarim committed Sep 11, 2023
1 parent b752181 commit 640f355
Show file tree
Hide file tree
Showing 12 changed files with 57 additions and 32 deletions.
2 changes: 2 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,8 @@ const collectionRouter = require("./routes/collection");
const itemRouter = require("./routes/item");
const signUpRouter = require("./routes/sign-up")
const logInRouter = require('./routes/log-in')


app.use("/",express.static(path.join(__dirname, "uploads")),indexRouter);
app.use("/collection", express.static(path.join(__dirname, "uploads")),collectionRouter);
app.use("/item",express.static(path.join(__dirname, "uploads")),itemRouter);
Expand Down
3 changes: 1 addition & 2 deletions controllers/collectionController.js
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ exports.edit_post_api =[
//handling create item request GET
exports.create_get =asyncHandler(async(req,res,next)=>{
const collections = await collectionModel.find({})

res.render('collectionCreate',{title:"collections create",collections:collections})


Expand All @@ -138,7 +138,6 @@ exports.create_get =asyncHandler(async(req,res,next)=>{
//handling create item request GET
exports.create_get_api =asyncHandler(async(req,res,next)=>{
const collections = await collectionModel.find({})

res.send({title:"collections create",collections:collections})


Expand Down
4 changes: 2 additions & 2 deletions controllers/log-inController.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ exports.logIn_post = [
passport.authenticate('local', function(err, user, info, status) {
if (err) { return next(err) }
if (!user) { return res.render('log-in',{title:'Log in',errors:[info]}) }
jwt.sign(req.body.username, '')
res.redirect('/');
const accessToken = jwt.sign({username:req.body.username}, process.env.ACCESS_TOKEN_SECRET)
res.send({accessToken:accessToken});
})(req, res, next)
}
}),
Expand Down
5 changes: 3 additions & 2 deletions controllers/sign-upController.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const asyncHandler = require("express-async-handler");
const {body , validationResult } = require('express-validator')
const userModel = require('../models/user')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')

exports.signUp_get = asyncHandler(async(req,res,next)=>{
res.render('sign-up',{title:'sign up'})
Expand Down Expand Up @@ -38,8 +39,8 @@ exports.signUp_post = [
password:hashedPassword
})
result = await user.save()
console.log(result)
res.redirect('/')
const accessToken = jwt.sign({username:req.body.username}, process.env.ACCESS_TOKEN_SECRET)
res.send({accessToken:accessToken});
}catch(err){
return next(err)
}
Expand Down
21 changes: 21 additions & 0 deletions helpers/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
const jwt = require('jsonwebtoken')
module.exports=function authenticate(req, res, next) {
const bearerHeader = req.headers["authorization"];

if (typeof bearerHeader !== "undefined") {
const token = bearerHeader.split(" ")[1];
console.log("token", token);

req.token = token;
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) => {
if (err || user.username !== "admin") {
console.log("eror", err);
res.sendStatus(403);
}
req.user = user;
next();
});
} else {
res.sendStatus(400);
}
}
File renamed without changes.
File renamed without changes.
2 changes: 1 addition & 1 deletion populateCategories.js → helpers/populateCategories.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ const fs = require("fs");
const csvParser = require("csv-parser");
const result = [];
const nameIndex = {}; // A mapping to track indexes of names
const collection = require("./models/collection");
const collection = require("../models/collection");
const express = require("express");
const { default: mongoose } = require("mongoose");

Expand Down
4 changes: 2 additions & 2 deletions populateItems.js → helpers/populateItems.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ const fs = require("fs");
const csvParser = require("csv-parser");
const result = [];
const nameIndex = {}; // A mapping to track indexes of names
const collection = require("./models/collection");
const collection = require("../models/collection");
const express = require("express");
const { default: mongoose } = require("mongoose");
const Item = require("./models/item");
const Item = require("../models/item");
const { getEnabledCategories } = require("trace_events");
require("dotenv").config();
//connecting to database
Expand Down
3 changes: 2 additions & 1 deletion request.rest
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
GET http://localhost:3000/collection/api
GET http://localhost:3000/item/edit
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiaWF0IjoxNjk0NDEzMzU0fQ.-bg_1nIVgNkEmWLDEivnXna4Lx0aT4qiOVSTSXCM_Gg
24 changes: 12 additions & 12 deletions routes/collection.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ const storage = multer.diskStorage({
})

const upload = multer({ storage: storage })

const authenticate = require('../helpers/auth')

/* GET users listing. */

Expand All @@ -23,33 +23,33 @@ router.get("/", collection_controller.list);
router.get("/api",cors(),collection_controller.api_list)

//handling edit collection request GET
router.get("/:id/edit/",collection_controller.edit_get)
router.post("/:id/edit/",upload.single('src'),collection_controller.edit_post)
router.get("/:id/edit/",authenticate,collection_controller.edit_get)
router.post("/:id/edit/",authenticate,upload.single('src'),collection_controller.edit_post)

//APIhandling edit collection request GET
router.get("/:id/edit/api",collection_controller.edit_get_api)
router.post("/:id/edit/api",upload.single('src'),collection_controller.edit_post_api)
router.get("/:id/edit/api",authenticate,collection_controller.edit_get_api)
router.post("/:id/edit/api",authenticate,upload.single('src'),collection_controller.edit_post_api)

//handling deleting collection POST
router.post('/:id/delete',collection_controller.delete)
router.post('/:id/delete',authenticate,collection_controller.delete)

//handling deleting collection POST
router.post('/:id/delete/api',collection_controller.delete_api)
router.post('/:id/delete/api',authenticate,collection_controller.delete_api)

//handling create collection request GET
router.get("/create",collection_controller.create_get)
router.get("/create",authenticate,collection_controller.create_get)

//handling create collection request GET
router.get("/create/api",collection_controller.create_get_api)
router.get("/create/api",authenticate,collection_controller.create_get_api)

//handling create collection request POST
router.post("/create",upload.single('src'),collection_controller.create_post)
router.post("/create",authenticate,upload.single('src'),collection_controller.create_post)

//handling create collection request POST
router.post("/create/api",upload.single('src'),collection_controller.create_post_api)
router.post("/create/api",authenticate,upload.single('src'),collection_controller.create_post_api)

// show all items in a specified collection
router.get("/:id", collection_controller.list_items);
router.get("/:id",collection_controller.list_items);

// show all items in a specified collection
router.get("/:id/api", collection_controller.list_items_api);
Expand Down
21 changes: 11 additions & 10 deletions routes/item.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,29 +12,30 @@ const storage = multer.diskStorage({
})

const upload = multer({ storage: storage })
const authenticate = require('../helpers/auth')


//creating item
router.get('/create',item_controller.edit_get)
router.post('/create',upload.array('src',10),item_controller.edit_post)
router.get('/create',authenticate,item_controller.edit_get)
router.post('/create',authenticate,upload.array('src',10),item_controller.edit_post)

//creating item
router.get('/create/api',item_controller.edit_get_api)
router.post('/create/api',upload.array('src',10),item_controller.edit_post_api)
router.get('/create/api',authenticate,item_controller.edit_get_api)
router.post('/create/api',authenticate,upload.array('src',10),item_controller.edit_post_api)

//editing item
router.get('/:id/edit',item_controller.edit_get)
router.post('/:id/edit',upload.array('src',10),item_controller.edit_post)
router.get('/:id/edit',authenticate,item_controller.edit_get)
router.post('/:id/edit',authenticate,upload.array('src',10),item_controller.edit_post)

//editing item
router.get('/:id/edit/api',item_controller.edit_get_api)
router.post('/:id/edit/api',upload.array('src',10),item_controller.edit_post_api)
router.get('/:id/edit/api',authenticate,item_controller.edit_get_api)
router.post('/:id/edit/api',authenticate,upload.array('src',10),item_controller.edit_post_api)

//handling deleting POST
router.post('/:id/delete',item_controller.delete)
router.post('/:id/delete',authenticate,item_controller.delete)

//handling deleting POST
router.post('/:id/delete/api',item_controller.delete_api)
router.post('/:id/delete/api',authenticate,item_controller.delete_api)
// displaying item details GET
router.get('/:id',item_controller.detail)

Expand Down

0 comments on commit 640f355

Please sign in to comment.