Merge PR #459 into 12.0

Signed-off-by StefanRijnhart
pull/487/head
OCA-git-bot 2021-02-09 13:25:58 +00:00
commit 9663c67ae3
16 changed files with 372 additions and 0 deletions

View File

@ -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.

View File

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

View File

@ -0,0 +1,21 @@
# 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": "12.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"],
}

View File

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

View File

@ -0,0 +1,33 @@
# Copyright 2020 Creu Blanca
# Copyright 2020 Ecosoft Co., Ltd.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo.addons.web.controllers import main as report
from odoo.http import route, request
from werkzeug.urls import url_decode
import json
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

View File

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

View File

@ -0,0 +1,72 @@
# Copyright 2020 Creu Blanca
# Copyright 2020 Ecosoft Co., Ltd.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import time
import logging
from odoo import fields, models, _
from io import BytesIO
from odoo.tools.safe_eval import safe_eval
from odoo.exceptions import ValidationError
_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, 'time': time})
except:
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()

View File

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

View File

@ -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)

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.2 KiB

View File

@ -0,0 +1,82 @@
// © 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 framework = require("web.framework");
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 (event) {
this._setValue();
},
})
EncryptDialog.askPassword = function (owner, action, action_options, options) {
var buttons = [
{
text: _t("Ok"),
classes: 'btn-primary',
close: true,
click: function (event) {
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) {
return value += serializedOptionsPath;
});
}
}
return reportUrls;
}
});
});

View File

@ -0,0 +1,13 @@
<?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>

View File

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

View File

@ -0,0 +1,33 @@
# © 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?

View File

@ -0,0 +1,25 @@
<?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>