Sending passport-local and express middleware to express router

Viewed 33

I have a simple app.js file with passport authentication, I have a app.get on my app.js that looks something like this

app.get('/test', isAuthenticated, (req, res) => {
    res.json(req.user)
})

When I open this page ('/test'), I get the following data

{
    "email": "jhondoe@example.com",
    "id": "f8dbee1ba8e95ace16656a008c548b91",
    "expiry": "06/10/2022"
}

Now, I'm trying to do the same thing, but in my express router ('/s/main'), this is how I've imported my router

const settings = require('./routes/settings')
app.use("/s", settings) 

Now I want to be able to access my 'req.user' and the isAuthenticated middleware that I declared in app.js

function isAuthenticated(req, res, done) {
    if (req.user) {
        return done();
    }

    return res.send('You need to be authenticated to view this page.');
}

this is my settings.js file from the routes folder

const express = require('express')
const router = new express.Router();

router.get('/main', (req, res) => {
    res.send(req.user)
})

module.exports = router;

Conclusion I want to do the same thing as the '/test' app.js in my '/s/main' in express router Thanks for reading

app.js

const express = require('express');
const app = express();
const session = require('express-session');
const passport = require('passport')
const LocalStrategy = require('passport-local').Strategy;
const fs = require('fs');

const settings = require('./routes/settings')
app.use("/s", settings) // 

app.use(express.urlencoded({ extended: false }))
app.use(session({ secret: 'pswd', resave: false, saveUninitialized: false }))
app.use(passport.initialize());
app.use(passport.session());

passport.use(new LocalStrategy(
    function(email, password, done) {

        console.log(email, password)
        let user = findByEmail(email) // converts email address to user ID
        let uid = user.id;
        console.log(user, uid)
        // compare(id) basically gets the password from the database
        if (user.code != 200) {
            return done(null, false, { message: 'Email not registered.' });
        }

        if (compare(uid) == password) {
            return done(null, user); // login success
        } else {
            return done(null, false, { message: 'Incorrect password.' });
        }
    }
))

passport.serializeUser((user, done) => {
    if (user) {
        return done(null, user.id);
    }

    return done(null, false);
});

passport.deserializeUser((id, done) => {
    let user = findById(id)
    if (user.id == null) {
        return done(null, false)
    }
    return done(null, user)
});

function isAuthenticated(req, res, done) {
    if (req.user) {
        return done();
    }

    return res.send('You need to be authenticated to view this page.');
}

app.get('/test', isAuthenticated, (req, res) => {
    res.json(req.user)
})

app.get('/login', (req, res) => {
    res.send('Login Page')
})

app.post('/login', passport.authenticate('local'), function (req, res) {
    console.log('Valid login')
    res.json(req.user)
})

app.post('/logout', (req, res) => {
    req.logout();
    res.send('Logged out')
})

app.get('/', (req, res) => {
    res.send('Hello World!');
})

function findByEmail(email) {
    let users = JSON.parse(fs.readFileSync('users.json', 'utf8'));
    let index = users.findIndex(user => user.email == email);
    if (index != -1) {
        users[index].code = 200;
        return users[index]
    } else {
        return { code: 404, email: null, id: null, expiry: null }
    }
}

function findById(id) {
    let users = JSON.parse(fs.readFileSync('users.json', 'utf8'));
    let index = users.findIndex(user => user.id == id);
    if (index != -1) {
        return users[index]
    } else {
        return { email: null, id: null, expiry: null }
    }
}

function compare(id) {
    // basisically comparing the user ID's password and the entered password  
    if (id == 'f8dbee1ba8e95ace16656a008c548b91') {
        return 'pswd_admin'
    }
}

app.listen(3000, () => {
    console.log('Server is up on port 3000');
});

module.exports = { isAuthenticated }

settings.js

const express = require('express')
const router = new express.Router();

router.get('/main', (req, res) => {     
    res.json(req.user) 
})

module.exports = router;```
0 Answers
Related