注册登录错误包括护照

时间:2018-03-02 02:39:22

标签: node.js passport.js

所以我正在寻求实施护照,而且我遇到了包含问题。

这是我到目前为止所做的:

users_controller.js

var nodemailer = require('nodemailer');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;

var User = require('../models/user');

exports.register = function(req, res, next) {
  res.render('register', { title: 'Rafflefly | Register' });
}

exports.post_register = function(req, res, next) {
  var first_name = req.body.first_name;
  var last_name = req.body.last_name;
  var email = req.body.email;
  var password = req.body.password;

  // validations
  req.checkBody('first name', 'The first name is required').notEmpty();
  req.checkBody('last name', 'The last name is required').notEmpty();
  req.checkBody('email', 'An account email is required').notEmpty();
  req.checkBody('email', 'This account email is not valid').isEmail();
  req.checkBody('password', 'An account password is required').notEmpty();

  if (error) {
    req.flash('error', 'The form could not send successfully');
  } else {
    var newUser = new User({
      first_name: first_name,
      last_name: last_name,
      email: email,
      password: password,
    });

    nodemailer.createTestAccount((err, account) => {
      // create reusable transporter object using the default SMTP transport
      if (process.env.NODE_ENV === 'production') {
        transporter = nodemailer.createTransport({
          host: "smtp.sendgrid.net",
          port: 587,
          auth: {
            user: process.env.SENDGRID_USERNAME,
            pass: process.env.SENDGRID_PASSWORD,
          }
        });
      } else {
        transporter = nodemailer.createTransport({
          host: "smtp.ethereal.email",
          port: 587,
          auth: {
            user: 'qkkvnabtziufbksa@ethereal.email',
            pass: 'A4W9HF2WbhAav263VM',
          }
        });
      }
      // setup email data with unicode symbols
      let mailOptions = {
        from: process.env.GLOBAL_EMAIL || 'ben@benbagley.co.uk', // sender address
        to: `${email}`, // list of receivers
        subject: 'Welcome to Rafflefly', // Subject line
        html: `Welcome to Rafflefly` // html body
      };
      // send mail with defined transport object
      transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
          return console.log(error);
        }

        req.flash('success', 'You are now registered, you can now login!');
        res.redirect('/');
      });
    });

    User.createUser(newUser, function(err, user) {
      if(err) throw err;
      console.log(user);
    });
  }
};

  passport.use(new LocalStrategy({
    usernameField: 'email'
    },
    function(email, password, done) {
      User.getUserByEmail(email, function(err, user){
        if(err) throw err;
        if(!user){
          return done(null, false, {message: 'Unknown Email Address'});
        }

        User.comparePassword(password, user.password, function(err, isMatch){
          if(err) throw err;
          if(isMatch){
            return done(null, user);
          } else {
            return done(null, false, {message: 'Invalid password'});
          }
        });
      });
    }));

  passport.serializeUser(function(user, done) {
    done(null, user.id);
  });

  passport.deserializeUser(function(id, done) {
    User.getUserById(id, function(err, user) {
      done(err, user);
    });
  });

exports.login = function(req, res, next) {
  res.render('login', { title: 'Rafflefly | Login' });
}

exports.post_login = function(req, res, next) {
  res.post('/login', passport.authenticate('local', {
    successRedirect: '/dashboard',
    failureRedirect: '/login',
    failureFlash: true })
  );
}

layout.pug

doctype html
html
  head
    title= title
    meta(name='viewport' content='width=device-width, initial-scale=1')
    meta(charset='utf-8')

    link(rel='stylesheet' href='/stylesheets/output.css')
    link(rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css')
  body(class='antialiased min-h-screen')
    include navigation
    include error
    block content
    include footer

    script(src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js')
    script(src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.min.js')
    script(src='/javascripts/fontawesome-all.min.js' defer)
    script(src='/javascripts/site.js')

这是我的文件结构

image

因此所有其他页面都在这里工作,但是当我提交注册表单时,我收到错误,注册页面确实加载但是这个错误似乎只是在提交表单时发生在帖子中。

我得到的错误是

[nodemon] 1.15.0
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node ./bin/www`
Connection has been established
Mongoose: users.ensureIndex({ email: 1 }, { unique: true, background: true })
Error: Failed to lookup view "error" in views directory "/Users/benbagley/Code/rafflefly/views"
    at Function.render (/Users/benbagley/Code/rafflefly/node_modules/express/lib/application.js:580:17)
    at ServerResponse.render (/Users/benbagley/Code/rafflefly/node_modules/express/lib/response.js:971:7)
    at /Users/benbagley/Code/rafflefly/app.js:88:7
    at Layer.handle_error (/Users/benbagley/Code/rafflefly/node_modules/express/lib/router/layer.js:71:5)
    at trim_prefix (/Users/benbagley/Code/rafflefly/node_modules/express/lib/router/index.js:315:13)
    at /Users/benbagley/Code/rafflefly/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/Users/benbagley/Code/rafflefly/node_modules/express/lib/router/index.js:335:12)

    at next (/Users/benbagley/Code/rafflefly/node_modules/express/lib/router/index.js:275:10)
    at Layer.handle_error (/Users/benbagley/Code/rafflefly/node_modules/express/lib/router/layer.js:67:12)
    at trim_prefix (/Users/benbagley/Code/rafflefly/node_modules/express/lib/router/index.js:315:13)
    at /Users/benbagley/Code/rafflefly/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/Users/benbagley/Code/rafflefly/node_modules/express/lib/router/index.js:335:12)
    at next (/Users/benbagley/Code/rafflefly/node_modules/express/lib/router/index.js:275:10)
    at Layer.handle_error (/Users/benbagley/Code/rafflefly/node_modules/express/lib/router/layer.js:67:12)
    at trim_prefix (/Users/benbagley/Code/rafflefly/node_modules/express/lib/router/index.js:315:13)
    at /Users/benbagley/Code/rafflefly/node_modules/express/lib/router/index.js:284:7
POST /register 500 248.111 ms - 2006

感谢您的任何帮助。

编辑1

app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var bodyParser = require('body-parser');
var nodemailer = require('nodemailer');
var flash = require('connect-flash');
var passport = require('passport');
var mongoose = require('mongoose');
var LocalStrategy = require('passport-local').Strategy;
var sslRedirect = require('heroku-ssl-redirect');

var index = require('./routes/index');

var app = express();
var port = process.env.PORT || 3000;

mongoose.set('debug', true); // Only set when debugging

// enable ssl redirect
app.use(sslRedirect());

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// expressSession
app.use(session({
  secret: 'secret',
  saveUninitialized: true,
  resave: true
}));

// Connect Flash
app.use(flash());
app.use((req, res, next) => {
  res.locals.success = req.flash('success');
  res.locals.errors = req.flash('error');
  next();
});

app.use('/', index);

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

// Database connection
if (app.get('env') === 'production') {
  mongoose.connect(process.env.MONGODB_URI);
} else {
  mongoose.connect('mongodb://localhost/rafflefly');
}

var db = mongoose.connection;
mongoose.Promise = global.Promise;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  console.log("Connection has been established");
});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error'); // line 88
});

module.exports = app;

1 个答案:

答案 0 :(得分:0)

https://stackoverflow.com/users/8436941/continuousload

提及的res.render('shared/error.pug)已添加