Complete the code to extract the JWT token from the Authorization header.
const token = context.req.headers.authorization?.[1](' ')[1];
The Authorization header usually contains the token prefixed by 'Bearer '. Using split(' ') splits the string into parts, and the token is the second part.
Complete the code to verify the JWT token using the secret key.
const decoded = jwt.[1](token, process.env.JWT_SECRET);The verify method checks the token's validity and decodes it using the secret key.
Fix the error in the code to handle missing or invalid JWT tokens gracefully.
if (!token) throw new Error('[1]');
If the token is missing, the error message should clearly say 'No token provided' to help debugging.
Fill both blanks to create a GraphQL context function that extracts and verifies the JWT token.
const context = ({ req }) => {
const token = req.headers.authorization?.[1](' ')[1];
const user = jwt.[2](token, process.env.JWT_SECRET);
return { user };
};First, split the Authorization header to get the token. Then verify the token with the secret key to get the user info.
Fill all three blanks to create a resolver that checks user authentication using JWT.
const resolver = async (parent, args, context) => {
if (!context.[1]) {
throw new Error('[2]');
}
return await getUserData(context.[3].id);
};The resolver checks if context.user exists. If not, it throws an error saying 'Authentication required'. Then it uses context.user.id to get user data.