PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, September 2, 2022

[FIXED] How to make a specific user log out? NodeJS-Express-MongoDB

 September 02, 2022     authentication, express, mongodb, node.js     No comments   

Issue

I have admin role and when I block some user, I want to log the user out immediately. req.session.destroy() is not the case as it log out me. Thanks in advance.

app.js

mongoose.connect('mongodb://127.0.0.1/nodeblog_db', {
    useNewUrlParser: true,
    useUnifiedTopology: true,
});

app.use(expressSession({
    secret: 'testotesto',
    resave: false,
    saveUninitialized: true,
    store: connectMongo.create({mongoUrl : 'mongodb://127.0.0.1/nodeblog_db'})
}))

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

login route

router.get('/login', (req, res) => {
    res.render('site/login');
});

router.post('/login', (req, res) => {
    const { email, password } = req.body;

    User.findOne({ email }, (error, user) => {
        if (user) {
            user.comparePassword(password, (matchError, isMatch) => {
                if (matchError) {
                    throw matchError;
                }
                else if (isMatch) {
                    req.session.userId = user._id; //**************
                    res.redirect('/');
                }
                else if (!isMatch) {
                    res.redirect('/users/login');
                }
            })
        }
        else {
            res.redirect('/users/register');
        }
    });
});

My User Model I have a banned field in my database. When I want to block a user, I set that field as true.

const mongoose = require('mongoose');
const bcrypt = require("bcryptjs");

const UserSchema = new mongoose.Schema({
    username: { type: String, required: true, unique: true },
    email: { type: String, required: true, unique: true },
    password: { type: String, required: true },
    verified: { type: Boolean, default: false },
    auth: { type: String, default: false },
    banned: { type: Boolean, default: false }
});


UserSchema.pre("save", function (next) {
    const user = this

    if (this.isModified("password") || this.isNew) {
        bcrypt.genSalt(10, function (saltError, salt) {
            if (saltError) {
                return next(saltError)
            } else {
                bcrypt.hash(user.password, salt, function (hashError, hash) {
                    if (hashError) {
                        return next(hashError)
                    }

                    user.password = hash
                    next()
                })
            }
        })
    } else {
        return next()
    }
})

UserSchema.methods.comparePassword = function (password, callback) {
    bcrypt.compare(password, this.password, function (error, isMatch) {
        if (error) {
            return callback(error)
        } else {
            callback(null, isMatch)
        }
    })
}



module.exports = mongoose.model('User', UserSchema); 

I use this code to check if user is logged in:

if(req.session.userId){
//the user is logged in
}

Solution

So The Default way I would try solving this is to add a middleware after the auth check

This is because am sure its gonna contain req.session.userId = user._id;

// Import Your Db Model

const checkBan = (req,res,next)=>{
    // If you don't pass your user state into req.user
    User.findOne({ _id:req.session.userId }, (error, user) => {
        if(error){
            next(err)
        }else{
            // The User Would have been authenticated 
            // Therefore User exist 
            
            if(user.banned){
                // User Is Banned so handle it as you like 
                res.send("Your Account is banned - other messages")
            }else{
                // Users Aren't Banned so continue  
                next()
            }
        }
    })
}

module.exports = checkBan;

You Can Now Import this After your Authentication checker middleware on routes you want the banned user to be unable to access

Now when you change the state to ban its renders this message and hinders any further interaction with your system from the user



Answered By - Ogoh.cyril
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing