Search code examples
javascriptnode.jsexpressmongoosebody-parser

Error: Authentication code missing (Mongoose-encryption)


im getting this error while login a registred user ofcourse i got this error after using dotenv package to secure my database encryption key

but proccess.env.SECRET is working currectly

i guess my problem is here :

userSchema.plugin(encrypt, {           
    secret: process.env.SECRET,         
    encryptedFields: ["password"],     
});

app.js :

require("dotenv").config();

const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require("mongoose");
const encrypt = require("mongoose-encryption");

const app = express();

app.use(express.static("public"));
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({ extended: true }));

mongoose.connect("mongodb://localhost:27017/userDB", {
    useUnifiedTopology: true,
    useNewUrlParser: true,
});

const userSchema = new mongoose.Schema({
    email: String,
    password: String,
});

                                         //_
//     encrypting password field         // | 
userSchema.plugin(encrypt, {             // | i guess problem is here
    secret: process.env.SECRET,          // |
    encryptedFields: ["password"],       //_|
});

const User = mongoose.model("User", userSchema);

error :

Error: Authentication code missing
    at Object.schema.methods.authenticateSync (C:\Users\Amir\Desktop\security\node_modules\mongoose-encryption\lib\plugins\mongoose-encryption.js:419:23)
    at model.<anonymous> (C:\Users\Amir\Desktop\security\node_modules\mongoose-encryption\lib\plugins\mongoose-encryption.js:239:47)
    at Kareem.execPreSync (C:\Users\Amir\Desktop\security\node_modules\kareem\index.js:115:16)
    at model.syncWrapper [as $__init] (C:\Users\Amir\Desktop\security\node_modules\kareem\index.js:232:12)
    at model.Document.init (C:\Users\Amir\Desktop\security\node_modules\mongoose\lib\document.js:513:8)
    at completeOne (C:\Users\Amir\Desktop\security\node_modules\mongoose\lib\query.js:2853:12)
    at model.Query.Query._completeOne (C:\Users\Amir\Desktop\security\node_modules\mongoose\lib\query.js:2094:7)
    at Immediate.<anonymous> (C:\Users\Amir\Desktop\security\node_modules\mongoose\lib\query.js:2138:10)
    at Immediate.<anonymous> (C:\Users\Amir\Desktop\security\node_modules\mquery\lib\utils.js:116:16)
    at processImmediate (internal/timers.js:456:21)

Solution

  • I had the same problem and this worked for me:

    1. Navigate to your database using your terminal using (as much I can see you use mongo) ex: show dbs, use databaseName, show collections, db.databaseName.find() and then

    2. Empty your database db.databaseName.drop() (If it is important stuff, then keep it somewhere safe so you can reuse it again, should be easy if you use Postman)

    3. And recreate your database