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;
Wow thatsたくさんのコードを読むことができます...あなたのdbsは正しく更新されますか? – deeveeABC