easygraphql-format-error
easygraphql-format-error copied to clipboard
graphql middleware auth don't worked.
Hi, I have a problem with the connection authorization after you connect the easygraphql-format-error. The problem is that, I give information about authorization in req due to the fact that I connected the plugin in context, it stopped being defined.
isAuth.js:
const jwt = require("jsonwebtoken");
module.exports = (req, res, next) => {
const authHeader = req.get("Authorization");
if (!authHeader) {
req.isAuth = false;
return next();
}
const token = authHeader.split(" ")[1];
if (!token || token === "") {
req.isAuth = false;
return next();
}
let decodedToken;
try {
decodedToken = jwt.verify(token, "somesupersecretkey");
} catch (err) {
req.isAuth = false;
return next();
}
if (!decodedToken) {
req.isAuth = false;
return next();
}
req.isAuth = true;
req.userId = decodedToken.userId;
next();
};
app.js:
app.use(isAuth);
app.use("/", (req, res) => {
console.log("req", req),
graphqlHttp({
schema: schema,
rootValue: graphQlResolvers,
graphiql: true,
context: { errorName },
formatError: err => {
return formatError.getError(err);
}
})(req, res);
});
I apologize in advance for my English...
I solved this problem like this:
context: { errorName, isAuth: req.isAuth, userId: req.userId }
Perhaps someone has a better solution? Advance thanks.