Reputation: 29
I have a simple social media app that uses: GraphQL & ApolloServer as a backend where users can like posts. But an error occurs when a user who isn't logged in tries to like a button and an error called:
Unhandled Rejection (Error): GraphQL error: Authorization header must be provided
occurs.
This is the code for the likePost mutation...
async likePost(_, { postId }, context) {
const { username } = checkAuth(context);
const post = await Post.findById(postId);
if (post) {
if (post.likes.find((like) => like.username === username)) {
post.likes = post.likes.filter((like) => like.username !== username);
} else {
post.likes.push({
username,
createdAt: new Date().toISOString()
});
}
await post.save();
return post;
} else throw new UserInputError('Post not found');
}
},
This is the code for checking authorization file.
const { AuthenticationError } = require('apollo-server');
const jwt = require('jsonwebtoken');
const { SECRET_KEY } = require('../config');
module.exports = (context) => {
// context = { ... headers }
const authHeader = context.req.headers.authorization;
if (authHeader) {
// Bearer ....
const token = authHeader.split('Bearer ')[1];
if (token) {
try {
const user = jwt.verify(token, SECRET_KEY);
return user;
} catch (err) {
throw new AuthenticationError('Invalid/Expired token');
}
}
throw new Error("Authentication token must be 'Bearer [token]");
}
throw new Error('Authorization header must be provided'); };
How do I go about solving this problem so that no error comes up when an unregistered user tries to like a post?
Upvotes: 0
Views: 813
Reputation: 11
If you are referring to this video to build the social media app (https://www.youtube.com/watch?v=n1mdAPFq2Os&ab_channel=freeCodeCamp.org). You might get this error because of the Button component in the LikeButton.js file.
<Button as='div' labelPosition='right' onClick={likePost}>
<CustomPopup content={liked? 'unlike post': 'like post'}>
{likeButton}
</CustomPopup>
</Button>
This Button component will execute the onClick method you specified (not the '/login'
path specified in the {likeButton}
) which is doing the mutation of the database and which will need a authorization header to do it. Therefore, when you are not login (no authorization header) but click on the like button, you will get an error.
And here is how I modified:
return(
user? (
<Button as='div' labelPosition='right' onClick={likePost}>
<CustomPopup content={liked? 'unlike post': 'like post'}>
{likeButton}
</CustomPopup>
</Button>
):(
<Button labelPosition='right' as='a' href='/login'>
<CustomPopup content={liked? 'unlike post': 'like post'}>
{likeButton}
</CustomPopup>
</Button>
)
);
Upvotes: 1