Express session id not saving in cookie (graphql)

Viewed 698

I cannot for the life of this program figure out why this cookie isn't being saved in the browser. If I run the graphql playground (which is on port 4000, the same as the server), the session ID will be stored in the browser no problem. I have cors enabled so this shouldn't be blocking this. But if I send the login request from any other url, it won't save it in the browser. I have tried multiple browsers and it won't save on any of them and I've tried logging the sessions to make sure I am actually saving them. Any ideas?

const { GraphQLServer } = require('graphql-yoga');
const session = require('express-session');
const bcrypt = require('bcryptjs');
const ms = require('ms');


const typeDefs = `
  type Query {
    isLoggedIn: Boolean!
  }
  type Mutation {
    logIn(email: String!, password: String!): Boolean!
    signUp(email: String!, password: String!): Boolean!
  }
`

// mock mockDBbase
const mockDB = {};

const resolvers = {

  Query: {
    // is the user authenticated
    isLoggedIn: (parent, args, ctx) => {
      return ctx.session.isLoggedIn === true;
    }
  },

  Mutation: {

    // user can sign up for a new account
    signUp: async (parent, { email, password }, ctx) => {
      // if user is already in the DB
      if (mockDB[email]) {
        throw new Error('This user already exists, please log in.');
      }
      const saltRounds = 14; // roughly 1.5 secs on 2GHZ CPU
      // store password in mock DB (replace with real DB)
      mockDB[email] = {
        // salt and hash pw
        password: await bcrypt.hashSync(password, saltRounds),
      };
      return true;
    },

    // authenticates user into respective account
    logIn: async (parent, { email, password }, ctx) => {
      // grab user from DB
      const user = mockDB[email];
      if (user) {
        // make sure pw matches
        if (await bcrypt.compareSync(password, user.password)) {
          // set user logged in flag
          ctx.session.isLoggedIn = true;
          return true;
        }
        throw new Error('User email or password is incorrect.');
      }
      throw new Error('User email or password is incorrect.');
    }
  }
}

// opts
const opts = {
  port: 4000,
  cors: {
    credentials: true,
    origin: "*"
  }
};

// context
const context = req => ({
  session: req.request.session,
});

// server
const server = new GraphQLServer({
  typeDefs,
  resolvers,
  context,
});

const SESSION_SECRET = 'my-super-secret-secret';

server.express.set('trust proxy', 1) // trust first proxy

// session middleware 
server.express.use(
  session({
    name: 'SSID',
    // change this to randomly generate a secret
    secret: SESSION_SECRET,
    resave: false,
    saveUninitialized: true,
    cookie: {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: process.env.NODE_ENV === 'production',
      maxAge: ms('1d'),
    }
  })
);

// start server
server.start(opts, () => console.log(`Server is running on http://localhost:${opts.port}`));
0 Answers
Related