Can I use Passport JWT for multiple user schema in a same express framework

633 Views Asked by At

I am currently working on a project that has multiple User Schema, as Admin, Teacher, Student all are different schema with different structure. The structure is very bad, but all the apis are made cant really change it back.

so the problem is here user authentication is configured by passport and jwt. but its only configured for Teacher.

const Teacher = require("../models/Teacher");
const User = require("../models/User");
const { SECRET } = require("../config");
const { Strategy, ExtractJwt } = require("passport-jwt");

const opts = {
  jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
  secretOrKey: SECRET
};

module.exports = passport => {
  passport.use(
    new Strategy(opts, async (payload, done) => {
      await Teacher.findById(payload.user_id)
        .then(user => {
          if (user) {
            return done(null, user);
          }
          return done(null, false);
        })
        .catch(err => {
          return done(null, false);
        });
    })
  );
};

But I need it for other two schema as well. When I am testing the api for others I simply await Teacher.findById(payload.user_id) change the Teacher to User and it works with the api's userAuth, otherwise it comes unauthorized as expected. Please suggest me an approach ho can I apply it simultaneously for all three Schema without changing it again and again.

2

There are 2 best solutions below

0
On BEST ANSWER

https://github.com/jaredhanson/passport/issues/50

this answers the question in detail.

0
On

You could try something like:

module.exports = passport => passport.use(
  new Strategy(opts, async (payload, done) => {
    try {
      const teacher = await Teacher.findById(payload.user_id);

      if(teacher) return done(null, teacher);

      const user = await User.findById(payload.user_id);

      if(user) return done(null, user);

      const admin = await Admin.findById(payload.user_id);

      if(admin) return done(null, admin);

      return done(null, false);
    }
    catch(err) {
      return done(null, false);
    }
  });
);