From 980a3dbeebcf3005caef1df4cfdd033cec2c990c Mon Sep 17 00:00:00 2001 From: Shaikh Rezwan Rafid Ahmad <sa03267@surrey.ac.uk> Date: Tue, 21 Mar 2023 16:58:29 +0000 Subject: [PATCH] Authentication auth.js File Added as Middleware --- .../server/controllers/appController.js | 6 +++--- .../server/middleware/auth.js | 17 +++++++++++++++++ .../server/router/route.js | 4 +++- 3 files changed, 23 insertions(+), 4 deletions(-) create mode 100644 daily-thought-user-service/server/middleware/auth.js diff --git a/daily-thought-user-service/server/controllers/appController.js b/daily-thought-user-service/server/controllers/appController.js index d0aba834..32b8a9d3 100644 --- a/daily-thought-user-service/server/controllers/appController.js +++ b/daily-thought-user-service/server/controllers/appController.js @@ -170,13 +170,13 @@ body: { export async function updateUser(req,res){ try { - const id = req.query.id; + const {userId} = req.user; - if(id){ + if(userId){ const body = req.body; // update the data - UserModel.updateOne({ _id : id }, body, function(err, data){ + UserModel.updateOne({ _id : userId }, body, function(err, data){ if(err) throw err; return res.status(201).send({ msg : "Record Updated...!"}); diff --git a/daily-thought-user-service/server/middleware/auth.js b/daily-thought-user-service/server/middleware/auth.js new file mode 100644 index 00000000..2381df5d --- /dev/null +++ b/daily-thought-user-service/server/middleware/auth.js @@ -0,0 +1,17 @@ +import jwt from 'jsonwebtoken'; +import ENV from '../config.js' + +export default async function Auth(req, res, next){ + try { + + const token = req.headers.authorization.split(" ")[1]; + + const decodedToken = await jwt.verify(token, ENV.JWT_SECRET); + req.user = decodedToken; + + next(); + + } catch (error) { + res.status(401).json({ error : "Authentication Failed!"}) + } +} \ No newline at end of file diff --git a/daily-thought-user-service/server/router/route.js b/daily-thought-user-service/server/router/route.js index bf15b016..aecf0eae 100644 --- a/daily-thought-user-service/server/router/route.js +++ b/daily-thought-user-service/server/router/route.js @@ -1,6 +1,8 @@ import { Router } from "express"; import * as controller from '../controllers/appController.js'; +import Auth from '../middleware/auth.js'; + const router = Router(); /** POST Methods */ @@ -12,6 +14,6 @@ router.route('/user/:username').get(controller.getUser); // GetUser /** PUT Methods */ -router.route('/updateuser').put(controller.updateUser); // is use to update the user profile +router.route('/updateuser').put(Auth, controller.updateUser); // is use to update the user profile export default router; \ No newline at end of file -- GitLab