0
可以請任何人告訴我我的代碼中出了什麼問題?當我嘗試登錄時,它總是說無效的密碼,但似乎用戶名正確。我只是不知道爲什麼我無法登錄到應用程序。這是我的users.js類。謝謝節點js + sqlite3身份驗證
var express = require('express');
var router = express.Router();
var passport = require('passport')
var LocalStrategy = require('passport-local').Strategy;
var crypto = require('crypto');
var User = require('../models/user');
var sqlite3 = require('sqlite3');
var db = new sqlite3.Database('./database.sqlite3');
//Register
router.get('/register', function(req,res) {
res.render('register');
});
//Login
router.get('/login', function(req,res) {
res.render('login');
});
//Register User
router.post('/register', function(req,res) {
var email = req.body.email;
var username = req.body.username;
var password = req.body.password;
var password2 = req.body.password2;
//Validation
req.checkBody('username', 'Username is required').notEmpty();
req.checkBody('email', 'Email is required').notEmpty();
req.checkBody('email', 'Email is not valid').isEmail();
req.checkBody('password', 'Password is required').notEmpty();
req.checkBody('password2', 'Passwords do not match').equals(req.body.password);
var errors = req.validationErrors();
if (errors){
res.render('register', {
errors:errors
});
} else {
var stmt = db.prepare("INSERT INTO users (id, username, email, password, salt) VALUES (NULL, ?, ?, ?, ?)");
stmt.run([ username, email, password[0], 'string' ]).finalize();
// GIVE ME A FLASH MESSAGE AND REDIRECT TO LOGIN
req.flash('success_msg','You are registered and can now login');
res.redirect('/users/login');
}
});
// LOGIN
function hashPassword(password, salt) {
var hash = crypto.createHash('sha256');
hash.update(password);
hash.update(salt);
return hash.digest('hex');
}
passport.use(new LocalStrategy(function(username, password, done) {
db.get('SELECT * FROM users WHERE username = ?', username, function(err, row) {
if (!row) return done(null, false,{message: 'Unknown User'});
var hash = hashPassword(password, row.salt);
db.get('SELECT * FROM users WHERE username = ? AND password = ?', username, hash, function(err, row) {
if (!row) return done(null, false,{message: 'Invalid password'});
return done(null, row);
});
});
}));
// SERIALIZE AND DESERIALIZE USER
passport.serializeUser(function(user, done) {
return done(null, user.id);
});
passport.deserializeUser(function(id, done) {
db.get('SELECT id, username FROM users WHERE id = ?', id, function(err, row) {
if (!row) return done(null, false);
return done(null, row);
});
});
router.post('/login', passport.authenticate('local', { successRedirect: '/',
failureRedirect: '/users/login',failureFlash:true }),
function(req,res) {
res.redirect('/');
});
router.get('/logout',function(req,res){
req.logout();
req.flash('success_msg','You are logged out');
res.redirect('/users/login');
})
module.exports = router;
哇,這是很多代碼來通讀...你的dbs得到正確更新? – deeveeABC