
const passport = require('passport');
const mongoose = require('mongoose'),
User = mongoose.model('User');

exports.sign_in = (req, res)=>{
    User.findOne({username: req.body.username}, function(err, founduser){
        console.log(req.body)
        if(founduser){
            const user = new User({
                username: req.body.username,
                password: req.body.password
            });
            
            passport.authenticate('local', (err, user) => {
                    if (err) {
                        console.log(err);
                    } else {
                        if (user) {
                            req.login(user, function (err) {
                               
                                res.redirect('/');
                            });
                        } else {
                           
                            req.flash('notify', 'Email Or Password Incorrect')
                            res.render('owners/signin'
                            );
                        }
                    }
                })(req,res);
        }else{
            console.log('im here 2')
            req.flash('notify', 'User doesnt exist')
            res.render('owners/signin'
            );
        }
    });
}

// log user out


exports.logout = function(req, res){
    if(req.isAuthenticated()){
        req.logout();
        res.render('owners/signin'
            );
    }else{
        res.render('owners/signin'
            );
    }
}