How do I get authentication to work on my resolvers in graphql social media app?

How do I get authentication to work on my resolvers in graphql social media app?


0

I am a new developer working on a project for a bootcamp, my project is a music social media application using graphql and mern stack. I am working on the resolvers for the cud operations and need to add authentication to my mutations for addPost, removePost, removeUser, addComment addFriend etc. When I run my current code using npm run dev I got to the apollo sandbox and when I try to add a post, remove a post, user etc I keep getting an authentication error in the sandbox. Any help would be greatly appreciated!

Here is resolver for addPost and remove user.

/User can add a post once logged in
    addPost: async (parent, { userId, post }, context) => {
      if (context.user) {
        return User.findByIdAndUpdate(
          { _id: userId },
          {
            $addToSet: { posts: post },
          },
          {
            new: true,
            runValidators: true,
          }
        );
      }
      throw AuthenticationError;
      // throw new GraphQLError("Must be logged in!")
    },

    removeUser: async (parent, { userId }, context) => {
      if (context.user) {

        const deleteUser = await User.findByIdAndDelete(
          {_id: context.user._id},
          { $pull: { user: {userId}}},
          {new: true}
        )
        return deleteUser;
      }
      throw AuthenticationError;
    },

Here is auth.js in utils folder

module.exports = {
  AuthenticationError: new GraphQLError('Could not authenticate user', {
    extensions: {
      code: 'UNAUTHENTICATED'
    }
  }),
  authMiddleware: function ({ req }) {
    // allows token to be sent via req.body, req.query, or headers
    let token = req.body.token || req.query.token || req.headers.authorization;
    // We split the token string into an array and return actual token
    if (req.headers.authorization) {
      token = token.split(' ').pop().trim();
    }
    if (!token) {
      return req;
    }
    // if token can be verified, add the decoded user's data to the request so it can be accessed in the resolver
    try {
      const { data } = jwt.verify(token, secret, { maxAge: expiration });
      req.user = data;
    } catch {
      console.log('Invalid token');
    }
    // return the request object so it can be passed to the resolver as `context`
    return req;
  },
  signToken: function ({ email, name, _id }) {
    const payload = { email, name, _id };
    return jwt.sign({ data: payload }, secret, { expiresIn: expiration });
  },
};

I have tried to add similar logic that is currently in the addUser

// If additional Authentication Needed
        // create a new token
        const token = signToken(newUser);
        // we want to return an AUTH datatype
        return { token, newUser };
      } catch (err) {
        console.log(err);
        throw err;
      }

I was hoping by adding this it would add the token to the other cud operations and would allow me to use them as if a user was registered/logged in.

New contributor

tyler johnson is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.


Load 6 more related questions


Show fewer related questions

0



Leave a Reply

Your email address will not be published. Required fields are marked *