Unable to save session with passport.js after signing up

19 views Asked by At

So, I am learning passport.js, everything seems to be working fine until, signing up a user.

NOTE: I am just playing with json-server now, so no db.

app.post('/signup', async (req, res) => {
  const { email, username, password } = req.body;

  if (!email || !username || !password) {
    req.flash('error', 'Missing credentials');
    res.redirect('/signup');
    return;
  }

  const response = await fetch('http://localhost:3000/users', {
    method: 'post',
    body: JSON.stringify(req.body),
    headers: { 'Content-Type': 'application/json' },
  });
  const data = await response.json();

  req.login(req.body, (err) => {
    if (err) {
      return next(err);
    }
    res.redirect('/posts');
  });
});

So my signup route works as expected by redirectly me to the /posts page with the new user object in the req.user.

app.get('/posts/', async (req, res) => {
  if (req.isAuthenticated()) {
    console.log(req.user);
    const response = await fetch('http://localhost:3000/posts');
    const data = await response.json();
    const sortedData = data.toSorted(
      (a, b) => new Date(b.date) - new Date(a.date)
    );
    const users = await getUsers();

    const newData = sortedData.map((post) => ({
      ...post,
      author: users.find((user) => parseInt(user.id) === post.userId).username,
    }));

    res.render('posts.ejs', { posts: newData, user: req.user });
  } else {
    res.redirect('/signin');
  }
});

Just some code for getting and orgnaization data from my json-server.

Everything works fine immediately after signing up. However, when I refresh the page or click to another page and come back, I will be redirected to the sign in page, sign in again before the authenticated again.

Here's my code for the passport:

passport.use(
  new LocalStrategy(async function verify(username, password, cb) {
    const users = await getUsers();

    const matchedUser = users.find((user) => user.username === username);
    if (!matchedUser || matchedUser.password !== password) {
      return cb(null, false, { message: 'Incorrect username or password.' });
    }

    return cb(null, matchedUser);
  })
);

passport.serializeUser(function (user, cb) {
  cb(null, user);
});

passport.deserializeUser(function (user, cb) {
  cb(null, user);
});

My cookie settings:

app.use(
  session({
    secret: 'secretStringForNow',
    resave: false,
    saveUninitialized: false,
    cookie: {
      maxAge: 1000 * 60 * 60 * 24,
    },
  })
);
app.use(passport.initialize());
app.use(passport.session());

I am just wondering if someone could help, I've tried to look through the doc, but I can't find everything there.

Thanks!

0

There are 0 answers