-
Notifications
You must be signed in to change notification settings - Fork 22
Open
Labels
bugSomething isn't workingSomething isn't workinghelp wantedExtra attention is neededExtra attention is needed
Description
I am searching for a way to test my authorization middleware.
I use express middleware to validate my authorization token.
//isAuth
//simplified
module.exports = (req, res, next) => {
const token = req.headers['x-auth-token'];
if (token invalid) {
req.user = {
isAuth: false,
}
else {
req.user = {
isAuth: true,
_id: decodedToken._id,
name: decodedToken.username,
role: decodedToken.role,
}
next();
}I then apply the middleware
const app = express();
app.use(isAuth);
function createApollo() {
const apollo = new ApolloServer({
schema: graphqlSchema,
context: ({req, res}) => ({req, res}),
});
apollo.applyMiddleware({app, path: "/graphql"});
return apollo
}Lastly, I wrap my graphql-compose resolvers that require authentication with this function:
module.exports = (resolvers) => {
Object.keys(resolvers).forEach((k) => {
resolvers[k] = resolvers[k].wrapResolve(next => async rp => {
if (!rp.context.req.user.isAuth) {
throw new Error('You must login to view this.');
}
return next(rp)
})
})
return resolvers
}In the end I got it working like this:
setOptions({
request: {
user: {
isAuth: true,
_id: decodedToken._id,
name: decodedToken.username,
role: decodedToken.role,
}
},
});but that bypasses my isAuth middleware.
Is there any way, using this or any other package to test middleware as well?
We could add apollo-client or alike as a dev-dependency and test the queries as if there were directly from frontend, but there has to be a better way.
nogashimoni
Metadata
Metadata
Assignees
Labels
bugSomething isn't workingSomething isn't workinghelp wantedExtra attention is neededExtra attention is needed