Sarulatha A
Sarulatha A

Reputation: 48

TypeError: Cannot read property 'authenticate' of null

I am working in user signin authentication in backend. Whenever I hit send request from postman it shows error as TypeError: Cannot read property 'authenticate' of null at /home/saru/mernbootcamp/projbackend/controllers/auth.js I had check this error in stackoverflow but the solution doesn't match my case

controllers/auth.js

`const User = require("../models/user");
//express-validator
const { check, validationResult } = require('express-validator');
var jwt = require('jsonwebtoken');
var expressJwt = require('express-jwt');

const dotenv = require("dotenv")
const config = dotenv.config({ path: './routes/.env' });

    //user object creation for class/model User
    const user = new User(req.body);

exports.signin = (req, res) => {
    const errors = validationResult(req);
    const { email, password } = req.body;

    if (!errors.isEmpty()) {
        return res.status(422).json({
            error: errors.array()[0].msg
        });
    }

    User.findOne({ email }, (err, user) => {
        if (err) {
            return res.status(400).json({
                error: "USER email does not exists"
            });
        }
        console.log(password);
        if (!user.authenticate(password)) {
            return res.status(401).json({
                error: "Email and password do not match"
            });
        }

        //create token
        const token = jwt.sign({ _id: user._id }, process.env.SECRET);
        //put token in cookie
        res.cookie("token", token, { expire: new Date() + 9999 });

        //send response to front end
        const { _id, name, email, role } = user;
        return res.json({ token, user: { _id, name, email, role } });
    });
};
`

models/user.js

`var mongoose = require("mongoose");
const crypto = require("crypto");
const uuidv1 = require("uuid/v1");

var userSchema = new mongoose.Schema(
    {
         email: {
            type: String,
            trim: true,
            required: true,
            unique: true
        },
      encry_password: {
            type: String,
            required: true
        },
        salt: String,
    },
    { timestamps: true }
);

userSchema
    .virtual("password")
    .set(function (password) {
        this._password = password;
        this.salt = uuidv1();
        this.encry_password = this.securePassword(password);
    })
    .get(function () {
        return this._password;
    });

userSchema.method = {
    authenticate: function (plainpassword) {
        return this.securePassword(plainpassword) === this.encry_password;
    },

    securePassword: function (plainpassword) {
        if (!password) return "";
        try {
            return crypto
                .createHmac("sha256", this.salt)
                .update(plainpassword)
                .digest("hex");
        } catch (err) {
            return "";
        }
    }
};

module.exports = mongoose.model("User", userSchema);
`

Upvotes: 2

Views: 1665

Answers (2)

Patel Aryant
Patel Aryant

Reputation: 1

You can use this code:

User.findOne({email}, (err, user) => {
  if (err || !user) {
    return res.status(400).json({
      error: "USER email does not exists"
    })
  }
});

Replace if (err) with if (err || !user) and use return before res.status

Upvotes: 0

Aditya Kulkarni
Aditya Kulkarni

Reputation: 94

In controllers/auth.js

Replace the if(err) with if(err || !user) in the findOne() method

Upvotes: 2

Related Questions