const LocalStrategy = require('passport-local').Strategy;
const User = require('../app/models/user');
const randomPass = require('randomstring');
module.exports = function(passport) {
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
passport.use('local-signup', new LocalStrategy({
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true
},
function(req, email, password, done) {
User.findOne({ 'local.email' : email.toLowerCase() }, function(err, user) {
if (err)
return done(err);
if (user) {
return done(null, false, req.flash('signupMessage', 'Адрес электронной почты уже занят'));
} else {
var newUser = new User();
newUser.local.email = email.toLowerCase();
newUser.local.password = newUser.generateHash(password);
newUser.save(function(err) {
if (err)
throw err;
return done(null, newUser);
});
}
});
}));
var newUser = new User();
newUser.local.email = email.toLowerCase();
password = randomPass.generate(7);
newUser.local.password = newUser.generateHash(password);
const { Router } = require('express')
const router = Router()
const Users = require('../models/Users')
const bcrypt = require('bcryptjs')
const fileUpload = require('../middleware/fileUpload.js')
router.get('/signin', (req, res, next) => {
res.render('user/signin', {
title: 'User sign in'
})
})
router.get('/signout', (req, res) => {
req.session.destroy(() => {
res.redirect('/user/signin')
})
})
router.post('/signin', async (req, res) => {
try {
const { nickname, password } = req.body
const candidateUser = await Users.findOne({ nickname })
if (candidateUser) {
const areSame = await bcrypt.compare(password, candidateUser.password) //true || false
if (areSame) {
req.session.userAuth = true
req.session.users = candidateUser
res.redirect('/users')
} else {
res.redirect('/user/signin')
}
} else {
res.redirect('/user/signin')
}
} catch (error) {
console.log(error);
}
});
router.get('/signup', (req, res) => {
res.render('user/signup', {
title: 'User sign up'
})
})
router.post('/signup', async (req, res) => {
const { nickname, name, password } = req.body
const userHasPassword = await bcrypt.hash(password, 10)
const users = new Users({
nickname,
name,
password: userHasPassword,
})
await users.save()
res.redirect('/user/signin')
})
module.exports = router