From 764c1c6f140554ac36d95923f78e6c0aa639e4ad Mon Sep 17 00:00:00 2001 From: SaadDamine Date: Fri, 21 Apr 2023 08:58:46 +0100 Subject: [PATCH 01/18] ignore node_modules folder --- .gitignore | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.gitignore b/.gitignore index b6e47617..26df0a2e 100644 --- a/.gitignore +++ b/.gitignore @@ -127,3 +127,5 @@ dmypy.json # Pyre type checker .pyre/ + +node_modules/ \ No newline at end of file From a99ec31906a04624c57e0e0d164ffb7ff9ec682e Mon Sep 17 00:00:00 2001 From: SaadDamine Date: Fri, 21 Apr 2023 09:01:08 +0100 Subject: [PATCH 02/18] fix express-session deprecated --- index.js | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/index.js b/index.js index 168c0532..0bffb2f6 100644 --- a/index.js +++ b/index.js @@ -29,7 +29,14 @@ const authenticatedUser = (username,password)=>{ const app = express(); -app.use(session({secret:"fingerpint"},resave=true,saveUninitialized=true)); +// This code sets up session management using the Express session middleware +app.use( + session({ + secret: "fingerpint", + resave: true, + saveUninitialized: true, + }) +); app.use(express.json()); @@ -38,16 +45,16 @@ app.use("/friends", function auth(req,res,next){ token = req.session.authorization['accessToken']; jwt.verify(token, "access",(err,user)=>{ if(!err){ - req.user = user; - next(); + req.user = user; + next(); } else{ return res.status(403).json({message: "User not authenticated"}) - } - }); - } else { + } + }); + } else { return res.status(403).json({message: "User not logged in"}) - } + } }); app.post("/login", (req,res) => { @@ -66,7 +73,7 @@ app.post("/login", (req,res) => { req.session.authorization = { accessToken,username } - return res.status(200).send("User successfully logged in"); + return res.status(200).send("User successfully logged in"); } else { return res.status(208).json({message: "Invalid Login. Check username and password"}); } @@ -77,13 +84,13 @@ app.post("/register", (req,res) => { const password = req.body.password; if (username && password) { - if (!doesExist(username)) { + if (!doesExist(username)) { users.push({"username":username,"password":password}); return res.status(200).json({message: "User successfully registred. Now you can login"}); } else { return res.status(404).json({message: "User already exists!"}); } - } + } return res.status(404).json({message: "Unable to register user."}); }); From 25fd3029fceeb31bb853bfb15f95a50060384342 Mon Sep 17 00:00:00 2001 From: SaadDamine Date: Fri, 21 Apr 2023 09:06:44 +0100 Subject: [PATCH 03/18] add jsonwebtoken --- package-lock.json | 185 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 185 insertions(+) diff --git a/package-lock.json b/package-lock.json index e8471ed4..317b92fb 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11,6 +11,7 @@ "dependencies": { "express": "^4.18.1", "express-session": "^1.17.3", + "jsonwebtoken": "^8.5.1", "nodemon": "^2.0.19" } }, @@ -104,6 +105,11 @@ "node": ">=8" } }, + "node_modules/buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==" + }, "node_modules/bytes": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", @@ -212,6 +218,14 @@ "npm": "1.2.8000 || >= 1.4.16" } }, + "node_modules/ecdsa-sig-formatter": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", + "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", + "dependencies": { + "safe-buffer": "^5.0.1" + } + }, "node_modules/ee-first": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", @@ -503,6 +517,86 @@ "node": ">=0.12.0" } }, + "node_modules/jsonwebtoken": { + "version": "8.5.1", + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-8.5.1.tgz", + "integrity": "sha512-XjwVfRS6jTMsqYs0EsuJ4LGxXV14zQybNd4L2r0UvbVnSF9Af8x7p5MzbJ90Ioz/9TI41/hTCvznF/loiSzn8w==", + "dependencies": { + "jws": "^3.2.2", + "lodash.includes": "^4.3.0", + "lodash.isboolean": "^3.0.3", + "lodash.isinteger": "^4.0.4", + "lodash.isnumber": "^3.0.3", + "lodash.isplainobject": "^4.0.6", + "lodash.isstring": "^4.0.1", + "lodash.once": "^4.0.0", + "ms": "^2.1.1", + "semver": "^5.6.0" + }, + "engines": { + "node": ">=4", + "npm": ">=1.4.28" + } + }, + "node_modules/jsonwebtoken/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + }, + "node_modules/jwa": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-1.4.1.tgz", + "integrity": "sha512-qiLX/xhEEFKUAJ6FiBMbes3w9ATzyk5W7Hvzpa/SLYdxNtng+gcurvrI7TbACjIXlsJyr05/S1oUhZrc63evQA==", + "dependencies": { + "buffer-equal-constant-time": "1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/jws": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/jws/-/jws-3.2.2.tgz", + "integrity": "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==", + "dependencies": { + "jwa": "^1.4.1", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/lodash.includes": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", + "integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==" + }, + "node_modules/lodash.isboolean": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", + "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==" + }, + "node_modules/lodash.isinteger": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", + "integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==" + }, + "node_modules/lodash.isnumber": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", + "integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==" + }, + "node_modules/lodash.isplainobject": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", + "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==" + }, + "node_modules/lodash.isstring": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", + "integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==" + }, + "node_modules/lodash.once": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", + "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==" + }, "node_modules/media-typer": { "version": "0.3.0", "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", @@ -1052,6 +1146,11 @@ "fill-range": "^7.0.1" } }, + "buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==" + }, "bytes": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", @@ -1127,6 +1226,14 @@ "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==" }, + "ecdsa-sig-formatter": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", + "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", + "requires": { + "safe-buffer": "^5.0.1" + } + }, "ee-first": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", @@ -1347,6 +1454,84 @@ "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==" }, + "jsonwebtoken": { + "version": "8.5.1", + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-8.5.1.tgz", + "integrity": "sha512-XjwVfRS6jTMsqYs0EsuJ4LGxXV14zQybNd4L2r0UvbVnSF9Af8x7p5MzbJ90Ioz/9TI41/hTCvznF/loiSzn8w==", + "requires": { + "jws": "^3.2.2", + "lodash.includes": "^4.3.0", + "lodash.isboolean": "^3.0.3", + "lodash.isinteger": "^4.0.4", + "lodash.isnumber": "^3.0.3", + "lodash.isplainobject": "^4.0.6", + "lodash.isstring": "^4.0.1", + "lodash.once": "^4.0.0", + "ms": "^2.1.1", + "semver": "^5.6.0" + }, + "dependencies": { + "ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + } + } + }, + "jwa": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-1.4.1.tgz", + "integrity": "sha512-qiLX/xhEEFKUAJ6FiBMbes3w9ATzyk5W7Hvzpa/SLYdxNtng+gcurvrI7TbACjIXlsJyr05/S1oUhZrc63evQA==", + "requires": { + "buffer-equal-constant-time": "1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "jws": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/jws/-/jws-3.2.2.tgz", + "integrity": "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==", + "requires": { + "jwa": "^1.4.1", + "safe-buffer": "^5.0.1" + } + }, + "lodash.includes": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", + "integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==" + }, + "lodash.isboolean": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", + "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==" + }, + "lodash.isinteger": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", + "integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==" + }, + "lodash.isnumber": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", + "integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==" + }, + "lodash.isplainobject": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", + "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==" + }, + "lodash.isstring": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", + "integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==" + }, + "lodash.once": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", + "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==" + }, "media-typer": { "version": "0.3.0", "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", From 1a6b87d42d7183f262f76e510e404d60237abd16 Mon Sep 17 00:00:00 2001 From: SaadDamine Date: Fri, 21 Apr 2023 09:12:37 +0100 Subject: [PATCH 04/18] create A auth helper simplifies auth tasks --- helpers/auth.js | 23 +++++++++++++++++++++++ index.js | 23 ++--------------------- 2 files changed, 25 insertions(+), 21 deletions(-) create mode 100644 helpers/auth.js diff --git a/helpers/auth.js b/helpers/auth.js new file mode 100644 index 00000000..75ce8c4c --- /dev/null +++ b/helpers/auth.js @@ -0,0 +1,23 @@ +const doesExist = (username) => { + let userswithsamename = users.filter((user) => { + return user.username === username; + }); + if (userswithsamename.length > 0) { + return true; + } else { + return false; + } +}; + +const authenticatedUser = (username, password) => { + let validusers = users.filter((user) => { + return user.username === username && user.password === password; + }); + if (validusers.length > 0) { + return true; + } else { + return false; + } +}; + +module.exports = { doesExist, authenticatedUser }; diff --git a/index.js b/index.js index 0bffb2f6..43d56f91 100644 --- a/index.js +++ b/index.js @@ -5,27 +5,8 @@ const routes = require('./router/friends.js') let users = [] -const doesExist = (username)=>{ - let userswithsamename = users.filter((user)=>{ - return user.username === username - }); - if(userswithsamename.length > 0){ - return true; - } else { - return false; - } -} - -const authenticatedUser = (username,password)=>{ - let validusers = users.filter((user)=>{ - return (user.username === username && user.password === password) - }); - if(validusers.length > 0){ - return true; - } else { - return false; - } -} +// Importing the authentication functions from the auth.js file +const { doesExist, authenticatedUser } = require("./helpers/auth"); const app = express(); From 917b386fba48262c2ab0941ad9457756d14cf4ae Mon Sep 17 00:00:00 2001 From: SaadDamine Date: Fri, 21 Apr 2023 09:29:28 +0100 Subject: [PATCH 05/18] directory contains all route modules --- controllers/friendsController.js | 54 ++++++++++++++++++++++++++++++++ index.js | 4 +-- routes/friends.js | 20 ++++++++++++ routes/index.js | 11 +++++++ 4 files changed, 87 insertions(+), 2 deletions(-) create mode 100644 controllers/friendsController.js create mode 100644 routes/friends.js create mode 100644 routes/index.js diff --git a/controllers/friendsController.js b/controllers/friendsController.js new file mode 100644 index 00000000..939a8d32 --- /dev/null +++ b/controllers/friendsController.js @@ -0,0 +1,54 @@ +const express = require("express"); + +const router = express.Router(); + +let friends = { + "johnsmith@gamil.com": { + firstName: "John", + lastName: "Doe", + DOB: "22-12-1990", + }, + "annasmith@gamil.com": { + firstName: "Anna", + lastName: "smith", + DOB: "02-07-1983", + }, + "peterjones@gamil.com": { + firstName: "Peter", + lastName: "Jones", + DOB: "21-03-1989", + }, +}; + +// GET request: Retrieve all friends +router.get("/", (req, res) => { + // Update the code here + + res.send("Yet to be implemented"); //This line is to be replaced with actual return value +}); + +// GET by specific ID request: Retrieve a single friend with email ID +router.get("/:email", (req, res) => { + // Update the code here + res.send("Yet to be implemented"); //This line is to be replaced with actual return value +}); + +// POST request: Add a new friend +router.post("/", (req, res) => { + // Update the code here + res.send("Yet to be implemented"); //This line is to be replaced with actual return value +}); + +// PUT request: Update the details of a friend with email id +router.put("/:email", (req, res) => { + // Update the code here + res.send("Yet to be implemented"); //This line is to be replaced with actual return value +}); + +// DELETE request: Delete a friend by email id +router.delete("/:email", (req, res) => { + // Update the code here + res.send("Yet to be implemented"); //This line is to be replaced with actual return value +}); + +module.exports = router; diff --git a/index.js b/index.js index 43d56f91..48541401 100644 --- a/index.js +++ b/index.js @@ -1,7 +1,7 @@ const express = require('express'); const jwt = require('jsonwebtoken'); const session = require('express-session') -const routes = require('./router/friends.js') +const routes = require("./routes"); let users = [] @@ -78,6 +78,6 @@ app.post("/register", (req,res) => { const PORT =5000; -app.use("/friends", routes); +app.use("/", routes); app.listen(PORT,()=>console.log("Server is running")); diff --git a/routes/friends.js b/routes/friends.js new file mode 100644 index 00000000..a029392d --- /dev/null +++ b/routes/friends.js @@ -0,0 +1,20 @@ +const express = require("express"); +const router = express.Router(); +const friendsController = require("../controllers/friendsController"); + +// GET request: Retrieve all friends +router.get("/", friendsController.getAllFriends); + +// GET by specific ID request: Retrieve a single friend with email ID +router.get("/:email", friendsController.getFriendByEmail); + +// POST request: Add a new friend +router.post("/", friendsController.addFriend); + +// PUT request: Update the details of a friend with email id +router.put("/:email", friendsController.updateFriend); + +// DELETE request: Delete a friend by email id +router.delete("/:email", friendsController.deleteFriend); + +module.exports = router; \ No newline at end of file diff --git a/routes/index.js b/routes/index.js new file mode 100644 index 00000000..5e02a660 --- /dev/null +++ b/routes/index.js @@ -0,0 +1,11 @@ +const express = require("express"); +const router = express.Router(); +const friendsRoutes = require("./friends"); + +router.use("/friends", friendsRoutes); + +router.get("/", (req, res) => { + res.send("Welcome to my app!"); +}); + +module.exports = router; \ No newline at end of file From 1d37afa7c56f758de1be29c7d99bbb0fca23efe1 Mon Sep 17 00:00:00 2001 From: SaadDamine Date: Fri, 21 Apr 2023 10:19:05 +0100 Subject: [PATCH 06/18] create a route for auth --- controllers/authController.js | 56 +++++++++++++++++++++++++++++++++++ index.js | 41 ------------------------- routes/auth.js | 12 ++++++++ routes/index.js | 2 ++ 4 files changed, 70 insertions(+), 41 deletions(-) create mode 100644 controllers/authController.js create mode 100644 routes/auth.js diff --git a/controllers/authController.js b/controllers/authController.js new file mode 100644 index 00000000..dc708fd9 --- /dev/null +++ b/controllers/authController.js @@ -0,0 +1,56 @@ +const express = require("express"); +const router = express.Router(); +const jwt = require("jsonwebtoken"); // Importing the jsonwebtoken module +const { doesExist, authenticatedUser } = require("../helpers/auth"); +let users = []; // Defining the users array + +let login = (req, res) => { + const username = req.body.username; + const password = req.body.password; + + if (!username || !password) { + return res.status(400).json({ + message: "Error logging in. Please provide both username and password.", + }); // Using status code 400 for bad request + } + + if (authenticatedUser(username, password)) { + let accessToken = jwt.sign( + { + data: password, + }, + "access", + { expiresIn: 60 * 60 } + ); + + req.session.authorization = { + accessToken, + username, + }; + return res.status(200).send("User successfully logged in"); + } else { + return res.status(401).json({ + message: + "Invalid login credentials. Please check your username and password.", + }); // Using status code 401 for unauthorized + } +}; + +let register = (req, res) => { + const username = req.body.username; + const password = req.body.password; + + if (username && password) { + if (!doesExist(username)) { + users.push({ username: username, password: password }); + return res + .status(201) // Using status code 201 for created + .json({ message: "User successfully registered. You can now log in." }); + } else { + return res.status(409).json({ message: "Username already exists." }); // Using status code 409 for conflict + } + } + return res.status(400).json({ message: "Invalid username or password." }); // Using status code 400 for bad request +}; + +module.exports = { login, register }; diff --git a/index.js b/index.js index 48541401..f37ff6f1 100644 --- a/index.js +++ b/index.js @@ -5,9 +5,6 @@ const routes = require("./routes"); let users = [] -// Importing the authentication functions from the auth.js file -const { doesExist, authenticatedUser } = require("./helpers/auth"); - const app = express(); // This code sets up session management using the Express session middleware @@ -38,44 +35,6 @@ app.use("/friends", function auth(req,res,next){ } }); -app.post("/login", (req,res) => { - const username = req.body.username; - const password = req.body.password; - - if (!username || !password) { - return res.status(404).json({message: "Error logging in"}); - } - - if (authenticatedUser(username,password)) { - let accessToken = jwt.sign({ - data: password - }, 'access', { expiresIn: 60 * 60 }); - - req.session.authorization = { - accessToken,username - } - return res.status(200).send("User successfully logged in"); - } else { - return res.status(208).json({message: "Invalid Login. Check username and password"}); - } -}); - -app.post("/register", (req,res) => { - const username = req.body.username; - const password = req.body.password; - - if (username && password) { - if (!doesExist(username)) { - users.push({"username":username,"password":password}); - return res.status(200).json({message: "User successfully registred. Now you can login"}); - } else { - return res.status(404).json({message: "User already exists!"}); - } - } - return res.status(404).json({message: "Unable to register user."}); -}); - - const PORT =5000; app.use("/", routes); diff --git a/routes/auth.js b/routes/auth.js new file mode 100644 index 00000000..e13954b5 --- /dev/null +++ b/routes/auth.js @@ -0,0 +1,12 @@ +const express = require("express"); +const router = express.Router(); + +const {login,register} = require("../controllers/authController"); + +// POST request to log in user +router.post("/login", login); + +// POST request to register new user +router.post("/register", register); + +module.exports = router; diff --git a/routes/index.js b/routes/index.js index 5e02a660..f771eef9 100644 --- a/routes/index.js +++ b/routes/index.js @@ -1,8 +1,10 @@ const express = require("express"); const router = express.Router(); const friendsRoutes = require("./friends"); +const authController = require("./auth"); router.use("/friends", friendsRoutes); +router.use("/auth", authController); router.get("/", (req, res) => { res.send("Welcome to my app!"); From 56ecd1476915bb987af62e5335c4706b6ba88c03 Mon Sep 17 00:00:00 2001 From: SaadDamine Date: Fri, 21 Apr 2023 10:20:05 +0100 Subject: [PATCH 07/18] fix error friends route - requires a callback function but got a object Undefined --- controllers/friendsController.js | 28 +++++++++++++++++----------- routes/friends.js | 28 +++++++++++++--------------- 2 files changed, 30 insertions(+), 26 deletions(-) diff --git a/controllers/friendsController.js b/controllers/friendsController.js index 939a8d32..36b14653 100644 --- a/controllers/friendsController.js +++ b/controllers/friendsController.js @@ -21,34 +21,40 @@ let friends = { }; // GET request: Retrieve all friends -router.get("/", (req, res) => { +let getAllFriends = (req, res) => { // Update the code here res.send("Yet to be implemented"); //This line is to be replaced with actual return value -}); +}; // GET by specific ID request: Retrieve a single friend with email ID -router.get("/:email", (req, res) => { +let getFriendByEmail = (req, res) => { // Update the code here res.send("Yet to be implemented"); //This line is to be replaced with actual return value -}); +}; // POST request: Add a new friend -router.post("/", (req, res) => { +let addFriend = (req, res) => { // Update the code here res.send("Yet to be implemented"); //This line is to be replaced with actual return value -}); +}; // PUT request: Update the details of a friend with email id -router.put("/:email", (req, res) => { +let updateFriend = (req, res) => { // Update the code here res.send("Yet to be implemented"); //This line is to be replaced with actual return value -}); +}; // DELETE request: Delete a friend by email id -router.delete("/:email", (req, res) => { +let deleteFriend = (req, res) => { // Update the code here res.send("Yet to be implemented"); //This line is to be replaced with actual return value -}); +}; -module.exports = router; +module.exports = { + getAllFriends, + getFriendByEmail, + addFriend, + updateFriend, + deleteFriend, +}; diff --git a/routes/friends.js b/routes/friends.js index a029392d..9ce8eea2 100644 --- a/routes/friends.js +++ b/routes/friends.js @@ -1,20 +1,18 @@ const express = require("express"); const router = express.Router(); -const friendsController = require("../controllers/friendsController"); -// GET request: Retrieve all friends -router.get("/", friendsController.getAllFriends); +const { + getAllFriends, + getFriendByEmail, + addFriend, + updateFriend, + deleteFriend, +} = require("../controllers/friendsController"); -// GET by specific ID request: Retrieve a single friend with email ID -router.get("/:email", friendsController.getFriendByEmail); +router.get("/", getAllFriends); +router.get("/:email", getFriendByEmail); +router.post("/", addFriend); +router.put("/:email", updateFriend); +router.delete("/:email", deleteFriend); -// POST request: Add a new friend -router.post("/", friendsController.addFriend); - -// PUT request: Update the details of a friend with email id -router.put("/:email", friendsController.updateFriend); - -// DELETE request: Delete a friend by email id -router.delete("/:email", friendsController.deleteFriend); - -module.exports = router; \ No newline at end of file +module.exports = router; From 1a77a30838ab66bc593461be1144f4c45dd19d06 Mon Sep 17 00:00:00 2001 From: SaadDamine Date: Fri, 21 Apr 2023 10:37:43 +0100 Subject: [PATCH 08/18] split middleware code into a separate module --- index.js | 21 ++------------------- middleware/authMiddleware.js | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+), 19 deletions(-) create mode 100644 middleware/authMiddleware.js diff --git a/index.js b/index.js index f37ff6f1..c01bdcdd 100644 --- a/index.js +++ b/index.js @@ -1,9 +1,7 @@ const express = require('express'); -const jwt = require('jsonwebtoken'); const session = require('express-session') const routes = require("./routes"); - -let users = [] +const authMiddleware = require("./middleware/authMiddleware"); const app = express(); @@ -18,22 +16,7 @@ app.use( app.use(express.json()); -app.use("/friends", function auth(req,res,next){ - if(req.session.authorization) { - token = req.session.authorization['accessToken']; - jwt.verify(token, "access",(err,user)=>{ - if(!err){ - req.user = user; - next(); - } - else{ - return res.status(403).json({message: "User not authenticated"}) - } - }); - } else { - return res.status(403).json({message: "User not logged in"}) - } -}); +app.use("/friends", authMiddleware); const PORT =5000; diff --git a/middleware/authMiddleware.js b/middleware/authMiddleware.js new file mode 100644 index 00000000..7c22d33f --- /dev/null +++ b/middleware/authMiddleware.js @@ -0,0 +1,19 @@ +const jwt = require("jsonwebtoken"); + +function auth(req, res, next) { + if (req.session.authorization) { + const token = req.session.authorization.accessToken; + jwt.verify(token, "access", (err, user) => { + if (!err) { + req.user = user; + next(); + } else { + return res.status(403).json({ message: "User not authenticated" }); + } + }); + } else { + return res.status(403).json({ message: "User not logged in" }); + } +} + +module.exports = auth; From 47ff281fffe02753e0bd30934b77aef29c06d11c Mon Sep 17 00:00:00 2001 From: SaadDamine Date: Fri, 21 Apr 2023 10:39:31 +0100 Subject: [PATCH 09/18] clean code --- controllers/authController.js | 3 +- controllers/friendsController.js | 4 --- router/friends.js | 47 -------------------------------- 3 files changed, 1 insertion(+), 53 deletions(-) delete mode 100644 router/friends.js diff --git a/controllers/authController.js b/controllers/authController.js index dc708fd9..3540907c 100644 --- a/controllers/authController.js +++ b/controllers/authController.js @@ -1,7 +1,6 @@ -const express = require("express"); -const router = express.Router(); const jwt = require("jsonwebtoken"); // Importing the jsonwebtoken module const { doesExist, authenticatedUser } = require("../helpers/auth"); + let users = []; // Defining the users array let login = (req, res) => { diff --git a/controllers/friendsController.js b/controllers/friendsController.js index 36b14653..83c0e447 100644 --- a/controllers/friendsController.js +++ b/controllers/friendsController.js @@ -1,7 +1,3 @@ -const express = require("express"); - -const router = express.Router(); - let friends = { "johnsmith@gamil.com": { firstName: "John", diff --git a/router/friends.js b/router/friends.js deleted file mode 100644 index 0b696b8d..00000000 --- a/router/friends.js +++ /dev/null @@ -1,47 +0,0 @@ -const express = require('express'); - -const router = express.Router(); - -let friends = { - "johnsmith@gamil.com": {"firstName": "John","lastName": "Doe","DOB":"22-12-1990"}, - "annasmith@gamil.com":{"firstName": "Anna","lastName": "smith","DOB":"02-07-1983"}, - "peterjones@gamil.com":{"firstName": "Peter","lastName": "Jones","DOB":"21-03-1989"} -}; - - -// GET request: Retrieve all friends -router.get("/",(req,res)=>{ - - // Update the code here - - res.send("Yet to be implemented")//This line is to be replaced with actual return value -}); - -// GET by specific ID request: Retrieve a single friend with email ID -router.get("/:email",(req,res)=>{ - // Update the code here - res.send("Yet to be implemented")//This line is to be replaced with actual return value -}); - - -// POST request: Add a new friend -router.post("/",(req,res)=>{ - // Update the code here - res.send("Yet to be implemented")//This line is to be replaced with actual return value -}); - - -// PUT request: Update the details of a friend with email id -router.put("/:email", (req, res) => { - // Update the code here - res.send("Yet to be implemented")//This line is to be replaced with actual return value -}); - - -// DELETE request: Delete a friend by email id -router.delete("/:email", (req, res) => { - // Update the code here - res.send("Yet to be implemented")//This line is to be replaced with actual return value -}); - -module.exports=router; From 8fe9d134030f02b4a2fcd26ccb7a2f566ac96801 Mon Sep 17 00:00:00 2001 From: SaadDamine Date: Fri, 21 Apr 2023 11:07:39 +0100 Subject: [PATCH 10/18] Implement crud in friendsController --- controllers/friendsController.js | 50 +++++++++++++++++++++++++------- 1 file changed, 39 insertions(+), 11 deletions(-) diff --git a/controllers/friendsController.js b/controllers/friendsController.js index 83c0e447..563f5e82 100644 --- a/controllers/friendsController.js +++ b/controllers/friendsController.js @@ -18,33 +18,61 @@ let friends = { // GET request: Retrieve all friends let getAllFriends = (req, res) => { - // Update the code here - - res.send("Yet to be implemented"); //This line is to be replaced with actual return value + res.send(JSON.stringify(friends, null, 4)); }; // GET by specific ID request: Retrieve a single friend with email ID let getFriendByEmail = (req, res) => { - // Update the code here - res.send("Yet to be implemented"); //This line is to be replaced with actual return value + const email = req.params.email; + const friend = friends[email]; + if (friend) { + res.json(JSON.stringify(friend, null, 4)); + } else { + res.status(404).send("Friend not found"); + } }; // POST request: Add a new friend let addFriend = (req, res) => { - // Update the code here - res.send("Yet to be implemented"); //This line is to be replaced with actual return value + const email = req.body.email; + const friend = req.body.friend; + if (email && friend) { + if (friends[email]) { + res.status(409).send("Friend with this email already exists"); + } else { + friends[email] = friend; + res.status(201).send("Friend added successfully"); + } + } else { + res.status(400).send("Bad request"); + } }; // PUT request: Update the details of a friend with email id let updateFriend = (req, res) => { - // Update the code here - res.send("Yet to be implemented"); //This line is to be replaced with actual return value + const email = req.params.email; + const friend = req.body.friend; + if (email && friend) { + if (friends[email]) { + friends[email] = friend; + res.send("Friend updated successfully"); + } else { + res.status(404).send("Friend not found"); + } + } else { + res.status(400).send("Bad request"); + } }; // DELETE request: Delete a friend by email id let deleteFriend = (req, res) => { - // Update the code here - res.send("Yet to be implemented"); //This line is to be replaced with actual return value + const email = req.params.email; + if (friends[email]) { + delete friends[email]; + res.send("Friend deleted successfully"); + } else { + res.status(404).send("Friend not found"); + } }; module.exports = { From 0cae9610fe33901f71a1c2327dc23260c2f6c492 Mon Sep 17 00:00:00 2001 From: SaadDamine Date: Fri, 21 Apr 2023 11:54:20 +0100 Subject: [PATCH 11/18] Readme for RESTful API for managing friends --- controllers/Friend.md | 86 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 controllers/Friend.md diff --git a/controllers/Friend.md b/controllers/Friend.md new file mode 100644 index 00000000..2484e903 --- /dev/null +++ b/controllers/Friend.md @@ -0,0 +1,86 @@ +# Friends API + +This is a simple RESTful API for managing friends. It allows you to: + +- GET a list of all friends +- GET a single friend by email ID +- POST a new friend +- PUT update a friend's details +- DELETE a friend + +By default, the API server will run on `http://localhost:5000`. + +## API Reference +``` +``` +### GET a list of all friends + +```http +GET /friends + +curl http://localhost:5000/friends +``` +#### Response: +``` +{ + "johnsmith@gamil.com": { + "firstName": "John", + "lastName": "Doe", + "DOB": "22-12-1990" + }, + "annasmith@gamil.com": { + "firstName": "Anna", + "lastName": "smith", + "DOB": "02-07-1983" + }, + "peterjones@gamil.com": { + "firstName": "Peter", + "lastName": "Jones", + "DOB": "21-03-1989" + } +} +``` +### GET a single friend by email ID +``` +GET /friends/:email + +curl http://localhost:5000/friends/johnsmith@gamil.com +``` +#### Response: +``` +{ + "firstName": "John", + "lastName": "Doe", + "DOB": "22-12-1990" +} +``` +## POST a new friend +``` +POST /friends + +curl -X POST -H "Content-Type: application/json" -d '{"email": "janesmith@gamil.com", "friend": {"firstName": "Jane", "lastName": "Smith", "DOB": "11-05-1995"}}' http://localhost:5000/friends +``` +#### Response: +``` +Friend added successfully +``` +## PUT update a friend's details +``` +PUT /friends/:email + +curl -X PUT -H "Content-Type: application/json" -d '{"friend": {"firstName": "John", "lastName": "Smith", "DOB": "22-12-1990"}}' http://localhost:5000/friends/johnsmith@gamil.com +``` +#### Response: +``` +Friend updated successfully +``` +## DELETE a friend +``` +DELETE /friends/:email + +curl -X DELETE http://localhost:5000/friends/peterjones@gamil.com +``` +#### Response: +``` +Friend deleted successfully +``` From a9983a8c927a5cbb1337ec4160e0ee18271f7fe7 Mon Sep 17 00:00:00 2001 From: SaadDamine Date: Fri, 21 Apr 2023 12:06:22 +0100 Subject: [PATCH 12/18] handle bad requests in friendController --- controllers/friendsController.js | 40 +++++++++++++++++++------------- 1 file changed, 24 insertions(+), 16 deletions(-) diff --git a/controllers/friendsController.js b/controllers/friendsController.js index 563f5e82..f664d5ec 100644 --- a/controllers/friendsController.js +++ b/controllers/friendsController.js @@ -36,15 +36,15 @@ let getFriendByEmail = (req, res) => { let addFriend = (req, res) => { const email = req.body.email; const friend = req.body.friend; - if (email && friend) { - if (friends[email]) { - res.status(409).send("Friend with this email already exists"); - } else { - friends[email] = friend; - res.status(201).send("Friend added successfully"); - } + if (!email || !friend) { + res.status(400).send("Please provide both email and friend in request body"); + } else if (!isValidFriend(friend)) { + res.status(400).send("Invalid friend object. Please provide a valid friend object with firstName, lastName, and DOB"); + } else if (friends[email]) { + res.status(409).send("Friend with this email already exists"); } else { - res.status(400).send("Bad request"); + friends[email] = friend; + res.status(201).send("Friend added successfully"); } }; @@ -52,15 +52,15 @@ let addFriend = (req, res) => { let updateFriend = (req, res) => { const email = req.params.email; const friend = req.body.friend; - if (email && friend) { - if (friends[email]) { - friends[email] = friend; - res.send("Friend updated successfully"); - } else { - res.status(404).send("Friend not found"); - } + if (!email || !friend) { + res.status(400).send("Please provide both email and friend in request body"); + } else if (!isValidFriend(friend)) { + res.status(400).send("Invalid friend object. Please provide a valid friend object with firstName, lastName, and DOB"); + } else if (!friends[email]) { + res.status(404).send("Friend not found"); } else { - res.status(400).send("Bad request"); + friends[email] = friend; + res.send("Friend updated successfully"); } }; @@ -75,6 +75,14 @@ let deleteFriend = (req, res) => { } }; +// Helper function to validate friend object +function isValidFriend(friend) { + if (!friend.firstName || !friend.lastName || !friend.DOB) { + return false; + } + return true; +} + module.exports = { getAllFriends, getFriendByEmail, From 7c6523f2633d8fe90c852021fcad790b73a50b42 Mon Sep 17 00:00:00 2001 From: SaadDamine Date: Fri, 21 Apr 2023 12:14:26 +0100 Subject: [PATCH 13/18] HTTP status codes for each CRUD operation --- controllers/friendsController.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/controllers/friendsController.js b/controllers/friendsController.js index f664d5ec..4feb2b66 100644 --- a/controllers/friendsController.js +++ b/controllers/friendsController.js @@ -18,7 +18,7 @@ let friends = { // GET request: Retrieve all friends let getAllFriends = (req, res) => { - res.send(JSON.stringify(friends, null, 4)); + res.status(200).send(JSON.stringify(friends, null, 4)); }; // GET by specific ID request: Retrieve a single friend with email ID @@ -26,7 +26,7 @@ let getFriendByEmail = (req, res) => { const email = req.params.email; const friend = friends[email]; if (friend) { - res.json(JSON.stringify(friend, null, 4)); + res.status(200).json(JSON.stringify(friend, null, 4)); } else { res.status(404).send("Friend not found"); } @@ -44,7 +44,7 @@ let addFriend = (req, res) => { res.status(409).send("Friend with this email already exists"); } else { friends[email] = friend; - res.status(201).send("Friend added successfully"); + res.status(201).send("The user" + (' ')+ (req.body.firstName) + " Has been added!"); } }; @@ -60,7 +60,7 @@ let updateFriend = (req, res) => { res.status(404).send("Friend not found"); } else { friends[email] = friend; - res.send("Friend updated successfully"); + res.status(200).send(`Friend with the email ${email} updated.`); } }; @@ -69,7 +69,7 @@ let deleteFriend = (req, res) => { const email = req.params.email; if (friends[email]) { delete friends[email]; - res.send("Friend deleted successfully"); + res.status(200).send(`Friend with the email ${email} deleted.`); } else { res.status(404).send("Friend not found"); } From b653ed3929c12a73c6ebdfaf5d3335170348c806 Mon Sep 17 00:00:00 2001 From: SaadDamine Date: Fri, 21 Apr 2023 13:02:38 +0100 Subject: [PATCH 14/18] create a Simple Model For User --- controllers/authController.js | 3 ++- helpers/auth.js | 3 +++ models/user.js | 21 +++++++++++++++++++++ 3 files changed, 26 insertions(+), 1 deletion(-) create mode 100644 models/user.js diff --git a/controllers/authController.js b/controllers/authController.js index 3540907c..eb1d4520 100644 --- a/controllers/authController.js +++ b/controllers/authController.js @@ -1,7 +1,8 @@ const jwt = require("jsonwebtoken"); // Importing the jsonwebtoken module const { doesExist, authenticatedUser } = require("../helpers/auth"); -let users = []; // Defining the users array +const user = require("../models/user"); +const users = user.getAllUsers(); let login = (req, res) => { const username = req.body.username; diff --git a/helpers/auth.js b/helpers/auth.js index 75ce8c4c..60a29d61 100644 --- a/helpers/auth.js +++ b/helpers/auth.js @@ -1,3 +1,6 @@ +const user = require("../models/user"); +const users = user.getAllUsers(); + const doesExist = (username) => { let userswithsamename = users.filter((user) => { return user.username === username; diff --git a/models/user.js b/models/user.js new file mode 100644 index 00000000..0e468666 --- /dev/null +++ b/models/user.js @@ -0,0 +1,21 @@ +// user.js + +let users = []; + +module.exports = { + addUser: function (username, password) { + users.push({ username: username, password: password }); + }, + + getUser: function (username) { + return users.find((user) => user.username === username); + }, + + doesExist: function (username) { + return users.some((user) => user.username === username); + }, + + getAllUsers: function () { + return users; + }, +}; From c22109436d9a06651b111741fdece16ce3b4f88e Mon Sep 17 00:00:00 2001 From: SaadDamine Date: Fri, 21 Apr 2023 13:42:53 +0100 Subject: [PATCH 15/18] fix userModel --- controllers/authController.js | 3 +-- helpers/auth.js | 6 ++---- models/user.js | 8 +++----- 3 files changed, 6 insertions(+), 11 deletions(-) diff --git a/controllers/authController.js b/controllers/authController.js index eb1d4520..98c97960 100644 --- a/controllers/authController.js +++ b/controllers/authController.js @@ -2,7 +2,6 @@ const jwt = require("jsonwebtoken"); // Importing the jsonwebtoken module const { doesExist, authenticatedUser } = require("../helpers/auth"); const user = require("../models/user"); -const users = user.getAllUsers(); let login = (req, res) => { const username = req.body.username; @@ -42,7 +41,7 @@ let register = (req, res) => { if (username && password) { if (!doesExist(username)) { - users.push({ username: username, password: password }); + user.addUser(username,password); return res .status(201) // Using status code 201 for created .json({ message: "User successfully registered. You can now log in." }); diff --git a/helpers/auth.js b/helpers/auth.js index 60a29d61..e176535e 100644 --- a/helpers/auth.js +++ b/helpers/auth.js @@ -1,10 +1,7 @@ const user = require("../models/user"); -const users = user.getAllUsers(); const doesExist = (username) => { - let userswithsamename = users.filter((user) => { - return user.username === username; - }); + let userswithsamename = user.getUser(username); if (userswithsamename.length > 0) { return true; } else { @@ -13,6 +10,7 @@ const doesExist = (username) => { }; const authenticatedUser = (username, password) => { + const users = user.getAllUsers(); let validusers = users.filter((user) => { return user.username === username && user.password === password; }); diff --git a/models/user.js b/models/user.js index 0e468666..0f2d39b6 100644 --- a/models/user.js +++ b/models/user.js @@ -8,11 +8,9 @@ module.exports = { }, getUser: function (username) { - return users.find((user) => user.username === username); - }, - - doesExist: function (username) { - return users.some((user) => user.username === username); + return users.filter((user) => { + return user.username === username; + }); }, getAllUsers: function () { From 55b18238ba0621656d1438402b20d8419e72a776 Mon Sep 17 00:00:00 2001 From: SaadDamine Date: Fri, 21 Apr 2023 14:33:30 +0100 Subject: [PATCH 16/18] add all crud op to userModel --- models/user.js | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/models/user.js b/models/user.js index 0f2d39b6..7712d2b7 100644 --- a/models/user.js +++ b/models/user.js @@ -1,12 +1,12 @@ -// user.js - let users = []; module.exports = { + // CREATE addUser: function (username, password) { users.push({ username: username, password: password }); }, + // READ getUser: function (username) { return users.filter((user) => { return user.username === username; @@ -16,4 +16,18 @@ module.exports = { getAllUsers: function () { return users; }, + + // UPDATE + updateUser: function (username, newUsername, newPassword) { + const userIndex = users.findIndex((user) => user.username === username); + if (userIndex !== -1) { + users[userIndex].username = newUsername; + users[userIndex].password = newPassword; + } + }, + + // DELETE + deleteUser: function (username) { + users = users.filter((user) => user.username !== username); + }, }; From 85f8d112ccb1b2a8e411e0d8c850b318e1c3d089 Mon Sep 17 00:00:00 2001 From: SaadDamine Date: Fri, 21 Apr 2023 14:45:57 +0100 Subject: [PATCH 17/18] create friend Module --- controllers/friendsController.js | 60 +++++++++++++++----------------- models/friend.js | 51 +++++++++++++++++++++++++++ 2 files changed, 80 insertions(+), 31 deletions(-) create mode 100644 models/friend.js diff --git a/controllers/friendsController.js b/controllers/friendsController.js index 4feb2b66..565a1fc9 100644 --- a/controllers/friendsController.js +++ b/controllers/friendsController.js @@ -1,32 +1,16 @@ -let friends = { - "johnsmith@gamil.com": { - firstName: "John", - lastName: "Doe", - DOB: "22-12-1990", - }, - "annasmith@gamil.com": { - firstName: "Anna", - lastName: "smith", - DOB: "02-07-1983", - }, - "peterjones@gamil.com": { - firstName: "Peter", - lastName: "Jones", - DOB: "21-03-1989", - }, -}; +const friends = require("../models/friend"); // GET request: Retrieve all friends let getAllFriends = (req, res) => { - res.status(200).send(JSON.stringify(friends, null, 4)); + res.status(200).send(friends.getAllFriends()); }; // GET by specific ID request: Retrieve a single friend with email ID let getFriendByEmail = (req, res) => { const email = req.params.email; - const friend = friends[email]; + const friend = friends.getFriend(email); if (friend) { - res.status(200).json(JSON.stringify(friend, null, 4)); + res.status(200).json(friend); } else { res.status(404).send("Friend not found"); } @@ -37,14 +21,22 @@ let addFriend = (req, res) => { const email = req.body.email; const friend = req.body.friend; if (!email || !friend) { - res.status(400).send("Please provide both email and friend in request body"); + res + .status(400) + .send("Please provide both email and friend in request body"); } else if (!isValidFriend(friend)) { - res.status(400).send("Invalid friend object. Please provide a valid friend object with firstName, lastName, and DOB"); - } else if (friends[email]) { + res + .status(400) + .send( + "Invalid friend object. Please provide a valid friend object with firstName, lastName, and DOB" + ); + } else if (friends.getFriend(email)) { res.status(409).send("Friend with this email already exists"); } else { - friends[email] = friend; - res.status(201).send("The user" + (' ')+ (req.body.firstName) + " Has been added!"); + friends.addFriend(email, friend); + res + .status(201) + .send("The user" + " " + req.body.firstName + " Has been added!"); } }; @@ -53,13 +45,19 @@ let updateFriend = (req, res) => { const email = req.params.email; const friend = req.body.friend; if (!email || !friend) { - res.status(400).send("Please provide both email and friend in request body"); + res + .status(400) + .send("Please provide both email and friend in request body"); } else if (!isValidFriend(friend)) { - res.status(400).send("Invalid friend object. Please provide a valid friend object with firstName, lastName, and DOB"); - } else if (!friends[email]) { + res + .status(400) + .send( + "Invalid friend object. Please provide a valid friend object with firstName, lastName, and DOB" + ); + } else if (!friends.getFriend(email)) { res.status(404).send("Friend not found"); } else { - friends[email] = friend; + friends.updateFriend(email, friend); res.status(200).send(`Friend with the email ${email} updated.`); } }; @@ -67,8 +65,8 @@ let updateFriend = (req, res) => { // DELETE request: Delete a friend by email id let deleteFriend = (req, res) => { const email = req.params.email; - if (friends[email]) { - delete friends[email]; + if (friends.getFriend(email)) { + friends.deleteFriend(email); res.status(200).send(`Friend with the email ${email} deleted.`); } else { res.status(404).send("Friend not found"); diff --git a/models/friend.js b/models/friend.js new file mode 100644 index 00000000..197b8e28 --- /dev/null +++ b/models/friend.js @@ -0,0 +1,51 @@ +let friends = { + "johnsmith@gmail.com": { + firstName: "John", + lastName: "Doe", + DOB: "22-12-1990", + }, + "annasmith@gmail.com": { + firstName: "Anna", + lastName: "smith", + DOB: "02-07-1983", + }, + "peterjones@gmail.com": { + firstName: "Peter", + lastName: "Jones", + DOB: "21-03-1989", + }, +}; + +module.exports = { + // CREATE + addFriend: function (email, firstName, lastName, DOB) { + friends[email] = { + firstName: firstName, + lastName: lastName, + DOB: DOB, + }; + }, + + // READ + getFriend: function (email) { + return friends[email]; + }, + + getAllFriends: function () { + return friends; + }, + + // UPDATE + updateFriend: function (email, firstName, lastName, DOB) { + if (friends[email]) { + friends[email].firstName = firstName; + friends[email].lastName = lastName; + friends[email].DOB = DOB; + } + }, + + // DELETE + deleteFriend: function (email) { + delete friends[email]; + }, +}; From f4e0be779c876e108b24bd1c933aaea0dc84b3ff Mon Sep 17 00:00:00 2001 From: SaadDamine Date: Fri, 21 Apr 2023 15:03:43 +0100 Subject: [PATCH 18/18] add a user to list userModules --- models/user.js | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/models/user.js b/models/user.js index 7712d2b7..34aff824 100644 --- a/models/user.js +++ b/models/user.js @@ -1,4 +1,9 @@ -let users = []; +let users = [ + { + username: "user2", + password: "password2", + }, +]; module.exports = { // CREATE