Skip to content

Commit

Permalink
feature #12: API protected with Bearer token auth
Browse files Browse the repository at this point in the history
  • Loading branch information
Boosmith committed Aug 29, 2019
1 parent 3a2fba5 commit 070520f
Showing 1 changed file with 21 additions and 1 deletion.
22 changes: 21 additions & 1 deletion src/tools/apiServer.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ server.post("/users/", function(req, res, next) {
}
});

server.post("/users/authenticate", function(req, res, next) {
server.post("/auth/login", function(req, res, next) {
const { userName, password } = req.body;
if (isAuthenticated(userName, password) === false) {
const status = 401;
Expand All @@ -51,6 +51,26 @@ server.post("/users/authenticate", function(req, res, next) {

router.db._.id = "_id";

server.use(/^(?!\/auth).*$/, (req, res, next) => {
if (
req.headers.authorization === undefined ||
req.headers.authorization.split(" ")[0] !== "Bearer"
) {
const status = 401;
const message = "Bad authorization header";
res.status(status).json({ status, message });
return;
}
try {
verifyToken(req.headers.authorization.split(" ")[1]);
next();
} catch (err) {
const status = 401;
const message = "Error: access_token is not valid";
res.status(status).json({ status, message });
}
});

server.use("/api", router);

const port = 3001;
Expand Down

0 comments on commit 070520f

Please sign in to comment.