护照在表格上缺少凭证

时间:2020-03-06 11:26:55

标签: mysql node.js express session passport.js

我正在使用MySQL开发一个nodejs express应用程序,并且为了进行会话,身份验证和授权,我使用的是护照,我不知道为什么,但是当我创建帐户时一切正常。正在创建用户。

但是,当我登录时,它返回一条错误消息,提示“缺少凭据”。 我已经看到了关于此问题的所有其他Stackoverflow问题,但没有找到解决方案。

app.js

const express = require("express");
const cors = require('cors');
const accountRoute = require("./routes/account");

const app = express();

app.use(cors());

app.use(express.json());
app.use(express.urlencoded({ extended: true }));


app.set("view engine","ejs");

app.use(express.static(__dirname + '/views'));

app.use(accountRoute.app)
app.use(accountRoute.router);

app.get("/", (req,res) => {
    res.render("index.ejs");
});


app.listen(8000, () => console.log(`Listening on port 8000...`));

登录并注册

const express = require('express');
const session = require('express-session');
const flash = require('express-flash');
const bcrypt = require('bcryptjs');
const passport = require('passport');
const config = require('../config');
const initalizePassport = require('../passport');
const user = require('../models/user').User;
const router = express.Router();
const app = express();


initalizePassport(passport, async (email) => {
    return await user.findOne({ where: { "email": email } }) === email;
}, async (id) => {
    return await user.findOne({ where: { "id": id } }) === id;
});

app.use(session({
    secret: config.sessionPassword,
    resave: false,
    saveUninitialized: false
}));

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

app.use(flash());

router.get('/login', (req, res) => {
    res.render('login.ejs');
});

router.post('/login', passport.authenticate('local', {
    successRedirect: '/',
    failureRedirect: '/login',
    failureFlash: true
}));

router.get('/register', (req, res) => {
    res.render('register.ejs');
});

router.post('/register', async (req, res) => {
    try {
        const hashedPassword = await bcrypt.hashSync(req.body.userpass, 10);
        user.create({
            "email": req.body.email,
            "username": req.body.username,
            "userpass": hashedPassword
        });
        res.redirect('/login');
    } catch (error) {
        res.redirect('/register');
    }
});

router.get('/unregister', (req, res) => {
    res.render('unregister.ejs');
});

router.post('/unregister', (req, res) => {
    res.send(req.body);
});

module.exports.router = router;
module.exports.app = app;

passport.js

const LocalStrategy = require('passport-local').Strategy
const bcrypt = require('bcryptjs')

function initialize(passport, getUserByEmail, getUserById) {
  const authenticateUser = async (email, userpass, done) => {
    const user = getUserByEmail(email);
    if (!user) {
      return done(null, false, { message: 'No user with that email' })
    }

    try {

      var correctPassword = false;

      await bcrypt.compare(userpass, user.userpass, function (err, result) {
        if (err) {
          console.log(err);
        }
        else {
          correctPassword = true;
          console.log("passwords match!");
          return;
        }
      });

      if (correctPassword) {
        return done(null, user)
      } else {
        return done(null, false, { message: 'Password incorrect' })
      }
    } catch (e) {
      return done(e)
    }
  }

  passport.use(new LocalStrategy({ usernameField: 'email', passwordField: 'userpass' }, authenticateUser))
  passport.serializeUser((user, done) => done(null, user.id))
  passport.deserializeUser((id, done) => {
    return done(null, getUserById(id))
  })
}

module.exports = initialize

Login.ejs

<h1>Login</h1>
<% if(messages.error) { %>
    <%= messages.error %>
<% } %>
<form action="/login" method="post">
    <input name="email" type="text" placeholder="email">
    <input name="userpass" type="password" placeholder="userpass">
    <input type="submit" value="submit">
</form>

现在把它扔给我了

Error: Illegal arguments: string, undefined
    at _async (C:\Users\datte\Desktop\auth\node_modules\bcryptjs\dist\bcrypt.js:286:46)
    at C:\Users\datte\Desktop\auth\node_modules\bcryptjs\dist\bcrypt.js:307:17
    at new Promise (<anonymous>)
    at Object.bcrypt.compare (C:\Users\datte\Desktop\auth\node_modules\bcryptjs\dist\bcrypt.js:306:20)      
    at Strategy.authenticateUser [as _verify] (C:\Users\datte\Desktop\auth\passport.js:13:24)
    at Strategy.authenticate (C:\Users\datte\Desktop\auth\node_modules\passport-local\lib\strategy.js:90:12)
    at attempt (C:\Users\datte\Desktop\auth\node_modules\passport\lib\middleware\authenticate.js:366:16)    
    at authenticate (C:\Users\datte\Desktop\auth\node_modules\passport\lib\middleware\authenticate.js:367:7)
    at Layer.handle [as handle_request] (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\datte\Desktop\auth\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\index.js:335:12)
    at next (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\index.js:275:10)
    at Function.handle (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\index.js:174:3)
    at router (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\index.js:47:12)
    at Layer.handle [as handle_request] (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\index.js:317:13)
    at C:\Users\datte\Desktop\auth\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\index.js:335:12)
    at next (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\index.js:275:10)
Executing (default): SELECT `id`, `email`, `username`, `userpass`, `createdAt`, `updatedAt` FROM `Users` AS `User` WHERE `User`.`email` = 'myemail' LIMIT 1;

0 个答案:

没有答案