Error TypeError: Cannot read properties of undefined (reading 'funcao')

Viewed 1769

Hi everyone i'm creating a site whit javascript and i need authentication to check if is an admin or a customer to redirect him for different ways , but i have a problem , when i try to check the Cannot read properties of undefined.

My AuthorizatioCheck

module.exports =  async function(req, res, next){
if(req.isAuthenticated()){
     const utilizador = req.Utilizador;
     if(utilizador.funcao==='admin'){
         next();
     }else{
          res.redirect('back');
     }
}else{
    res.redirect('/utilizadores/login');
}

};

The model

    const mongoose = require('mongoose');

const utilizadorSchema = mongoose.Schema({

    nome:{
        type: String,
        required: true
    },
    email:{
        type: String,
        required: true
    },
    password:{
        type: String,
        required: true
    },
    funcao:{
        type: String,
        required: true,
        default: 'customer'
    },

    fidelizacao:{
        type:Number,
        default:0
        

    },
    carrinho:[{
        livro:{
            type: mongoose.Schema.Types.ObjectId,
            ref: "Livro",
        },
        quantidade:{
            type: Number,
            required: true,
            default: 1
        }
    }]
});

module.exports = mongoose.model("Utilizador", utilizadorSchema);

The error

TypeError: Cannot read properties of undefined (reading 'funcao')

at module.exports (C:\Users\cardo\Desktop\book--store--nodejs-master\middleware\checkAuthorization.js:4:24)

Can someone fix me ? i'm watching the code for hours and can't figure out...

1 Answers

The error means that utilizador (=> req.Utilizador) is undefined and therefore funcao is not a valid property of it.

To fix this specific error I suggest using optional chaining;

if (utilizador?.funcao === 'admin') {
    next();
} else {
    res.redirect('back');
}

Next you should probably check why req.Utilizador is not being defined, assuming it should be in your application logic.

Related