0

I have the following model:

class LibraryBook(models.Model):
    _name = 'library.book'
    name = fields.Char('Title', required=True)
    date_release = fields.Date("Release Date")
    author_ids = fields.Many2many("res.partner", string="Authors")

I'm new to Odoo and trying to understand the basics of how to save data to my model from a POST request like the following

curl -i -X POST --data "name=Odoo%20-%20Much%20Mystery,%20Wow&author_id=Doge" http://0.0.0.0:8069/test

I found a way doing this by setting the csrf parameter in my controller to false like so:

[...]
@http.route('/test', type='http', auth='public',methods=['POST'], website=True, csrf=False)
def test(self, **kwargs):
    record = request.env['library.book'].sudo()
    record.create(kwargs)

I'm wondering now if there is a way to avoid setting csrf=false since I've read that it's a bad idea to do so in general. Also, what would I need to get rid of that .sudo()? Not setting csrf=false leads to a 400 BAD REQUEST with Invalid CSRF token. Removing sudo() leads to a 500 INTERNAL SERVER ERROR. In Odoo Development Cookbook it says in one example with auth='none'

Lack of a user is also why we have to sudo() all our calls to model methods in the example code

Assuming I would expect a POST request from an API, is it possible to associate it with a user so I don't have to sudo()?

I would very much appreciate any clarification on this.

UPDATE

So I just found this (line 817):

  • if the form is accessed by an external third party (e.g. REST API endpoint, payment gateway callback) you will need to disable CSRF
    protection (and implement your own protection if necessary) by
    passing the csrf=False parameter to the route decorator.

which I guess leaves only one question open, regarding sudo.

Andrei Poehlmann
  • 341
  • 5
  • 14

1 Answers1

1

SUDO()

creates a new environment with the provided user set, uses the administrator if none is provided (to bypass access rights/rules in safe contexts), returns a copy of the recordset it is called on using the new environment:

Odoo does not allow public users to create, update, delete a record. If we want to create a record from the public users then we need to create a record with the sudo().

Create record object as administrator

  request.env['library.book'].sudo().create(vals)

I hope this may help you. for more information you can navigate to following links : https://www.odoo.com/documentation/9.0/reference/orm.html

Thanks

  • How does this ensure that the data came from a legitimate source and not a malicious user? Couldnt someone inject sql commands in the POST? – user2757902 Jul 13 '17 at 11:58