Handlebars: Access has been denied to resolve the property “from” because it is not an “own property” of its parent

后端 未结 11 1829
我在风中等你
我在风中等你 2020-12-05 13:27

I am using a Nodejs backend with server-side rendering using handlebars. After reading a doc array of objects from handlebars, which contains key \"content\" an

11条回答
  •  萌比男神i
    2020-12-05 13:49

    "Wow this worked, Why is this happening though? I am currently using express-handlebars (3.1.0) which I set as a render engine in my express app." – Lee Boon Kong Jan 12 at 14:13

    "In the past, Handlebars would allow you to access prototype methods and properties of the input object from the template... Multiple security issues have come from this behaviour... In handlebars@^4.6.0. access to the object prototype has been disabled completely. Now, if you use custom classes as input to Handlebars, your code won't work anymore... This package automatically adds runtime options to each template-calls, disabling the security restrictions... If your users are writing templates and you execute them on your server you should NOT use this package, but rather find other ways to solve the problem... I suggest you convert your class-instances to plain JavaScript objects before passing them to the template function. Every property or function you access, must be an "own property" of its parent." – README

    More details here: https://www.npmjs.com/package/@handlebars/allow-prototype-access

    QUICK AND DIRTY INSECURE METHOD

    Usage (express-handlebars and mongoose):

    express-handlebars does not allow you to specify runtime-options to pass to the template function. This package can help you disable prototype checks for your models.

    "Only do this, if you have full control over the templates that are executed in the server."

    Steps:

    1 - Install dependency

    npm i @handlebars/allow-prototype-access

    2 - Use this snippet as an example to rewrite your express server

    const express = require('express');
    const mongoose = require('mongoose');
    const Handlebars = require('handlebars');
    const exphbs = require('express-handlebars');
    
    // Import function exported by newly installed node modules.
    const { allowInsecurePrototypeAccess } = require('@handlebars/allow-prototype-access');
    
    const PORT = process.env.PORT || 3000;
    
    const app = express();
    
    const routes = require('./routes');
    
    app.use(express.urlencoded({ extended: true }));
    app.use(express.json());
    app.use(express.static('public'));
    
    // When connecting Handlebars to the Express app...
    app.engine('handlebars', exphbs({
        defaultLayout: 'main',
        // ...implement newly added insecure prototype access
        handlebars: allowInsecurePrototypeAccess(Handlebars)
        })
    );
    app.set('view engine', 'handlebars');
    
    app.use(routes);
    
    const MONGODB_URI = process.env.MONGODB_URI || >'mongodb://localhost/dbName';
    
    mongoose.connect(MONGODB_URI);
    
    app.listen(PORT, function () {
      console.log('Listening on port: ' + PORT);
    });
    

    3 - Run the server and do your happy dance.


    LONGER MORE SECURE METHOD

    Before passing the object returned by your AJAX call to the Handlebars template, map it into a new object with each property or function you need to access in your .hbs file. Below you can see the new object made before passing it to the Handlebars template.

    const router = require("express").Router();
    const db = require("../../models");
    
    router.get("/", function (req, res) {
        db.Article.find({ saved: false })
            .sort({ date: -1 })
            .then(oldArticleObject => {
                const newArticleObject = {
                    articles: oldArticleObject.map(data => {
                        return {
                            headline: data.headline,
                            summary: data.summary,
                            url: data.url,
                            date: data.date,
                            saved: data.saved
                        }
                    })
                }
                res.render("home", {
                    articles: newArticleObject.articles
                })
            })
            .catch(error => res.status(500).send(error));
    });
    

    Your mongoose query

    Correct me if I'm wrong but I think this might work for your query...

    Confession.find()
        .sort({ date: -1 })
        .then(function (oldDoc) {
    
            for (var i = 0; i < oldDoc.length; i++) {
                //Check whether sender is anonymous
                if (oldDoc[i].from === "" || oldDoc[i].from == null) {
                    oldDoc[i].from = "Anonymous";
                }
    
                //Add an extra JSON Field for formatted date
                oldDoc[i].formattedDate = formatTime(oldDoc[i].date);
            }
    
            const newDoc = {
                doc: oldDoc.map(function (data) {
                    return {
                        from: data.from,
                        formattedDate: data.formattedDate
                    }
                })
            }
            
            res.render('index', { title: 'Confession Box', success: req.session.success, errors: req.session.errors, confession: newDoc.doc });
            req.session.errors = null;
            req.session.success = null;
        });
    

提交回复
热议问题