3
votes

initially my authentication was working ok. then i left the computer on and came back to code again and this time, my authentication failed with following message

[GraphQL error]: Message: Context creation failed: Your session has ended. Please sign in again, Location: undefined, Path: undefined

i had set an expiry for the token. I tried to clear the cache before signin but still get the above error.

below is my code for the signin function

 _handleSubmit = (values, bag, signIn) => {
    signIn({
      variables: {
        email: values.email,
        password: values.password
      }
    })
      .then(async ({ data }) => {
        if (data && data.signIn.token) {
          await AsyncStorage.setItem("token", data.signIn.token);
          this.props.navigation.navigate("Main");
        }
      })
      .catch(err => {
        bag.setSubmitting(false);
        bag.setErrors(err);
      });
  };

my stack is apollo, mongodb, react-native. i suspected the problem might be the caching. i tried to clear the cache but clearning the cache on Expo by pressing "R" but i still can't log in.

[Update] the error is due to jwt token expired. I get this error when I console.log(@res, res) in getUser function

{ TokenExpiredError: jwt expired...

funny thing though is i created a new jwt token for each signin. below is my codes for createToken and getUser

Anyone encountered such situation before? How do you solve it?

const createToken = (user, expiresIn) => {
  const { _id, email } = user;
  //creturn jwt.sign({ _id, email }, process.env.SECRET_KEY, { expiresIn });
  return jwt.sign({ _id, email }, process.env.SECRET_KEY);
};


const getUser = async token => {
  if (token) {
    try {
      const res = await jwt.verify(token, process.env.SECRET_KEY);
      console.log("@res ", res);
      return res;
    } catch (error) {
      console.log("@error ", error);
      throw new AuthenticationError(
        "Your session has ended. Please sign in again"
      );
    }
  }
};

Thanks

2

2 Answers

1
votes

i ran in my ApolloClient's authLink...

await AsyncStorage.removeItem("token"); 

then commented it out, n it worked again!

const authLink = setContext(async (req, { headers }) => {
  // await AsyncStorage.removeItem("token");
  const token = await AsyncStorage.getItem("token");
  console.log("@token ", token);

  return {
    headers: {
      ...headers,
      authorization: token ? `${token}` : ""
    }
  };
});
0
votes

Just make sure you don't send undefined as a token in headers on the frontend. Usually in App.js when an unauthorized user tries to login.