Browse Source

Merge PR #464 into 14.0

Signed-off-by StefanRijnhart
myc-14.0-py3o
OCA-git-bot 4 years ago
parent
commit
57169c0673
  1. 1
      .travis.yml
  2. 80
      report_qweb_encrypt/README.rst
  3. 2
      report_qweb_encrypt/__init__.py
  4. 18
      report_qweb_encrypt/__manifest__.py
  5. 1
      report_qweb_encrypt/controllers/__init__.py
  6. 37
      report_qweb_encrypt/controllers/main.py
  7. 1
      report_qweb_encrypt/models/__init__.py
  8. 74
      report_qweb_encrypt/models/ir_actions_report.py
  9. 3
      report_qweb_encrypt/readme/CONTRIBUTORS.rst
  10. 4
      report_qweb_encrypt/readme/DESCRIPTION.rst
  11. 1
      report_qweb_encrypt/readme/USAGE.rst
  12. BIN
      report_qweb_encrypt/static/description/icon.png
  13. 96
      report_qweb_encrypt/static/src/js/report/action_manager_report.js
  14. 16
      report_qweb_encrypt/templates/assets.xml
  15. 1
      report_qweb_encrypt/tests/__init__.py
  16. 32
      report_qweb_encrypt/tests/test_report_qweb_encrypt.py
  17. 32
      report_qweb_encrypt/views/ir_actions_report.xml
  18. 1
      setup/report_qweb_encrypt/odoo/addons/report_qweb_encrypt
  19. 6
      setup/report_qweb_encrypt/setup.py

1
.travis.yml

@ -33,6 +33,7 @@ install:
- git clone --depth=1 https://github.com/OCA/maintainer-quality-tools.git - git clone --depth=1 https://github.com/OCA/maintainer-quality-tools.git
${HOME}/maintainer-quality-tools ${HOME}/maintainer-quality-tools
- export PATH=${HOME}/maintainer-quality-tools/travis:${PATH} - export PATH=${HOME}/maintainer-quality-tools/travis:${PATH}
- export WKHTMLTOPDF_VERSION=0.12.4
- travis_install_nightly - travis_install_nightly
script: script:

80
report_qweb_encrypt/README.rst

@ -0,0 +1,80 @@
===================
Report Qweb Encrypt
===================
.. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!! This file is generated by oca-gen-addon-readme !!
!! changes will be overwritten. !!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
.. |badge1| image:: https://img.shields.io/badge/maturity-Beta-yellow.png
:target: https://odoo-community.org/page/development-status
:alt: Beta
.. |badge2| image:: https://img.shields.io/badge/licence-AGPL--3-blue.png
:target: http://www.gnu.org/licenses/agpl-3.0-standalone.html
:alt: License: AGPL-3
.. |badge3| image:: https://img.shields.io/badge/github-OCA%2Freporting--engine-lightgray.png?logo=github
:target: https://github.com/OCA/reporting-engine/tree/12.0/report_qweb_encrypt
:alt: OCA/reporting-engine
.. |badge4| image:: https://img.shields.io/badge/weblate-Translate%20me-F47D42.png
:target: https://translation.odoo-community.org/projects/reporting-engine-12-0/reporting-engine-12-0-report_qweb_encrypt
:alt: Translate me on Weblate
.. |badge5| image:: https://img.shields.io/badge/runbot-Try%20me-875A7B.png
:target: https://runbot.odoo-community.org/runbot/143/12.0
:alt: Try me on Runbot
|badge1| |badge2| |badge3| |badge4| |badge5|
This module allows you to encrypt pdf files with a password when
downloading them.
**Table of contents**
.. contents::
:local:
Usage
=====
To make a report encryptable mark the field `Encryptable` in the report record.
Bug Tracker
===========
Bugs are tracked on `GitHub Issues <https://github.com/OCA/reporting-engine/issues>`_.
In case of trouble, please check there if your issue has already been reported.
If you spotted it first, help us smashing it by providing a detailed and welcomed
`feedback <https://github.com/OCA/reporting-engine/issues/new?body=module:%20report_qweb_encrypt%0Aversion:%2012.0%0A%0A**Steps%20to%20reproduce**%0A-%20...%0A%0A**Current%20behavior**%0A%0A**Expected%20behavior**>`_.
Do not contact contributors directly about support or help with technical issues.
Credits
=======
Authors
~~~~~~~
* Creu Blanca
Contributors
~~~~~~~~~~~~
* Enric Tobella <etobella@creublanca.es>
* Jaime Arroyo <jaime.arroyo@creublanca.es>
Maintainers
~~~~~~~~~~~
This module is maintained by the OCA.
.. image:: https://odoo-community.org/logo.png
:alt: Odoo Community Association
:target: https://odoo-community.org
OCA, or the Odoo Community Association, is a nonprofit organization whose
mission is to support the collaborative development of Odoo features and
promote its widespread use.
This module is part of the `OCA/reporting-engine <https://github.com/OCA/reporting-engine/tree/12.0/report_qweb_encrypt>`_ project on GitHub.
You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute.

2
report_qweb_encrypt/__init__.py

@ -0,0 +1,2 @@
from . import controllers
from . import models

18
report_qweb_encrypt/__manifest__.py

@ -0,0 +1,18 @@
# Copyright 2020 Creu Blanca
# Copyright 2020 Ecosoft Co., Ltd.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Report Qweb Encrypt",
"summary": "Allow to encrypt qweb pdfs",
"version": "14.0.1.0.0",
"license": "AGPL-3",
"author": "Creu Blanca,Ecosoft,Odoo Community Association (OCA)",
"website": "https://github.com/OCA/reporting-engine",
"depends": [
"web",
],
"data": ["views/ir_actions_report.xml", "templates/assets.xml"],
"installable": True,
"maintainers": ["kittiu"],
}

1
report_qweb_encrypt/controllers/__init__.py

@ -0,0 +1 @@
from . import main

37
report_qweb_encrypt/controllers/main.py

@ -0,0 +1,37 @@
# Copyright 2020 Creu Blanca
# Copyright 2020 Ecosoft Co., Ltd.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import json
from werkzeug.urls import url_decode
from odoo.http import request, route
from odoo.addons.web.controllers import main as report
class ReportController(report.ReportController):
@route()
def report_download(self, data, token):
result = super().report_download(data, token)
# When report is downloaded from print action, this function is called,
# but this function cannot pass context (manually entered password) to
# report.render_qweb_pdf(), encrypton for manual password is done here.
requestcontent = json.loads(data)
url, ttype = requestcontent[0], requestcontent[1]
if (
ttype in ["qweb-pdf"]
and result.headers["Content-Type"] == "application/pdf"
and "?" in url
):
url_data = dict(url_decode(url.split("?")[1]).items())
if "context" in url_data:
context = json.loads(url_data["context"])
if "encrypt_password" in context:
Report = request.env["ir.actions.report"]
data = result.get_data()
encrypted_data = Report._encrypt_pdf(
data, context["encrypt_password"]
)
result.set_data(encrypted_data)
return result

1
report_qweb_encrypt/models/__init__.py

@ -0,0 +1 @@
from . import ir_actions_report

74
report_qweb_encrypt/models/ir_actions_report.py

@ -0,0 +1,74 @@
# Copyright 2020 Creu Blanca
# Copyright 2020 Ecosoft Co., Ltd.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import logging
from io import BytesIO
from odoo import _, fields, models
from odoo.exceptions import ValidationError
from odoo.tools.safe_eval import safe_eval
_logger = logging.getLogger(__name__)
try:
from PyPDF2 import PdfFileReader, PdfFileWriter
except ImportError as err:
_logger.debug(err)
class IrActionsReport(models.Model):
_inherit = "ir.actions.report"
encrypt = fields.Selection(
[("manual", "Manual Input Password"), ("auto", "Auto Generated Password")],
string="Encryption",
help="* Manual Input Password: allow user to key in password on the fly. "
"This option available only on document print action.\n"
"* Auto Generated Password: system will auto encrypt password when PDF "
"created, based on provided python syntax.",
)
encrypt_password = fields.Char(
help="Python code syntax to gnerate password.",
)
def _render_qweb_pdf(self, res_ids=None, data=None):
document, ttype = super(IrActionsReport, self)._render_qweb_pdf(
res_ids=res_ids, data=data
)
password = self._get_pdf_password(res_ids[:1])
document = self._encrypt_pdf(document, password)
return document, ttype
def _get_pdf_password(self, res_id):
encrypt_password = False
if self.encrypt == "manual":
# If use document print action, report_download() is called,
# but that can't pass context (encrypt_password) here.
# As such, file will be encrypted by report_download() again.
# --
# Following is used just in case when context is passed in.
encrypt_password = self._context.get("encrypt_password", False)
elif self.encrypt == "auto" and self.encrypt_password:
obj = self.env[self.model].browse(res_id)
try:
encrypt_password = safe_eval(self.encrypt_password, {"object": obj})
except Exception:
raise ValidationError(
_("Python code used for encryption password is invalid.\n%s")
% self.encrypt_password
)
return encrypt_password
def _encrypt_pdf(self, data, password):
if not password:
return data
output_pdf = PdfFileWriter()
in_buff = BytesIO(data)
pdf = PdfFileReader(in_buff)
output_pdf.appendPagesFromReader(pdf)
output_pdf.encrypt(password)
buff = BytesIO()
output_pdf.write(buff)
return buff.getvalue()
def _get_readable_fields(self):
return super()._get_readable_fields() | {"encrypt"}

3
report_qweb_encrypt/readme/CONTRIBUTORS.rst

@ -0,0 +1,3 @@
* Enric Tobella <etobella@creublanca.es>
* Jaime Arroyo <jaime.arroyo@creublanca.es>
* Kitti U. <kittiu@ecosoft.co.th>

4
report_qweb_encrypt/readme/DESCRIPTION.rst

@ -0,0 +1,4 @@
This module allow you to encrypt PDF with a password seting option,
* Manually keyin password (only applicable for record print action)
* Auto generated password based on object data (python)

1
report_qweb_encrypt/readme/USAGE.rst

@ -0,0 +1 @@
To make a report encryptable mark the field `Encryption` in the report record.

BIN
report_qweb_encrypt/static/description/icon.png

After

Width: 128  |  Height: 128  |  Size: 9.2 KiB

96
report_qweb_encrypt/static/src/js/report/action_manager_report.js

@ -0,0 +1,96 @@
// © 2017 Creu Blanca
// License AGPL-3.0 or later (https://www.gnuorg/licenses/agpl.html).
odoo.define("report_qweb_encrypt.Dialog", function (require) {
"use strict";
var ActionManager = require("web.ActionManager");
var Dialog = require("web.Dialog");
var core = require("web.core");
var _t = core._t;
var EncryptDialog = Dialog.extend({
events: _.extend({}, Dialog.prototype.events, {
change: "_onChange",
}),
_setValue: function () {
this.value = this.$el.find(".o_password").val();
},
_onChange: function () {
this._setValue();
},
});
EncryptDialog.askPassword = function (owner, action, action_options, options) {
var buttons = [
{
text: _t("Ok"),
classes: "btn-primary",
close: true,
click: function () {
var password = this.value || false;
owner._executeReportAction(action, action_options, password);
},
},
{
text: _t("Cancel"),
close: true,
click: false,
},
];
return new EncryptDialog(
owner,
_.extend(
{
size: "small",
buttons: buttons,
$content: $(
'<div><input class="o_password" type="password"/></div>'
),
title: _t("Encrypt"),
},
options
)
).open();
};
ActionManager.include({
_executeReportAction: function (action, options, password) {
if (
action.encrypt === "manual" &&
action.report_type === "qweb-pdf" &&
password === undefined
) {
EncryptDialog.askPassword(this, action, options);
return $.Deferred();
} else if (action.encrypt === "manual") {
action.context = _.extend({}, action.context, {
encrypt_password: password,
});
}
return this._super(action, options, password);
},
_makeReportUrls: function (action) {
var reportUrls = this._super.apply(this, arguments);
if (action.encrypt === "manual" && action.context.encrypt_password) {
if (
_.isUndefined(action.data) ||
_.isNull(action.data) ||
(_.isObject(action.data) && _.isEmpty(action.data))
) {
var serializedOptionsPath =
"?context=" +
encodeURIComponent(
JSON.stringify({
encrypt_password: action.context.encrypt_password,
})
);
reportUrls = _.mapObject(reportUrls, function (value) {
value += serializedOptionsPath;
return value;
});
}
}
return reportUrls;
},
});
});

16
report_qweb_encrypt/templates/assets.xml

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8" ?>
<odoo>
<!--
(Copyright) 2020 Creu Blanca
License AGPL-3.0 or later (https://www.gnuorg/licenses/agpl.html).
-->
<template id="assets_backend" inherit_id="web.assets_backend">
<xpath expr="." position="inside">
<script
type="text/javascript"
src="/report_qweb_encrypt/static/src/js/report/action_manager_report.js"
/>
</xpath>
</template>
</odoo>

1
report_qweb_encrypt/tests/__init__.py

@ -0,0 +1 @@
from . import test_report_qweb_encrypt

32
report_qweb_encrypt/tests/test_report_qweb_encrypt.py

@ -0,0 +1,32 @@
# © 2016 Therp BV <http://therp.nl>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo.exceptions import ValidationError
from odoo.tests.common import HttpCase
class TestReportQwebEncrypt(HttpCase):
def test_report_qweb_no_encrypt(self):
ctx = {"force_report_rendering": True}
report = self.env.ref("web.action_report_internalpreview")
report.encrypt = False
pdf, _ = report.with_context(ctx)._render_qweb_pdf([1])
self.assertFalse(pdf.count(b"/Encrypt"))
def test_report_qweb_auto_encrypt(self):
ctx = {"force_report_rendering": True}
report = self.env.ref("web.action_report_internalpreview")
report.encrypt = "auto"
report.encrypt_password = False
# If no encrypt_password, still not encrypted
pdf, _ = report.with_context(ctx)._render_qweb_pdf([1])
self.assertFalse(pdf.count(b"/Encrypt"))
# If invalid encrypt_password, show error
report.encrypt_password = "invalid python syntax"
with self.assertRaises(ValidationError):
pdf, _ = report.with_context(ctx)._render_qweb_pdf([1])
# Valid python string for password
report.encrypt_password = "'secretcode'"
pdf, _ = report.with_context(ctx)._render_qweb_pdf([1])
self.assertTrue(pdf.count(b"/Encrypt"))
# TODO: test_report_qweb_manual_encrypt, require JS test?

32
report_qweb_encrypt/views/ir_actions_report.xml

@ -0,0 +1,32 @@
<?xml version="1.0" encoding="utf-8" ?>
<!-- Copyright 2020 Creu Blanca
Copyright 2020 Ecosoft Co., LTd.
License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). -->
<odoo>
<record model="ir.ui.view" id="ir_actions_report_form_view">
<field name="name">ir.actions.report.form (in report_qweb_encrypt)</field>
<field name="model">ir.actions.report</field>
<field name="inherit_id" ref="base.act_report_xml_view" />
<field name="arch" type="xml">
<field name="paperformat_id" position="after">
<label
for="encrypt"
attrs="{'invisible': [('report_type', 'not in', ('qweb-pdf', 'qweb-html'))]}"
/>
<div
name="encrypt"
attrs="{'invisible': [('report_type', 'not in', ('qweb-pdf', 'qweb-html'))]}"
>
<field name="encrypt" />
<field
name="encrypt_password"
attrs="{'invisible': [('encrypt', '!=', 'auto')]}"
placeholder="python syntax, i.e., (object.default_code or 'secretcode')"
/>
</div>
</field>
</field>
</record>
</odoo>

1
setup/report_qweb_encrypt/odoo/addons/report_qweb_encrypt

@ -0,0 +1 @@
../../../../report_qweb_encrypt

6
setup/report_qweb_encrypt/setup.py

@ -0,0 +1,6 @@
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
Loading…
Cancel
Save