2018-02-18 02:00:56 +00:00
|
|
|
const AuthAPI = require("../AuthAPI");
|
2017-11-11 20:18:13 +00:00
|
|
|
|
2018-02-18 02:00:56 +00:00
|
|
|
const ReadMethods = { GET: true, HEAD: true };
|
2017-11-11 20:18:13 +00:00
|
|
|
|
2018-09-01 16:36:48 +00:00
|
|
|
function decodeBase64(string) {
|
|
|
|
return Buffer.from(string, "base64").toString();
|
|
|
|
}
|
|
|
|
|
2017-11-11 20:18:13 +00:00
|
|
|
/**
|
|
|
|
* Sets req.user from the payload in the auth token in the request.
|
|
|
|
*/
|
|
|
|
function userToken(req, res, next) {
|
|
|
|
if (req.user) {
|
2018-02-18 02:00:56 +00:00
|
|
|
return next();
|
2017-11-11 20:18:13 +00:00
|
|
|
}
|
|
|
|
|
2018-09-01 16:36:48 +00:00
|
|
|
const auth = req.get("Authorization");
|
|
|
|
const token = auth
|
|
|
|
? decodeBase64(auth)
|
2018-09-01 13:37:48 +00:00
|
|
|
: (ReadMethods[req.method] ? req.query : req.body).token;
|
2017-11-11 20:18:13 +00:00
|
|
|
|
|
|
|
if (!token) {
|
2018-02-18 02:00:56 +00:00
|
|
|
req.user = null;
|
|
|
|
return next();
|
2017-11-11 20:18:13 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
AuthAPI.verifyToken(token).then(
|
|
|
|
payload => {
|
2018-02-18 02:00:56 +00:00
|
|
|
req.user = payload;
|
|
|
|
next();
|
2017-11-11 20:18:13 +00:00
|
|
|
},
|
|
|
|
error => {
|
2017-11-25 21:25:01 +00:00
|
|
|
if (error.name === "JsonWebTokenError") {
|
2017-11-11 20:18:13 +00:00
|
|
|
res.status(403).send({
|
|
|
|
error: `Bad auth token: ${error.message}`
|
2018-02-18 02:00:56 +00:00
|
|
|
});
|
2017-11-11 20:18:13 +00:00
|
|
|
} else {
|
2018-02-18 02:00:56 +00:00
|
|
|
console.error(error);
|
2017-11-11 20:18:13 +00:00
|
|
|
|
|
|
|
res.status(500).send({
|
2017-11-25 21:25:01 +00:00
|
|
|
error: "Unable to verify auth"
|
2018-02-18 02:00:56 +00:00
|
|
|
});
|
2017-11-11 20:18:13 +00:00
|
|
|
}
|
|
|
|
}
|
2018-02-18 02:00:56 +00:00
|
|
|
);
|
2017-11-11 20:18:13 +00:00
|
|
|
}
|
|
|
|
|
2018-02-18 02:00:56 +00:00
|
|
|
module.exports = userToken;
|