简体   繁体   中英

Trouble running passport login Strategy. Authentication error~ TypeError: Cannot read property 'authenticate' of undefined

Things I've tried

  • Moving the authenticate directly into the server
  • Uninstalling and reinstalling the following( as well as their corresponding types ):
    • passport
    • passport-jwt
    • passport-local

All of these still result in getting the following error message :
"TypeError: Cannot read property 'authenticate' of undefined"~Crashing the app

Code

Server File

import * as express from "express";
import apiRouter from "./routes/index";
import * as passport from 'passport';
import * as PassportLocal from 'passport-local';


import './middleware/passport-stradegies';

const app = express();


app.use(passport.initialize());
app.use(express.static("public"));
app.use(express.json());
app.use(apiRouter);

const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Server listening on port: ${port}`));



Passport Login Code

import * as passport from 'passport';
import * as PassportLocal from 'passport-local';
import blogs from "../db/blogs";
import { compareHash } from "../utils";

passport.serializeUser((user, done)=> done(null, user));
passport.deserializeUser((user, done)=> done(null, user));

passport.use(new PassportLocal.Strategy({
    usernameField: 'email'
},async (email, password, done) =>{
    try {
         const [userFound] = await blogs.find("email", email);
          if (userFound && compareHash(password, userFound.userpassword)) {
            done(null, userFound);
    }else{
        done(null, false);
    }
    } catch (error) {
        done(error);
    }
}))

Login / Token Creation Page

import * as express from "express";
// import * as jwt from 'jsonwebtoken';
import { authenticate } from 'passport';
import config from '../../config';


const router = express.Router();

router.post("/", authenticate('local'), async (req, res, next) => {
   try {
  //     const token = jwt.sign({
  //       userid: userFound.id, email: userFound.email, role: 1}, 
  //       config.jwt.secret, {expiresIn: '15d'}
  //       );
  //     return res.json(token);
    res.json('plz');
  } catch (err) {
    console.log(err);
    res.status(500).json({ message: "My code login broke oops" });
  }
});

export default router;

The only problem is passport changed how authenticate is imported

In login/token Authentication Page

Change the import:

// import { authenticate } from 'passport'; to
import * as passport from 'passport';

// then anywhere you use authenticate just use passport.authenticate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM