passport.js 893 B

12345678910111213141516171819202122232425262728293031323334
  1. import { Strategy as JwtStrategy, ExtractJwt } from 'passport-jwt';
  2. import passport from 'passport';
  3. import {User} from "./routes/auth.js";
  4. import dotenv from 'dotenv';
  5. // Geheimschlüssel für JWT
  6. // aus einem ENV File laden
  7. dotenv.config();
  8. const SECRET_KEY = process.env.JWT_SECRET.toString();
  9. const opts = {
  10. jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
  11. secretOrKey: SECRET_KEY
  12. };
  13. passport.use(
  14. new JwtStrategy(opts, async (jwt_payload, done) => {
  15. try {
  16. const user = await User.findById(jwt_payload.id);
  17. if (user) {
  18. return done(null, user); // Successfully authenticated user
  19. } else {
  20. return done(null, false); // No user found
  21. }
  22. } catch (err) {
  23. return done(err, false); // Authentication error
  24. }
  25. })
  26. );
  27. export { passport, SECRET_KEY };