Hi everyoneI have an API and I have made a function to check if a user is authenticated, if he is then the API redirects him to the home page else to the /login page ,
Authenticate function:
function checkAuthenticated(req, res, next) { if (req.isAuthenticated()) { return next() } res.redirect('/login')}
Homepage route :
app.get('/', checkAuthenticated, (req, res) => { res.render('index.ejs', { name: req.user.name }) })
But now I want to add this functionality to other routes like the import routes I have made, For that i copied the function in the route endpoint like this:
router.get('/',function (req, res) { if (req.isAuthenticated()) { //Display the articles console.log('request: GET /newspapers') res.status(200).json(jornales) console.log('auth') } res.redirect('/login')}
Problem: Now the function redirects the user to /login if he's logged in,BUT it doesn't show the JSON result if he is logged in instead it redirects him to the homepage.
Server.js
app.use('/api/v3/newspapers', v3newspapersRoute);//v3newspapersRoute// calling the validation function that takes user.email & user.idconst initializePassport = require('./passport-config')initializePassport( passport, email => users.find(user => user.email === email), id => users.find(user => user.id === id))// adding ejs so the system can acces the data enterd in the ejs forms to redapp.set('view-engine', 'ejs')app.use(express.urlencoded({ extended: false }))app.use(flash())app.use(session({// PROBLEM secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: false}))app.use(passport.initialize())app.use(passport.session())app.use(methodOverride('_method'))//--- ROUTES // HOME , first check if he's authenticated, if yes redricet to index.ejs else go to loginapp.get('/', checkAuthenticated, (req, res) => { res.render('index.ejs', { name: req.user.name })})function checkAuthenticated(req, res, next) { if (req.isAuthenticated()) { return next() } res.redirect('/login')}function checkNotAuthenticated(req, res, next) { if (req.isAuthenticated()) { return res.redirect('/') } next()}app.listen(3000)
Newspapers.js
const passport = require('passport')const flash = require('express-flash')const session = require('express-session')const methodOverride = require('method-override')const express = require('express')const initializePassport = require('../../../passport-config')initializePassport( passport, email => users.find(user => user.email === email), id => users.find(user => user.id === id))//router.set('view-engine', 'ejs')router.use(express.urlencoded({ extended: false }))router.use(flash())router.use(session({// PROBLEM secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: false}))router.use(passport.initialize())router.use(passport.session())router.use(methodOverride('_method'))//Get all newspapers (id,website,source) ---- DONErouter.get('/',function (req, res) { if (req.isAuthenticated()) { //Display the articles console.log('request: GET /newspapers') res.status(200).json(jornales) console.log('auth') } res.redirect('/login')});function checkAuthenticated(req, res, next) { if (req.isAuthenticated()) { return next() } res.redirect('/login')}function checkNotAuthenticated(req, res, next) { if (req.isAuthenticated()) { return res.redirect('/') } next()}///module.exports = router;
passport-config
const LocalStrategy = require('passport-local').Strategyconst bcrypt = require('bcrypt')function initialize(passport, getUserByEmail, getUserById) { const authenticateUser = async (email, password, done) => { const user = getUserByEmail(email) if (user == null) { return done(null, false, { message: 'No user with that email' }) } try { if (await bcrypt.compare(password, user.password)) { return done(null, user) } else { return done(null, false, { message: 'Password incorrect' }) } } catch (e) { return done(e) } } passport.use(new LocalStrategy({ usernameField: 'email' }, authenticateUser)) passport.serializeUser((user, done) => done(null, user.id)) passport.deserializeUser((id, done) => { return done(null, getUserById(id)) })}module.exports = initialize
PS: I'm noob & I'm using ejs for the home/login/register pages and not for the other routes
Youtube video i followed: https://www.youtube.com/watch?v=-RCnNyD0L-s&t=135s