jaredhanson / passport

Simple, unobtrusive authentication for Node.js.
https://www.passportjs.org?utm_source=github&utm_medium=referral&utm_campaign=passport&utm_content=about
MIT License
22.93k stars 1.24k forks source link

req.user = [] #698

Closed GabrielLeonte closed 5 years ago

GabrielLeonte commented 5 years ago

I have this code: `// load all the things we need const passport = require('passport'); const LocalStrategy = require('passport-local').Strategy; const fs = require('fs'); var sqlite3 = require('sqlite3').verbose(); const bcrypt = require('bcrypt-nodejs'); const db = require('./database'); const settings = require('./settings'); var database; database = new sqlite3.Database(settings.dbName);

//Check if database exists or not. If it not exist it will create one.

if (fs.existsSync(settings.dbName)) {} else { db.Init();

}

// expose this function to our app using module.exports module.exports = function (passport) {

// =========================================================================
// passport session setup ==================================================
// =========================================================================
// required for persistent login sessions
// passport needs ability to serialize and unserialize users out of session
passport.serializeUser(function (user, done) {
    done(null, user);
});

// used to deserialize the user
passport.deserializeUser(function (id, done) {
    database.all("SELECT * FROM users WHERE id = ? ", [id], function (err, rows) {
        done(err, rows);
    });
});

// =========================================================================
// LOCAL SIGNUP ============================================================
// =========================================================================
// we are using named strategies since we have one for login and one for signup
// by default, if there was no name, it would just be called 'local'

passport.use(
    'local-signup',
    new LocalStrategy({
            // by default, local strategy uses username and password, we will override with email
            usernameField: 'username',
            passwordField: 'password',
            passReqToCallback: true // allows us to pass back the entire request to the callback
        },
        function (req, username, password, done) {
            function getRandomInt(max) {
                return Math.floor(Math.random() * Math.floor(max));
            }
            // find a user whose email is the same as the forms email
            // we are checking to see if the user trying to login already exists
            database.all("SELECT * FROM users WHERE username = ?", [username], function (err, rows) {
                if (err)
                    return done(err);
                if (rows.length) {
                    return done(null, false, console.log("User exists"));
                } else {
                    // if there is no user with that username
                    // create the user
                    var newUserMysql = {
                        username: username,
                        email: req.body.email,
                        id: Math.floor(new Date() / 1000) + getRandomInt(Math.floor(new Date() / 1000)),
                        password: bcrypt.hashSync(password, null, null) // use the generateHash function in our user model
                    };

                    var insertQuery = "INSERT INTO users (id, username, email, password ) values (?,?,?,?)";
                    database.all(insertQuery, [newUserMysql.id, newUserMysql.username, newUserMysql.email, newUserMysql.password], function (err, rowsf) {
                        return done(null, newUserMysql);
                    });
                }
            });
        })
);

// =========================================================================
// LOCAL LOGIN =============================================================
// =========================================================================
// we are using named strategies since we have one for login and one for signup
// by default, if there was no name, it would just be called 'local'

passport.use(
    'local-login',
    new LocalStrategy({
            // by default, local strategy uses username and password, we will override with email
            usernameField: 'username',
            passwordField: 'password',
            passReqToCallback: true // allows us to pass back the entire request to the callback
        },
        function (req, username, password, done) { // callback with email and password from our form
            database.all("SELECT * FROM users WHERE username = ?", [username], function (err, rows) {
                if (err)
                    return done(err);
                if (!rows.length) {
                    return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash
                }

                // if the user is found but the password is wrong
                if (!bcrypt.compareSync(password, rows[0].password))
                    return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata

                // all is well, return successful user
                return done(null, rows[0]);
            });
        })
);

};`

When i log in and try to get req.user.username or id i get in console.log that [] Some help please?

GabrielLeonte commented 5 years ago

app.post('/login', passport.authenticate('local-login', { successRedirect: '/dashboard', // redirect to the secure profile section failureRedirect: '/login' // redirect back to the signup page if there is an error }), function (req, res) { console.log("hello"); if (req.body.remember) { req.session.cookie.maxAge = 1000 60 3; } else { req.session.cookie.expires = false; } res.redirect('/'); }); app.get('/dashboard', isLoggedIn, async function (req, res) {

    // render the page and pass in any flash data if it exists
    res.render('dashboard', {
        user: req.user
    });
})

And this is from routes

GabrielLeonte commented 5 years ago

Solved. passport.serializeUser(function (user, done) { done(null, user.id); });