Skip to content

Commit

Permalink
feat: add basic cookie authorisation handler and route
Browse files Browse the repository at this point in the history
Relates #34
  • Loading branch information
Netceer committed Oct 22, 2020
1 parent 5798b20 commit 970a9d0
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 4 deletions.
10 changes: 10 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
]
},
"devDependencies": {
"airtable": "^0.10.0"
"airtable": "^0.10.0",
"cookie-parser": "^1.4.5"
}
}
10 changes: 7 additions & 3 deletions src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,16 @@ 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);

app.use(express.json());

app.use(cors());
app.use(cookieParser());

////// NON-ADMIN ROUTES //////
app.get("/countries", displayAllCountries);
Expand All @@ -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;
16 changes: 16 additions & 0 deletions src/middleware/auth.js
Original file line number Diff line number Diff line change
@@ -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 };

0 comments on commit 970a9d0

Please sign in to comment.