Passport.ls/Mysql – get authenticated/current user data

I’m building a chat app. When users send messages, I want their responses to output username, date, comments.

For now I’m just testing that I can output the selected data from my database.

I’m using Passport js to authenticate users. I’m able to output selected data of users from the database manually, but that’s not what I want, I want to output data of the logged in/authenticated user only.

Index.js

    sqlDatabase.query('SELECT users.username, comments.comments, comments.date FROM users, comments WHERE users.id=comments.id',      function(error, results, fields) {         if (error) throw error;          results.forEach((id) => {             console.log(id.username, id.date, id.comments) 

The above outputs selected data of all users instead of CURRENT/LOGGED IN user

Output:Kaunda 2020-07-08 Hello friend. It’s good to see you!

Output NowayOut 2020-07-09 this is my time

As you can also see, I have two tables in my db. I pull username from one table, and date and comments from the other table

I’ve been told to try using session_id to do what I want. I don’t know. Here’s my code for log in.

router.post("/login",    passport.authenticate('local', {        successRedirect: '/',        failureRedirect: '/login',        // failureFlash: true,     })); passport.use(new LocalStrategy({        usernameField: 'email',        passwordField: 'password',        passReqToCallback: true,    },    function(req, email, password, done) {        console.log(email, password, done);        const sqlDatabase = require('../db.js');          sqlDatabase.query('SELECT * FROM users WHERE email = ?', [email], (err, results, fields, res) => {            if (err)                return done(err);            console.log(err, fields, results);                if (results.length === 0) {                done(null, false, { message: 'Check email and password again.' });            } else {                 const hash = results[0].                password.toString();                 const user_id = results[0].id;                  bcrypt.compare(password, hash, function(err, response) {                    console.log('User id is:' + user_id);                    if (response === true) {                        return done(null, 'User id is:' + user_id);                    } else {                        console.log(user_id);                        console.log(err);                        return done(null, false, { message: 'This is a test notification.' });                     }                })            }         })     }));  passport.serializeUser(function(user_id, done) {    console.log(user_id);    done(null, user_id);    console.log(done);  }); passport.deserializeUser(function(user_id, done) {    done(null, user_id);    console.log(done);  });```   Yeah, so I've been battling with this. I want to output data of ONLY the authenticated user. Excuse all the console.log() stuff  Thanks in advance.   
Add Comment
1 Answer(s)

To restrict only users who are logged in to use your chat you can use a middleware to check if user is authenticated if not it will be redirected you can simply put it in a different file and export it and then add it to any route you want to restrict access.

module.exports={     checkuserauth:(req,res,next)=>{         if(req.isAuthenticated()){         res.set('Cache-Control', 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0')              return next()         }      req.flash("error_msg","Please login to see this content")       res.redirect('/login')         },     forwardAuthenticated: function(req, res, next) {     if (!req.isAuthenticated()) {       return next();     }     res.redirect('/');         }     } 

now in your route you can add the middleware like this

router.get("/",checkuserauth,(req,res){ //your code here }) 

To output data of the logged in/authenticated users only you can use the fact that passport serializes users into the session, it attaches the user Id to the request and you can use that to know about users that are logged In and make a request to the database req.user_id. an alternative approach is to add a boolean variable isauthenticated in your database to every user and whenever a user is successfully authenticated you simply set it to true, this will allow you to filter only authenticated users

Answered on July 16, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.