U
U
unituser2020-07-04 21:41:22
Express.js
unituser, 2020-07-04 21:41:22

How can I implement checking if the user is logged in Express.js?

Good afternoon, I got such a check, but I don’t like it at all, because this check must be specified in each route. Is there any way to take this out to another file and correct it. I do everything through the passport module. Maybe you can somehow display this in passport serialize?

router.get('/', async(req, res) => {
    if (req.user !== undefined) {
        authenticate = true
    } else {
        authenticate = false
    }
    res.render('index', {
        titlePage: 'Asd',
        auth: authenticate,
        user: req.user
    })
})


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

passport.deserializeUser(function(obj, done) {
    done(null, obj);
});


function ensureAuthenticated(req, res, next) {
    if (req.isAuthenticated()) { return next() }
    res.redirect('/')
    console.log('Для того, чтобы зайти в профиль авторизируйтесь')
}


You can not offer this, as I understand it, the function checks whether the user is logged in, but it is intended to enter the page, and I need to display the elements on the site. Or am I just misunderstanding and this function can be used as a login check?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question