Home > Enterprise >  How to use Passport.js with Prisma
How to use Passport.js with Prisma

Time:11-24

I'm following the tutorials from theodinproject right now and I'm having trouble with the user authentication. In the tutorials, they used Mongodb with Mongoose to integrate with the Passport.js but in my case, I use Postgres with Prisma to integrate with the Passport.js so the code will be a little bit different. I checked both theodinproject and doc from Passport.js one use Mongoose and one uses raw SQL code. So I don't know how to do it with Prisma. I tried to do some research to see if anyone has done this before but I don't see many results for that.

I tried to type something to play along with it and comes up with the code below

passport.use(async (username, password, done) => {
  const user = await prisma.user.findFirst(
    { where: { username } },
    (err, user) => {
      if (err) {
        return done(err);
      }
      if (!user) {
        return done(null, false, { message: "Incorrect username" });
      }
      if (user.password !== password) {
        return done(null, false, { message: "Incorrect password" });
      }
      return done(null, user);
    }
  );
});

Clearly, it's wrong (because the app crashed) but I don't know how to fix that. Can anyone help me with this?

Thank you in advance :)

CodePudding user response:

Are you trying to do something like this?

passport.use(async (username, password, done) => {
  const user = await prisma.user.findFirst(
    { where: { username } },
  );

  if (!user) {
    return done(null, false, { message: "Incorrect username" });
  }
  if (user.password !== password) {
    return done(null, false, { message: "Incorrect password" });
  }
  return done(null, user);
});

findFirst takes only one parameter

If you really want to catch a possible error, something that shouldn't happen unless your database is down maybe, you can do

passport.use(async (username, password, done) => {
  try {
    const user = await prisma.user.findFirst(
      { where: { username } },
    );

    if (!user) {
      return done(null, false, { message: "Incorrect username" });
    }
    if (user.password !== password) {
      return done(null, false, { message: "Incorrect password" });
    }
    return done(null, user);
  } catch (error) {
    return done(err);
  }
});
  • Related