无法通过express和mysql

时间:2018-01-31 21:51:44

标签: mysql node.js express passport.js

我正在尝试使用护照实施本地策略,以便用户可以根据mysql的数据库凭据登录。但是我一直在查看"查看错误"出于某种原因,当我尝试使用我的登录表单登录时。

当我在没有凭据的情况下登录时,它会发出一个" Missing Credential"连接闪存错误。但是当我在登录时输入用户名和密码时,我得到一个"无法查找视图"错误"在views目录"。

我希望有人能指出问题在我的代码中的位置。

我的结构以这种方式设置

config
 --database.js
 --passport.js
models
 --user.js
routes
 --users.js
views
 --login.js
app.js

app.js文件

const express = require('express');
const mysql = require('mysql');
const path = require('path');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const expressValidator = require('express-validator');
const flash = require('connect-flash');
const session = require('express-session');
const passport = require('passport');
const config = require('./config/database');

// Init MySql
const db = mysql.createConnection(config);

db.connect((err) => {
    if(err) throw err;
    console.log('MySql Connected...');
});

// Init App
const app = express();

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

// Connect to public directory
// 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')));

// Express Session Middleware
app.use(session({
    secret: 'secretKey',
    resave: true,
    saveUninitialized: true
}));

// Express Messages Middleware
app.use(require('connect-flash')());
app.use((req, res, next) => {
    res.locals.messages = require('express-messages')(req, res);
    next();
});

// Express Validator Middleware
app.use(expressValidator({
    errorFormatter: (param, msg, value) => {
        var namespace = param.split('.'),
        root = namespace.shift(),
        formParam = root;
    while(namespace.length) {
        formParam += '[' + namepsace.shift() + ']';
    }
    return {
        param: formParam,
        msg: msg,
        value: value
    };
    }
}));

// Passport Config
require('./config/passport')(passport);
// Passport Middleware
app.use(passport.initialize());
app.use(passport.session());


// Route Files
let index = require('./routes/index');
let users = require('./routes/users');
let posts = require('./routes/posts');

// Routers
app.use('/', index);
app.use('/users', users);
app.use('/posts', posts);

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

// error handler
app.use((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');
});

// Start Server
app.listen('3000', (req, res, next) => {
    console.log('Server started on port 3000...');
});

module.exports = app;

模型/ user.js的

let mysqlModel = require('mysql-model');
const config = require('../config/database');

let UserModel = mysqlModel.createConnection(config);

// User Model
let User = UserModel.extend({
    tableName: 'users'
});

module.exports = User;

路由/ users.js

const express = require('express');
const mysql = require('mysql');
const router = express.Router();
const config = require('../config/database');
const bcrypt = require('bcryptjs');
const passport = require('passport');

// Init MySql
const db = mysql.createConnection(config);

// User Model
let User = require('../models/user');

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

// Login Process
router.post('/login', (req, res, next) => {
    passport.authenticate('local', {
        successRedirect: '/',
        failureRedirect: '/users/login',
        failureFlash: true
    })(req, res, next);
});

module.exports = router;

配置/ passport.js

const LocalStrategy = require('passport-local').Strategy;
const mysql = require('mysql');
const bcrypt = require('bcryptjs');
const config = require('../config/database');

// Init MySql
const db = mysql.createConnection(config);

// User Model
const User = require('../models/user');

module.exports = (passport) => {
    // Local Strategy
    passport.use(new LocalStrategy((username, password, done) => {
        // Match Username
        let query = {username:username};
        User.findOne(query, (err, user) => {
            if(err) throw err;
            if(!user){
                return done(null, false, {message: 'No user found'});
            }
        // Match Password
        bcrypt.compare(password, user.password, (err, isMatch) => {
                if(err) throw err;
                if(isMatch){
                    return done(null, user);
                } else {
                    return done(null, false, {message: 'Wrong Password'});
                }
            });
        });
    }));
            passport.serializeUser(function(user, done) {
                done(null, user.id);
        });
            passport.deserializeUser(function(id, done) {
            User.findById(id, function(err, user) {
            done(err, user); done(err, user);
        });
    });
}

视图/ login.pug

extends layout

block content
        h1 Login
        hr
        form(method='POST', action='/users/login')
            #form-group
                label Username
                input.form-control(name='username', type='text')
            #form-group
                label Password
                input.form-control(name='password', type='password')
                br
                input.btn.btn-primary(type='submit', value='Submit')

我已经被困了很长时间,任何帮助都会受到赞赏。谢谢。

1 个答案:

答案 0 :(得分:1)

我不能简单评论,因为我没有声誉。但是我在app.js中的中间件堆栈顺序方面遇到了类似的问题。

您是否使用用户序列化和反序列化功能初始化护照? E.g;

module.exports = function(passport){
    //Serialise User
    passport.serializeUser(function(user, done) {
        console.log("Serializing User: " + user.username + "\n" + user + ".");
        done(null, user._id);
    });

    //De-Serialise User
    passport.deserializeUser(function(id, done) {
        User.findById(id, function(err, user) {
            console.log("Deserializing User: " + user.username + "\n" + user);
            done(err, user);
        });
    });

    //Setting up Passport Strategies for Login and SignUp/Registration
    login(passport);
    signup(passport);
}

您还需要在app.js

中指定路线的护照
// Route Files
let index = require('./routes/index')(passport);
let users = require('./routes/users')(passport);
let posts = require('./routes/posts')(passport);

并且在路径文件本身中,您将要将您的路线包裹在护照的模块导出功能中。 E.g;

module.exports = function(passport) {
    //Routes

    return router;
}

然后,您可以通过编写检查用户是否已登录的函数来保护您的路由。

let isAuthenticated = function(req, res, next) {
    if (req.isAuthenticated()) {
        console.log("User " + req.user.username + " authenticated.");
        return next();
    } else {
        res.redirect('/unauthorised');
    }
}

//Protect a route
router.get('/some-route', isAuthenticated, function(req, res) {
    res.render('some-file');
}

查看here有关此问题的教程。