Что заставляет паспорт не проходить проверку подлинности? - PullRequest
0 голосов
/ 13 января 2020

То, что я пытаюсь сделать, это получить паспорт для аутентификации с использованием passport-local-mon goose.

У меня есть один набор кода, который работает, и один набор кода, который не работает хотя я не могу найти никакой разницы между ними. Ошибка генерируется во время части passport.authenticate ("local") в той, которая работает, и следующая функция не вызывается. В той части, которая работает, вызывается следующая функция.

Я публикую код, который работает, а затем код, который не работает.

//jshint esversion:6

const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const session = require('express-session');
const passport = require("passport");
const passportLocalMongoose = require("passport-local-mongoose");


const app = express();

app.use(express.static("public"));
app.use(bodyParser.urlencoded({
  extended: true
}));

app.use(session({
  secret: "a secret.",
  resave: false,
  saveUninitialized: false
}));

app.use(passport.initialize());
app.use(passport.session());


mongoose.connect("mongodb://localhost:27017/userDB", {
  useUnifiedTopology: true,
  useNewUrlParser: true
});

mongoose.set('useCreateIndex', true);


const userSchema = new mongoose.Schema({
  email: String,
  password: String
});

userSchema.plugin(passportLocalMongoose);

const Player = new mongoose.model("User", userSchema);

passport.use(Player.createStrategy());
passport.serializeUser(Player.serializeUser());
passport.deserializeUser(Player.deserializeUser());


app.post("/register", function(req, res) {


  let userName = req.body.username;
  let passWord = req.body.password;

  Player.register({username: userName}, passWord, function(err, user) {
    console.log(user);
    if (err) {
      console.log(err);
      res.send(err);
    } else {
      passport.authenticate("local")(req, res, function() {
        res.send("Authenticated successfully");
      });
    }
  })
});

app.post("/login", function(req, res) {
  const username = req.body.username;
  const password = req.body.password;

  const user = new User({
    username: username,
    password: password
  });

  req.login(user, function(err) {
    if (err) {
      console.log(err);
    } else {
      passport.authenticate("local")(req, res, function() {
        res.send("Logged in Succesffully");
      })
    }
  })
});

app.listen(3000, function() {
  console.log("Server listening on port 3000");
});

И код, который не работает

//jshint esversion:6

const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");

const session = require("express-session");
const passport = require("passport");
const passportLocalMongoose = require("passport-local-mongoose");


const app = express();


app.use(express.static("public"));
app.use(bodyParser.urlencoded({
  extended: true
}));

app.use(session({
  secret: "a secret.",
  resave: false,
  saveUninitialized: false
}));


app.use(passport.initialize());
app.use(passport.session());

//Mongoose set up
mongoose.connect('mongodb://localhost:27017/tictactoeDB',
 {
  useUnifiedTopology: true,
  useNewUrlParser: true
})
.catch((err) => {
  console.log(err);
});             

mongoose.set('useCreateIndex', true);

const playerInfoSchema = new mongoose.Schema({
  email: String,
  password: String
});
playerInfoSchema.plugin(passportLocalMongoose);

const Player = new mongoose.model("Player", playerInfoSchema);

passport.use(Player.createStrategy());
passport.serializeUser(Player.serializeUser());
passport.deserializeUser(Player.deserializeUser());

//Block to handle player data
//IMPORTANT DISABLE BEFORE PRODUCTION
app.get("/api/players", function(req, res) {
  Player.find({}, (err, players) => {
    if (err) {console.log(err); throw err;}

    console.log(`${players.length} players were found and returned`);
    res.send(players);
  });
});

//Creates a new player with given parameters
app.post("/api/players/register", function(req, res) {
  let userName = req.body.userName;
  let passWord = req.body.passWord;

  console.log(`UserName and passWord are ${userName} and ${passWord} `);

  Player.register({username: userName}, passWord, function(err, user) {
    console.log(`User is ${user}`);
    if (err) {
      console.log(err);
      res.send("There was an error registering the player in question");
    } else {
      passport.authenticate("local", function (error, userInternal, info) {
        console.log(`Error in authentication is ${error}`);
        console.log(`UserI in authentication is ${userInternal}`);
        console.log(`Info in authentication is ${info}`);
        res.send(info);

      })(req, res, function() {

        res.send("The player was successfully registered");
      });
    }
  });
});

//Login as the current player
app.post("/api/players/login", function(req, res) {
  const userName = req.body.userName;
  const passWord = req.body.passWord;

  const user = new Player({
    usename: userName,
    password: passWord
  });
  console.log(user)

  req.login(user, function(err) {
    if (err) {
      console.log(err);
      res.send("There was an error while logging in");
    } else {
      passport.authenticate("local", function (error, user, info) {
        // this will execute in any case, even if a passport strategy will find an error
        // log everything to console
        console.log(error);
        console.log(user);
        console.log(info);

        if (error) {
          res.status(401).send(error);
        } else if (!user) {
          res.status(401).send(info);
        } else {
          next();
        }

        res.status(401).send(info);
      })(req, res, function() {
        res.send("You have successfully logged in!");
      });
    }
  })
});



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

...