context.getUser() returns undefined after logging in
See original GitHub issueProblem:
context.getUser()
is not working despite logging in.
To Reproduce: Note: Code was written using these articles and this repo as resources.
- Clone this repo/branch
- Run
yarn
- Run
yarn build:dev
- In a second terminal, run
yarn run:dev
. - 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]
- Run the
currentUser
query (note that the terminal shows us that the user is not authenticated, despite logging in, and thatcontext.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:
- Created 4 years ago
- Comments:9 (2 by maintainers)
Top 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 >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
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
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:
Let me know if this worked
@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.