Passport isAuthenticated() always returns false?

Ize_Cubz

So I am having a problem with Passport I've been trying to move from my original method of authentication because Passport supports other types like Google and GitHub. I'm trying to implement the local authentication and it doesn't seem to be working, even after looking up many articles and they all don't work.

This is at the top of the code:

const cookieExpirationDate = new Date();
cookieExpirationDate.setDate(cookieExpirationDate.getDate() + 7);

app.use(session({
    secret: secret_key,
    store: sessionStore,
    resave: true,
    saveUninitialized: true,
    cookie: {
        httpOnly: true,
        sameSite: 'strict',
        expires: cookieExpirationDate
    }
}));

// PASSPORT //
app.use(passport.initialize());
app.use(passport.session());

passport.use('local', new LocalStrategy({

        usernameField: 'username',

        passwordField: 'password',

        passReqToCallback: true //passback entire req to call back
    }, async function (req, username, password, done) {


        if (!username || !password) {
            return done(null, false, {message: 'Please complete the form!'})
        }
        const reqBody = {
            response: req.body['h-captcha-response'],
            secret: captcha_key
        }
        let axiosResult = await axios.post('https://hcaptcha.com/siteverify', qs.stringify(reqBody), {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        })
        if (axiosResult.data.success === true) {
            let results = await runQuery('SELECT * FROM accounts WHERE (username = ? OR email = ?)', [username, username])
            const forwarded = req.headers['x-forwarded-for']
            const ip = forwarded ? forwarded.split(/, /)[0] : req.connection.remoteAddress

            if (!results.length) {
                let amtLeft = await loginAttempts(ip);
                if (amtLeft > 1) {
                    return done(null, false, {message: `Incorrect Username and/or Password! (${amtLeft} attempt(s) left)`});
                } else {
                    return done(null, false, {message: `You must wait 15 minutes before trying again!`});
                }
            }
            let user = results[0]
            let isMatch = await bcrypt.compareSync(password, user.password)
            if (!isMatch) {
                let amtLeft = await loginAttempts(ip);
                if (amtLeft > 1) {
                    return done(null, false, {message: `Incorrect Username and/or Password! (${amtLeft} attempt(s) left)`});
                } else {
                    return done(null, false, {message: `You must wait 15 minutes before trying again!`});
                }
            } else {
                if (user.activation_code === "activated") {
                    return done(null, user)
                } else {
                    return done(null, false, {message: 'Check your email for an activation email!'})
                }
            }
        } else {
            return done(null, false, {message: `You must complete the captcha!`});
        }
    }
));

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

passport.deserializeUser(async function (usrid, done) {
    let results = await runQuery('SELECT * FROM accounts WHERE id = ?', usrid)
    done(results[0]);
});

Login API part:

app.post('/login_sys', regularFunctions, function (req, res, next) {
    passport.authenticate('local', {failWithError: true}, function (error, user, info) {
        if (error) {
            return res.status(500).json(error);
        }
        if (!user) {
            return res.status(401).json(info);
        }
        return res.status(200).send('Success')
    })(req, res, next);
})

regularFunctions:

let regularFunctions = [
    bodyParser.urlencoded({extended: true}),
    bodyParser.json(),
    function (req, res, next) {
        console.log('Authenticated: ' + req.isAuthenticated())
        if (req.isAuthenticated()) {
            req.session.loggedin = true;
            return next();
        } else {
            req.session.loggedin = false;
            return next();
        }
    }
]

I need it to return some sort of notification to the client if it fails or succeeds because I have a little pop up that lets them know they are getting redirected if it works and to notify them of their attempts left. The problem is it works and says that it logged in but when I refresh the page it never did.

Ize_Cubz

Ok just found out the answer after searching for a while, I had to use req.login inside the login_sys route.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Node js passport's req.isAuthenticated returns always false

Passport isAuthenticated() always returns TRUE

Ionic + Passport isAuthenticated() returns false

passport req.isAuthenticated() always returns fasle

isAuthenticated always false using Javascript express and passport

Node.js, Vue.js and Passport.js. .isAuthenticated() always returns false? Axios headers possibly?

Setting up passport for the first time. isAuthenticated() always returning false

koa-passport w/ passport-steam: ctx.isAuthenticated() always false

passport's req.isAuthenticated always returning false, even when I hardcode done(null, true)

Express-session + Passport + MongoDB - req.isAuthenticated() always return false after login

Azure AD API returns System.Security.Principal.GenericIdentity.IsAuthenticated as false always

Request.IsAuthenticated always returning false on Login

Passportjs req.isAuthenticated always shows false

req.session.passport and req.user blank , and req.isAuthenticated returns false after initial successful login using passport-facebook

Contains always returns false

isEqualToString always returns False

hasNextLine() always returns false

isHardwareAccelerated() always returns false

Always returns false

StrPos always returns False?

Passport.js `isAuthenticated()` inconsistent behavior; false when it should be true

Laravel 5.4 passport axios always returns Unauthenticated

Regex matches always returns false

RegEx matcher always returns false

python if statement always returns False

Testing a path always returns False

DOMDocument loadHTMLFile always returns false

Hash::check() always returns false

Somewhy the program always returns 'false'?