question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

context.getUser() returns undefined after logging in

See original GitHub issue

Problem: context.getUser() is not working despite logging in.

To Reproduce: Note: Code was written using these articles and this repo as resources.

  1. Clone this repo/branch
  2. Run yarn
  3. Run yarn build:dev
  4. In a second terminal, run yarn run:dev.
  5. Login (note that the terminal does show us that the user is authenticated and context.getUser works).
mutation {
  login(email: "maurice@moss.com", password: "abcdefg") {
    user {
      id
      firstName
      lastName
      email
    }
  }
}

terminal response:

--- login response ---
isAuthenticated: true
isUnauthenticated: false
getUser: [object Object]
  1. Run the currentUser query (note that the terminal shows us that the user is not authenticated, despite logging in, and that context.getUser returns undefined):
query{
  currentUser{
    id
  }
}

terminal response:

--- currentUser response ---
isAuthenticated: false
isUnauthenticated: true
getUser: undefined

Main code used: index.ts:

import { ApolloServer } from 'apollo-server-express';
import express from 'express';
import http from 'http';
import passport from 'passport';
import session from 'express-session';
import uuid from 'uuid/v4';
import { GraphQLLocalStrategy, buildContext } from 'graphql-passport';
import Users from './users';
import resolvers from './resolvers';
import typeDefs from './typeDefs';

passport.serializeUser((user, done) => {
  // @ts-ignore
  done(null, user.id);
});

passport.deserializeUser((id, done) => {
  const users = Users.getUsers();
  const matchingUser = users.find((user) => user.id === id);
  done(null, matchingUser);
});

passport.use(
  new GraphQLLocalStrategy((email, password, done) => {
    const users = Users.getUsers();
    const matchingUser = users.find((user) => email === user.email && password === user.password);
    const error = matchingUser ? null : new Error('no matching user');
    done(error, matchingUser);
  }),
);

const server = new ApolloServer({
  context: ({ req, res }) => buildContext({ req, res, Users }),
  resolvers,
  typeDefs,
});

export default server;

// Adds express as middleware to our server.
const app = express();
app.use(session({
  // cookie: { secure: true }, // cookie must be sent via https
  genid: (request) => uuid(), // generates a session ID
  resave: false,
  saveUninitialized: false,
  secret: 'bad secret', // secret that is needed to sign the cookie
}));

app.use(passport.initialize());
app.use(passport.session());

server.applyMiddleware({ app });

const PORT = 4000;

// We create an http server from our apollo server.
const httpServer = http.createServer(app);
server.installSubscriptionHandlers(httpServer);

// We run our http server.
httpServer.listen(PORT, () => {
  console.log(`Server ready at http://localhost:${PORT}${server.graphqlPath}`);
  console.log(`Subscriptions ready at ws://localhost:${PORT}${server.subscriptionsPath}`);
});

// Using webpack's hot module replacement, if needed.
if (module.hot) {
  module.hot.accept();
  module.hot.dispose(() => server.stop());
}

resolvers.ts:

const resolvers = {
  Query: {
    currentUser: (parent, args, context) => {
      console.log('--- currentUser response ---');
      console.log(`isAuthenticated: ${context.isAuthenticated()}`);
      console.log(`isUnauthenticated: ${context.isUnauthenticated()}`);
      console.log(`getUser: ${context.getUser()}`);
      return context.getUser();
    },
  },
  Mutation: {
    login: async (parent, { email, password }, context) => {
      const { user } = await context.authenticate('graphql-local', { email, password });
      context.login(user);

      console.log('--- login response ---');
      console.log(`isAuthenticated: ${context.isAuthenticated()}`);
      console.log(`isUnauthenticated: ${context.isUnauthenticated()}`);
      console.log(`getUser: ${context.getUser()}`);

      return { user };
    },
  },
};

export default resolvers;

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:9 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
jkettmanncommented, Jan 4, 2020

Hi Jimmy, thanks for this issue. I checked your repository and everything seems to be fine. Actually, when I run the project the login is working for me. Can you check if the connect.sid cookie is set after login? If it’s currently set please delete it first.

One thing that comes to my mind is the playground settings. In the repo you mentioned the playground settings are defined inside the code as

playground: {
  settings: {
    'request.credentials': 'same-origin',
  },
},

You can also do this manually by opening the settings via the gear symbol in the right top in the playground and add following line:

"request.credentials": "same-origin"

Let me know if this worked

0reactions
gforgecommented, Jan 6, 2020

@jkettmann - yeah, I guess you’re right. My instinct was that the login will probably be queued to be handled after the failing contexts as they happen in @jimmy-e’s example code. Anyway, hopefully the typings should help users to correctly call the functions.

Read more comments on GitHub >

github_iconTop Results From Across the Web

context.getUser() returns undefined after logging in #20 - GitHub
Problem: context.getUser() is not working despite logging in. To Reproduce: Note: Code was written using these articles and this repo as ...
Read more >
accessing useContext state-variable returns undefined value
I am trying to implement authentication flow where a User can log in and log out. If the user presses a button in...
Read more >
[Solved] In the server this.userId returns undefined when has a ...
I was suppose to do this method and unexpectedly felt on an inconvenient trouble by my side. // /imports/api/usersAdminFieldPublish.js ...
Read more >
Auth0Client is undefined - Auth0 Community
I'm having an issue getting started with Auth0. I have been able to successfully login to my app, but it's inconsistent. I often...
Read more >
Authentication and authorization - Apollo GraphQL Docs
const user = await getUser(token);. 28. 29. // Add the user to the context. 30. return { user };. 31. },. 32. });....
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found