diff --git a/package-lock.json b/package-lock.json index 91d295e..bdcd76d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -603,6 +603,16 @@ "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.0.tgz", "integrity": "sha512-+Hp8fLp57wnUSt0tY0tHEXh4voZRDnoIrZPqlo3DPiI4y9lwg/jqx+1Om94/W6ZaPDOUbnjOt/99w66zk+l1Xg==" }, + "cookie-parser": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/cookie-parser/-/cookie-parser-1.4.5.tgz", + "integrity": "sha512-f13bPUj/gG/5mDr+xLmSxxDsB9DQiTIfhJS/sqjrmfAWiAN+x2O4i/XguTL9yDZ+/IFDanJ+5x7hC4CXT9Tdzw==", + "dev": true, + "requires": { + "cookie": "0.4.0", + "cookie-signature": "1.0.6" + } + }, "cookie-signature": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", diff --git a/package.json b/package.json index 4c1d44a..9d50ecd 100644 --- a/package.json +++ b/package.json @@ -44,6 +44,7 @@ ] }, "devDependencies": { - "airtable": "^0.10.0" + "airtable": "^0.10.0", + "cookie-parser": "^1.4.5" } } diff --git a/src/app.js b/src/app.js index 3de862c..eb08e5e 100644 --- a/src/app.js +++ b/src/app.js @@ -13,6 +13,8 @@ const { displayAllCountries, } = require("./handlers/tableHandlers"); const handleErrors = require("./middleware/error"); +const { checkBasicAuth, setCookie } = require("./middleware/auth"); +const cookieParser = require("cookie-parser"); const app = express(); app.use(handleErrors); @@ -20,6 +22,7 @@ app.use(handleErrors); app.use(express.json()); app.use(cors()); +app.use(cookieParser()); ////// NON-ADMIN ROUTES ////// app.get("/countries", displayAllCountries); @@ -32,8 +35,9 @@ app.post("/countries/:id/businesses", addBusinessHandler); app.post("/countries/:id/things_to_do", addThingsToDoHandler); ////// ADMIN ROUTES FOR PAULA ////// -app.put("/admin/:table/:postId", approvePostHandler); -app.delete("/admin/:table/:postId", deletePostHandler); -app.get("/admin/:table", getUnapprovedPostsHandler); +app.post("/admin", setCookie); +app.put("/admin/:table/:postId", checkBasicAuth, approvePostHandler); +app.delete("/admin/:table/:postId", checkBasicAuth, deletePostHandler); +app.get("/admin/:table", checkBasicAuth, getUnapprovedPostsHandler); module.exports = app; diff --git a/src/middleware/auth.js b/src/middleware/auth.js new file mode 100644 index 0000000..fe5fb62 --- /dev/null +++ b/src/middleware/auth.js @@ -0,0 +1,16 @@ +function checkBasicAuth(req, res, next) { + const { username, password } = req.cookies; + if (username === "admin" && password === "password") return next(); + else res.send("not authorised"); +} + +function setCookie(req, res, next) { + const { username, password } = req.body; + if (username === "admin" && password === "password") { + res + .cookie("username", req.body.username) + .cookie("password", req.body.password); + res.status(200).send("loggedin"); + } else res.send("wrong credentials"); +} +module.exports = { checkBasicAuth, setCookie };