passport.js 632 B

1234567891011121314151617181920212223
  1. const passport = require("passport");
  2. const UserModel = require("../model/user");
  3. const { Strategy, ExtractJwt } = require("passport-jwt");
  4. require("dotenv").config();
  5. const SECRET_KEY = process.env.JWT_SECRET;
  6. const params = {
  7. secretOrKey: SECRET_KEY,
  8. jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
  9. };
  10. passport.use(
  11. new Strategy(params, async ({ id }, done) => {
  12. try {
  13. const user = await UserModel.findById(id);
  14. if (!user) return done(new Error("User not found"));
  15. if (!user.token) return done(null, false);
  16. return done(null, user);
  17. } catch (err) {
  18. done(err);
  19. }
  20. })
  21. );