Когда я подписываю новое письмо, оно перенаправляется на страницу входа в систему, в router.post('/login')
я добавил successRedirect: '/' and
failureRedirect: '/test'
, но в любом случае оно перенаправляет на / test , даже если оно успешно!
index. js
var express = require('express');
var router = express.Router();
const users = require('../model/db');
const { check, validationResult } = require('express-validator');
const passport = require('passport');
//GET login
router.get('/login', (req, res, next)=>{res.render('login')});
router.post('/login', passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/test',
failureFlash: true,
}));
router.get('/signup', function (req, res, next){
const msg = req.flash('error')
res.render('signup');
});
router.post('/signup', [
check('password').isLength({ min: 5 }).withMessage('Please enter Password with more than 5 letters!'),
check('password').not().isEmpty().withMessage('Please fill password fie'),
check('repassword').custom((val, {req})=>{
if(val !== req.body.password){
throw new Error('Password is not equal to confirm password');
}
return true;
})
],
function (req, res, next){
const newUser = new users({
email : req.body.email,
password : new users().hashPassword(req.body.password)
});
users.findOne({email : req.body.email}, (err, doc)=>{
if(err){
console.log('ERR while getting username =>' + err);
return ;
}
if(doc){
res.send('this email is already registered before!');
return ;
}
newUser.save((err, doc)=>{
if(err){
console.log('err' + err)
}else{
res.redirect('/login')
}
});
});
// Finds the validation errors in this request and wraps them in an object with handy functions
const errors = validationResult(req);
if (!errors.isEmpty()) {
var validationMessage = [];
for(var i = 0; i<errors.errors.length; i++){
validationMessage.push(errors.errors[i].msg);
}
req.flash('error', validationMessage)
res.redirect('signup')
}
});
module.exports = router;
Согласно этим двум строкам кода,
router.post('/login', passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/test',
failureFlash: true,
}));
Это должно Перенаправить меня на / test , если произошел сбой, и На / , если ему удалось
войти .hbs
<div class="container">
<div class="s-f">
<div class="card">
<div class="card-body">
<div>
<h6>Log in | <a href='/' target="_blank">Coursatak</a></h6>
</div>
<form action="/login" method="post">
<div class="form-group">
<label for="email">Email</label>
<input type="text" name="email" id="email" class="form-control">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" name="password" id="password" class="form-control">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary"> Sign Up</button>
</div>
<div>
<p class='if'></span><a href="/signup">Sign Up</a>, <span>If you already registered before.</p>
</div>
</form>
</div>
</div>
</div>
</div>
config / conficuration. js
const LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcryptjs');
const User = require('../model/students');
module.exports = function(passport) {
passport.use(
new LocalStrategy('local', { usernameField: 'email' }, (email, password, done) => {
// Match user
User.findOne({email: email}).then(user => {
if (!user) {
return done(null, false, { message: 'That email is not registered' });
}
bcrypt.compare(password, student.password, (err, isMatch) => {
if (err) throw err;
if (isMatch) {
return done(null, user);
} else {
return done(null, false, { message: 'Password incorrect' });
}
});
});
})
);
};
Схема
const mongoose = require('mongoose');
const bcrypt = require('bcrypt-nodejs');
const stDB = mongoose.Schema({
email : {
type: String,
required: true
},
password : {
type: String,
required: true
}
});
stDB.methods.hashPassword = function(password){
return bcrypt.hashSync(password, bcrypt.genSaltSync(10));
}
stDB.methods.comparePasswords = (password, hash) => {
return bcrypt.compareSync(password,hash)
}
module.exports = mongoose.model('db', stDB);
Версия узла: 10.16.1
Express Версия: 4.16.1