Commit Graph
102 Commits
Author SHA1 Message Date
0a744accc2 [IMP] base_automation,*: simpler edition workflow
*: base, crm, digest, mail, mass_mailing, sms, test_base_automation,
   website_forum, website_sale

This commit makes "Automated Actions" more discoverable and usable by:

- Adding a menu in the kanban header config dropdown to add/edit them.
- Creating a new custom kanban view for a clear understanding of each
  automated action record and its associated actions.
- Introducing new "smart" triggers that appear in the form view based on the
  chosen model:
  - Updated Values category:
    - "Stage is set to" when a `stage_id` field exists in the model,
      allowing users to select a specific stage value.
    - "State is set to" when a `state` field exists in the model,
      allowing users to select a specific state value.
    - "Priority is set to" (`priority`) where users can select a specific priority.
    - "User is set" (`user_id`, `user_ids` fields)
    - "Tag is added" (`tag_ids` field) where users can select a specific tag.
    - "On Archive"
    - "On Unarchive"
  - Timing Conditions:
    - "After creation"
    - "After last update"
- Deprecating previously known triggers "On Creation" (`on_create`) and "On
  Update" (`on_write`) to simplify the user experience. "On Creation & Update"
  (`on_create_or_write`) is retained and renamed to "On save".
- Changing the `ir.actions.server` Many2one relationship to a One2many
  relationship. Automated actions can now directly contain multiple actions,
  eliminating the need for an "Execute several actions" action in automation
  rules.
- Introducing a widget for the new `ir.actions.server` One2many field for a
  clearer understanding of multiple actions.

This commit also enhances the usability of "Server Actions" (`ir.actions`) by:

- Removing the `ir.server.object.lines` model and the associated `fields_lines`
  One2Many field. The attributes of the removed model are now merged into
  `ir.actions`. An action can now write to only one field, and the create action
  is now a name_create action.
- Adapting the form view when creating an "Update the record" action. The value
  field shown adapts itself based on the field to update; this field can be a
  `reference` field for a `one2many` `update_field_id`, a `one2many` field for a
  selection `update_field_id`, or a `text` field otherwise.
- Refactoring the form view to display only relevant details and other
  miscellaneous improvements.

Taskid: 3085360
Part-of: odoo/odoo#114352
Co-authored-by: Florent Dardenne <dafl@odoo.com>
Co-authored-by: Julien Carion <juca@odoo.com>
Co-authored-by: Lucas Perais <lpe@odoo.com>
2023-09-05 18:44:13 +00:00
Julien Carion (juca) d1c6bc5d95 [FIX] mail, base: move user settings access rules
In b1e2c3453f50cc05a1b03dc1c8571a01ad7b7dd2, the `res.users.settings`
model was moved from `mail/` to `base/`, but its record rules remained
in `mail/`. This means that if `mail/` is not installed, users will be
able to access other users' `res.users.settings` records. In practice,
this is not a problem, as the only field that can exist in
`res.users.settings` without `mail/` is `homemenu_config`, which
contains nothing senstive.

This commit moves the forgotten record rules to `base/`, preventing
potential problems if new fields with sensitive information were to be
added to `res.users.settings` in the future.

Task-3461652

closes odoo/odoo#131538

X-original-commit: 5a79550c8e35ce733375c2ef7df2ea12e6added6
Signed-off-by: Louis Wicket (wil) <wil@odoo.com>
2023-08-10 18:14:36 +02:00
Martin Trigaux cd2f330bec [IMP] *: remove glocal ACL
Specify explicit route for each ,, line
This is part of task 3230280 where global ir.model.access will be
forbidden.
The goal is to make access to public/portal explicit. Too often,
global access was granted with only employees in mind.

Remove ,,0,0,0,0 lines

mail:
employee already had read access to mail.group
still needed to subtypes as in ir.rule domain

mail_group: employee already had read access
pos_mercury: only needed for employees

membership:
move public access for website_membership as needed in the controllers

website_customer: employee already had read access

website_event_booth: no need for category
website_event_exhibitor: retrieved in sudo
website_event_track: not needed for location

Part-of: odoo/odoo#125216
2023-07-11 22:33:47 +02:00
Yannick Tivisse b1f7e56f79 [IMP] base: Remove private res.partner type
- Improve performances, as the ir.rule restricting private partners
  visibility is also applied on res.users by inheritance, on each
  prefetch.
- Solve the issue of partners set as followers on records (eg: application
  form) and then made private, making them impossible to contact via the
  chatter.
- Solve the multiple access issues when trying to access the bank
  account, or the private address for non HR people like the accountants
  forcing the usage of sudo in the business code.

TaskID: 3101400
2023-07-05 14:21:28 +02:00
Julien Carion (juca) 2a37a3d06f [REF] web, base, mail: move res.users.settings from mail to base
This commit moves and adapt the res.users.settings model from mail to base and
and allows to access and modify its content with web's user service.
This allows to access user settings without needing the mail module.

closes odoo/odoo#116005

Related: odoo/enterprise#38360
Signed-off-by: Michaël Mattiello (mcm) <mcm@odoo.com>
2023-06-22 15:40:43 +02:00
Martin Trigaux 604a47ead8 [IMP] *: remove global ACL
THese are rarely intended for all users but often intended only for
employees.

account:
account.incoterms: only used within internal business models
account.journal.group: same as account.journal, add sudo in computed field

account_edi: need access to accounting objects

base_address_extended:
res.city: only employees should access address data

board: only employees uses this (old) module

crm:
crm.stage: internal users business object

hr_recruitment: employees can read

im_livechat: apply same as for the steps

l10n_ar: used on partner, not only invoices
l10n_ec: accessed only through account.move
l10n_latam: accessed on res.partner

mail:
publisher.warrenty.contract: no data, only static models
mail.channel: group_user has already his own rule
mail.group: group_user has already his own rule
mail.message.subtype: group_user has already his own rule
mail.message.all: remove, already has a portal and employee rule

partner_autocomplete: no interaction with public

project:
project.tags: only needed for project sharing

sale_management:
sale.order.option: same as sale.order

utm: employee already has write access

web_editor: test models that have nothing to do here
web_tour: only employees uses tours

website_sale:
product.ribbon: add sudo for access

base:
ir.default: only employees uses set (could probably be converted to group_system)
ir.ui.view.custom: same as ir.ui.view, add sudo when needed
report.*: portal users don't configure reports
res.users.log: create in sudo, no access needed (adapt test to use another model)
res.lang: still needed for public

closes odoo/odoo#118701

Related: odoo/enterprise#41285
Signed-off-by: Martin Trigaux (mat) <mat@odoo.com>
2023-06-12 22:39:26 +02:00
Martin Trigaux 53ca9840d8 [IMP] base: remove read on ir.default
And make get private

Part-of: odoo/odoo#118701
2023-06-12 22:39:25 +02:00
ef00294e71 [IMP] core: store translated fields as JSONB columns
Translated fields no longer use the model ir.translation.  Instead they store
all their values as JSON, and store them into JSONB columns in the model's
table.  The field's column value is either NULL or a JSON dict mapping language
codes to text (the field's value in the corresponding language), and must
contain an entry for key 'en_US' (as it is used as a fallback for all other
languages).  Empty text is allowed in translation values, but not NULL.

Here are examples for a field with translate=True:

    NULL
    {"en_US": "Foo"}
    {"en_US": "Foo", "fr_FR": "Bar", "nl_NL": "Baz"}
    {"en_US": "Foo", "fr_FR": "", "nl_NL": "Baz"}

Like before, writing False to the field makes it NULL, i.e., False in all
languages.  However, writing "" to the field makes its value empty in the
current language, but does not discard the values in the other languages.

Here are examples for a field with translate=xml_translate:

    NULL
    {"en_US": "<div>Foo<p>Bar</p></div>", "fr_FR": "<div>Fou<p>Barre</p></div>"}

Change for callable(translate) fields: one can now write any value in any
language on such a field.  The new value will be adapted in all languages, based
on the mapping of terms between languages in the old values.  Basically the
structure of the value must remain the same in all languages, like before.

Reading a translated field is now both simpler and faster than the former
implementation.  We fetch the value of the field in the current language by
coalescing its value with the 'en_US' value of the field:

    SELECT id, COALESCE(name->>'fr_FR', name->>'en_US') AS name ...

The raw cache of the field contains either None or a dict which is conceptually
a subset of the JSON value in database (except for missing languages).  For the
sake of simplicity, most cache operations deal with the dict and return the text
value in the current language.

Trigram indexes have been adapted to the new storing strategy, and should enable
to search in any language.  Before this change, only the source value of the
field ('en_US') could be indexed.

Computed stored translated fields are not supported by the framework, because of
the complexity of the computation itself: the field would need to be computed in
all active languages.  We chose to not provide any hook to compute a field in
all languages at once, and the framework always invokes a compute method once to
recompute it.

Code translations are no longer stored into the database.  They become static,
and are extracted from the PO files when needed.  The worker simply uses a cache
with extracted code translations for performance.  This is reasonable, since
fr_FR code translations for all modules takes around 2MB of memory, and the
cache can be shared among all registries in the worker.  Changing code
translations requires to update the corresponding PO file and reloading the
worker(s).

Performance summary:
 (+) reading 'model' translated fields is faster
 (+) reading 'model_terms' translated fields is much faster (no need to inject
     translations into the source value)
 (+) searching translated fields with operator 'ilike' is much faster when the
     field is indexed with 'trigram'
 (+) updating translated fields requires less ORM flushing
 (-) importing translations from PO files is 2x slower

Some extra fixes:
 - make field 'name' of ir.actions.actions translated; because of the PG
   inheritance, this is necessary to make the column definition consistent in
   all models that inherit from ir.actions.actions.
 - add some backend API for the web/website client for editing translations
 - move methods get_field_string() to model ir.model.fields
 - move _load_module_terms to model ir.module.module
 - adapt tests in test_impex, test_new_api
 - because env.lang is injected into SQL queries, its returned value is
   now guaranteed to correspond to a valid active language or None
 - remove wizard to insert missing translations (no longer makes sense)

task-id: 2081307

Co-authored-by: Fabien Pinckaers <fp@openerp.com>
Co-authored-by: Raphael Collet <rco@odoo.com>
2022-09-15 22:37:50 +02:00
Xavier Morel b3b85cae9b [IMP] *: owlify password meter and convert change password to real wizard
The changes in `auth_password_policy` are largely the owlification of
the password meter widget:

- modernize the password policy module and convert it to an
  odoo-module (note: now exports a pseudo-abstract class which is
  really a policy, for the sake of somewhat sensibly typing
  `recommendations`)
- replace the implementation of the Meter and PasswordField widgets by
  owl versions

The changes to web and base stem from taking a look at converting the
ChangePassword wizard, and finding that it would be a pain in the ass
but also... unnecessary? It seems to have been done as a wizard
completely in javascript despite being backend-only for legacy
reasons: apparently one of the very old web clients (v5 or v6
probably) implemented it as a "native action" which was directly part
of the client's UI, and so it had to be implemented entirely in the
client.

Over time it was moved back into the regular UI (and moved around
quite a bit), hooked as a client action to maintain access to the
existing UI / dialog.

But since it's been an action opened via a button for years it can
just... be a normal wizard, with password fields, which
auth_password_policy can then set the widget of.

So did that:

- removed the old unnecessary JS, and its dedicated endpoint (which is
  *not* used by portal, portal has its own endpoint)
- used check_identity for the "old password check"
- split out `change_password` with an internal bit so we can have a
  safer (and logged) "set user password" without needing to provide
  the old password, which is now used for the bulk password change
  wizard as well
- added a small wizard which just takes a new password (and
  confirmation), for safety a given change password wizard is only
  accessible to their creator (also the wizard is restricted to
  employees though technically it would probably be fine for portal
  users as well)

Rather than extensive messy rewrite / monkeypatching (the original
wizard was 57 LOC, though also 22 LOC of template, the auth_policy
hooking / patching was 33, plus 8 lines of CSS),
`auth_password_policy` just sets the widget of the `new_password`
field in the new wizard, much as it did the bulk wizard.

Also improve the "hide meter if field is empty" feature by leveraging
`:placeholder-shown`. This requires setting a placeholder, and while
empty works fine in firefox, it doesn't work in chrome. So the
placeholder needs to be a single space. Still, seems better than
updating a fake attribute or manipulating a class for the sake of
trivial styling.

Notes on unlink + transient vacuum

Although the wizard object is only created when actually calling
`change_password`, and is deleted on success, it is possible for the
user to get an error and fail to continue (it should be unlikely
without overrides since the passwords are checked while creating /
saving but...).

While in that case the `new_password` in the database is not the
user's own, it could be their *future* password, or give evidence as
to their password-creation scheme, or some other signal useful to
attack that front of the user's life and behavior. As such, quickly
removing leftovers from the database (by setting a very low transient
lifetime) seems like a good idea.

This is compounded by the `check_identity` having a grace period of 10
minutes. 0.1 is 6 minutes, but because the cron runs every 10 the user
effectively has 6~10 minutes between the moment they create an
incorrect / incomplete version of the wizard and the moment where it
is destroyed if they just leave it.

closes odoo/odoo#99458

Signed-off-by: Xavier Morel (xmo) <xmo@odoo.com>
2022-09-08 18:31:18 +02:00
Romain Derie cf844e34dd [IMP] core: allow some users to bypass the sanitize of HTML field
Add the possibility to flag a HTML field as `sanitize_overridable`.
The sanitizer will then be bypassed if the user doing the operation is
part of the new group `base.group_sanitize_override`.
The "Settings" users are part of that new group.

If such a user wrote some HTML that would have normally been removed by
the sanitizer, then users without the right to bypass the sanitizer
won't be able to write on that field anymore.
Otherwise, it would sanitize the previously written data.
Such cases are detected, and the modification prevented by the system,
which will warn the user about it.

For instance, with a `field.html(sanitize_overridable=True)`: one being
part of `group_sanitize_override` could write `<script></script>`.
Then, someone not part of the group trying to add an element inside that
field like appending a `<p/>` -> `<script></script><p>New Content</p>`
would not be able to because it would go through the sanitizer and
ultimately, removing part of the original value:
`<p>New Content</p>` (`<script></script>` would be removed).

== Real use case ==
In the website builder, there is 2 editor rights:
- group_website_publisher: restricted editor
- group_website_designer: editor & designer

The designer editor can edit pages and views, while the restricted
editor can't do anything unless he is part of other groups.
In edit mode, the restricted editor will only be able to edit fields of
record he has access to.
For instance, being a sales manager allows you to edit a product
description on the website.
Being an event manager -> edit event. Slide manager -> Slides etc.
As those restricted editor are able to edit those fields, they are
(almost) always sanitized to prevent them to introduce malicious code.

Since those fields are sanitized, even admins / designer editor are not
able to fully use the website builder in such fields.

Some clients don't really care about that sanitation, they'd prefer to
avoid it as they trust their manager and would prefer to have the full
builder capability instead.
This is typically the case in small project (butcher, hairdresser,
reseller etc) and in SMEs.

With the new `sanitize_overridable` feature, they will be able to do
that, as the "Designer & Editor" group now also receive the group
`base.group_sanitize_override` (done in next commit).

Part-of: odoo/odoo#97398
2022-08-24 23:03:23 +02:00
std-odoo 66f5bc4dbf [IMP] portal: allow portal users to deactivate their accounts
Purpose
=======
Allow portal users to deactivate their accounts from the portal view.

After the deactivation, they are redirected to the login page, so
they can verify that they can not longer login with their credentials.

We first archived the record and remove sensitive information (password,
login, so he can not log in again with the same credentials).

After the deactivation, we blacklist the email and the phone of the
user, so we are sure that we never send him again email / SMS.

Then, we create a <res.users.deletion> to delete the user and the
partner in a CRON because this operation can be heavy (write_uid,
create_uid field on all models).

Task-2629544

Part-of: odoo/odoo#78298
2022-06-30 12:10:56 +02:00
Victor Feyens fba6ea5a47 [IMP] *: do not force admins to be app admins
For bugfix purposes, app administration groups have been given to
(implied by) the "Settings" group because without those rights,
opening/saving the settings crashed.

1) Do not load hidden view content

This commit uses the conditional inheritance of views
(depending on user groups) to avoid loading unnecessary view
& record content client-side.

This improves performance for admins without the specific application
admin rights, but also fixes the main bugfix problem,
caused by the webclient querying name_get for the records in relational
fields content.

Example:

sale_management adds a res.config.settings field to specify
the default sale.order.template for the current company.

If a 'Settings' user without 'sale.group_sale_manager' opens the
settings, he won't see this setting, but if a default template is
specified for the current company, the webclient will still request
the name_get of this template to the server, because the field
was present in the view, only hidden with a groups attribute.

With this commit change in sale, the field won't be in the view unless
you have the Sale manager group, avoiding the error/traceback/bug.

2) Remove implied application administration groups

Do not force the specific application groups on all 'Settings' user,
they globally do not need those rights, and if they need it, they
can add it to their account themselves.

3) Add a test to make sure settings user are able to manage settings.

4) Enforce 'settings' -> 'access rights' -> 'internal user' groups

As the previous test highlighted some 'false positives' because
it considered a settings user unable to read `crm.team`
and `stock.warehouse` records, we also took the opportunity to enforce
the fact that 'Settings' & 'Access rights' users must be internal users.

It makes no sense for a portal/public user to have access to the
settings, and didn't work anyway.

Part-of: odoo/odoo#91909
2022-06-23 23:48:29 +02:00
Abdelouahab (abla) 533cf7a984 [FIX] base : add unlink access to partner manager
To reproduce
============

- make sure to have two contacts with same email (duplicate Mitchell for example)
- in 'Contacts', switch to 'list view', selected any two contacts with the checkboxes, go the the 'Action' menu and select 'Merge'
- Click on 'Skip these contacts', then click on 'Deduplicate the other contacts', then check the 'Email' checkbox and click on 'Merge with manual check'.
- click on 'Skip these contacts'

an Access Error is raised

Purpose
=======

Partner Manager doesn't have the unlink access to `partner.merge.line` model, this access wasn't given because it's often unecessary,
but here it's good example where it's needed.

Specification
=============

to solve the issue we give the unlink access to partner manager.

opw-2851507

closes odoo/odoo#92188

X-original-commit: a6754f3524401c325ae6926ed6984dc1add24f79
Signed-off-by: Nicolas Lempereur (nle) <nle@odoo.com>
Signed-off-by: abla001 <abla@odoo.com>
2022-05-24 17:09:04 +02:00
Xavier-Do 68ea460f3f [IMP] profiling, base: add enable profiling wizard
When using profiling on a fresh test database, it can be tedious to
access settings to enable the feature. This commit adds a wizard to help
enabling profiling without accessing the settings when trying to
activate profiling on a administrator session.

closes odoo/odoo#75967

Signed-off-by: Xavier Dollé (xdo) <xdo@odoo.com>
2021-09-06 12:03:27 +00:00
Martin Trigaux 5dc4cff60a [IMP] base: remove read access to ir.model*
Model, fields and selections are no longer readable
Removes metadata access
2021-08-10 13:49:04 +02:00
Xavier-Do 4444475ef4 [ADD] base, core: built-in profiling tool in Odoo
This commit adds tooling to profile performance and save execution by
saving stack traces and queries to a file/database in specific format.

----------
Collectors
----------

For now, three different profiling modes (aka Collectors) are available
even if a last once should be introduced by @Gorash to profile qweb
execution.

- SQLCollector (or 'sql'): Saves the current stack trace and the query
every time Cursor.execute() is called. Any query executed on the thread
will be collected, no matter the cursor.

- PeriodicCollector (or 'traces_async'): Saves the stack trace every
'interval' seconds using a parallel thread to profile the caller thread.
The python implementation was optimized to minimize impact on
performance while remaining portable and easy to enable/disable
inside a odoo execution. Higher the frequency (lower the interval),
more impactful the profiling will become on the execution and increase
memory usage. From last experiments, 1ms looks to be a good minimum for
short executions.

- SyncCollector (or 'traces_sync'): Saves the stack trace every function
call/return. This collector is obviously quite impactful on performance
and can quickly overload the memory for long executions, but this is
quite useful to understand the precise path followed by some short
executions. Any time related information will be almost irrelevant with this
collector.

A base Collector defining minimal collectors features can easily be
extended to create custom collectors if needed.

----------------
Profiler & Usage
----------------

Collectors are not supposed to be used by themselves, but should be
given to a Profiler. The Profiler will synchronize collectors starts and
stop, and manage saving them to a file of in a ir_profile in the
database.

Exemple of usage:
```
    with Profiler():
        do_stuff()
```

This simple example will use the default collectors (sql and
traces_async) and save them to the database. The database is defined
automatically from current_thread 'dbname' if available.

Example of usage:
```
    with Profiler(collectors=['sql'], db=False, path=/home/user/logs/do_stuff_profile/{time}):
        do_stuff()
```

This more complex example disable the default behavior consisting
to save to the database, gives a path where the profile will be saved
and specify to only use the 'sql' collector. Note that
collectors=[SQLCollector()] would have the same behavior since
Collectors can be either a Collector instance or a string describing the
desired collector. This allows to define custom params for the
collectors and use custom collectors if needed.

Note that it is always possible to get results after execution without
saving it since they are available on the profiler.

```
    with Profiler(collectors=['sql'], db=False) as p:
        do_stuff()
    print(len([None for entry in p.collectors[0].entries if ...]))
```

Profiler will also save the stack below the profiler start point, and
collectors will only collect the part of the stack over this stack.
This is a good way to reduce collectors CPU and memory usage.

Collected entries will be saved as follows:

```
    [{
        'start': 2.0,
        'context': {},
        'stack': [
            ['path_to_file', lno, 'func_name', 'line_content'],
            ...
        ],
    },
    ...
    ]
```
SQLCollector will add three additional keys on each entry:
- query      (query without parameters)
- full_query (mogrified query with parameters)
- time       (the 'exact' execution time of the query)

----------------
ExecutionContext
----------------

A last tool, ExecutionContext, allows to define some context on some block of code:

Example of usage:
```
    def process_modules(modules)
        for module in modules:
          with ExecutionContext(module=module): # note the 'not linter frienldy but still convenient' 2 spaces indentation
            do_stuff(module):
```

This context will automatically be added in the stack as a virtual frame between
process_modules and do_stuff in order to split do_stuff from one single frame to
one frame per module.

----------
Speedscope
----------
The saved data are in a simple json format easy to analyze, but can't be visualized in
speedscope as they are. A utility class `Speedscope` can be used to generate a format
readable by speedscope. The used format is actually the format defined by speedscope,
meaning that all features should be available using it.

The output format is evented, meaning that we need to transform a list of samples
(a list of stack) to a list of event (going in/out a frame).
This is the main task of the Speedscope, as well as combining samples from different
sources, to display SQLCollector and PeriodicCollector results mixed together.

When stored on an ir_profile, the default speedscope generation can easily be generated
with the speedscope computed field.

This class can be used as it is but will mainly be useful for the next commit.

Special thanks to @rco-odoo for the in depth review and @Gorash for support.
2021-06-02 07:47:48 +00:00
8cc066173d [IMP] *: Improve assets management
This commit changes the way assets are declared in Odoo modules.

Before: assets were declared in template files. Template bundles were
generated from primary templates, so technically any qweb template could
have been called as an asset bundle, with the 't-call-assets' directive.

Being standard qweb templates, they had access to standard HTML tags
(script, link, with or without raw scripts or style definition), qweb
directives (t-call, t-raw, etc.) and could be inherited by other
templates.

Now: assets are defined in the module's manifest and generated by the
't-call-assets' directive.

More information on the new system can be found on the updated user
documentation (see the "JavaScript Reference" section).

Task: 2352566

Co-authored-by: Bruno Boi <boi@odoo.com>
Co-authored-by: Julien Mougenot <jum@odoo.com>
Co-authored-by: Lucas Perais <lpe@odoo.com>
Co-authored-by: Mathieu Duckerts-Antoine <dam@odoo.com>
Co-authored-by: Raphael Collet <rco@odoo.com>
Co-authored-by: Simon Genin <ges@odoo.com>
2021-03-31 13:57:17 +02:00
Julien Castiaux 4b28f1162a [ADD] ir.cron.trigger: Manually schedule cron jobs
Introduce a way to schedule the execution of cron jobs *soon*. Triggered
jobs are included in the next execution batch.

Heavy refactor of the `ir.cron` model so the various parallel queries
use the (not so new) `SKIP LOCKED` postgresql select option which skip
rows that are locked instead of throwing an exception like `NOWAIT`
would do. Various methods has been renamed and the overall selection,
execution and update of job records have been re-architectured.

The cron workers can now to wake up early via a notification on the
`cron_trigger` channel of the meta `postgres` database.

closes odoo/odoo#62124

Task: 2368911
Signed-off-by: Raphael Collet (rco) <rco@openerp.com>
2020-12-09 14:36:28 +00:00
Julien Castiaux 90b52d144a [REF] base: Use Command helper for x2many
Task: 2366606
2020-11-30 10:16:09 +00:00
Victor Feyens 5023d90eb9 [IMP] base: restrict creation/deletion of decimal precisions
A manually created decimal precision won't have any impact on the system 
unless used in custom code, and in this case, the record should be 
specified directly in the custom code datas.

Furthermore, it can still be created/deleted in superuser mode if really 
necessary.

closes odoo/odoo#60744

Signed-off-by: Victor Feyens (vfe) <vfe@odoo.com>
2020-11-27 16:10:01 +00:00
Martin Trigaux 51527987c0 [FIX] base: verify the rights on individual records too
The access rights of a model was checked but not the records themself.
In case a user has access to a model but not to a specific record, he
should not be able to execute a server action on it.

Correct the ir.rule on private partners to be also verified for other
operations than read.
While it was not possible to actually write on it (due to side effects
of ORM where write implies a read operation),
check_access_rule('write') was working on a private address

closes odoo/odoo#61253

X-original-commit: b0028c05d6ba9c67f16992ddb446eea6a854d099
Signed-off-by: Martin Trigaux (mat) <mat@odoo.com>
2020-11-03 11:48:41 +00:00
Simon Genin (ges) 618067aa3f [IMP] base: Document layout preview improvements
The document layout preview is a complete defferent simplified template
with its own css that replicates at best the different styles.
It does not have the external layout features and lack of fidelity.

The new preview actually use the real documents templates and put the
result in an iframe. It now has a high fidelity, though not perfect.

The goal is for a better onboarding, where clients see easely how
documents will look if they had an app to generate them. Of course, the
data on the document is a false invoice.

Refactor all this from base to web.

Task ID 2304177

closes odoo/odoo#56995

X-original-commit: c121a246f16899735306266a3a12b526e08e7620
Signed-off-by: Lucas Perais (lpe) <lpe@odoo.com>
2020-09-03 08:44:35 +00:00
Victor Feyens 633e2252f3 [IMP] base: restrict countries creation/deletion
The modification of countries data should be restricted to knowledgeable users.

Indeed, by modifying, deleting and/or creating res.country records, the resulting
behavior generally won't be what you expect, breaking existing flows (delivery, taxes, VAT validation, ...)
in an open OR hidden way...

By restricting those modifications, we reduce the risks of users breaking their database through
'minor' changes unexpectingly triggering 'heavy' problems.
2020-09-02 16:43:45 +00:00
Nisha patel fac0380c37 [IMP] base: Move the private address, group to technical category
Currently, the access to private addresses group show in the other
category in user form view and due to that it is visible in non-debug
mode too.

So in this commit, Move the private addresses group to tehcnical
category so it should visible in  debug mode only.

closes odoo/odoo#56811

Task-id: 2318509
X-original-commit: 5f0ef2e36c33343a6beada36ef121de4b8767089
Related: odoo/enterprise#12803
Signed-off-by: Yannick Tivisse (yti) <yti@odoo.com>
2020-08-31 14:00:13 +00:00
Martin Trigaux de4213b771 [IMP] base: remove read access on ir.actions.*
Custom actions may contain sensitive information, including business
logic

Task-id: 8203
2020-08-17 09:08:21 +00:00
d0dbbe23f4 [ADD] base: API keys support
* ability for a user to request / create keys associated to their user
* overrides can block RPC solely through API keys, by overriding
  `_rpc_api_keys_only()` (to require API auth even in
  situations where the user has not requested it themselves)
* hash keys just in case as we can do so and might as well, add a
  cleartext index (first 4 bytes of 20) to avoid blowing up the DB if
  a user decides to create millions of keys for some daft reason
* users can delete their own keys, admins can delete (invalidate)
  anyone's keys
* `scope` on API keys can be used to restrict usage to certain
  kind of applications, so API keys can be used for other things
  than global authentication. New keys manually created by users
  have no scope by default so they are valid everywhere (global
  keys). RPC auth (stateless XML-RPC/JSON-RPC) requires global keys

Co-authored-by: Florimond Husquinet <fhu@odoo.com>
Co-authored-by: Olivier Dony <odo@odoo.com>
2020-08-14 23:03:27 +00:00
Xavier Morel 6e69465773 [ADD] base: enhanced security mode for users
Similar to github's sudo mode, my understanding of the intent is to
avoid third parties being able to perform sensitive / serious
operations when leaving a logged-in machine unattended.

This v1 only handles protecting "action methods" (methods called
through buttons and intended to return action descriptors), although
they can be used to "lock out" any methods they won't be able to
prompt and the caller will likely be surprised.
2020-08-14 21:20:47 +00:00
Thibault Francois ec56db3c66 [FIX] base: access right on partner merge wizard are too restricted
Before this commit only admin setting user can merge contact which is a bit to restrictive

Contract Creation group seems more adequate

closes odoo/odoo#54831

X-original-commit: b5d5bc30dd3769deab09cbc0915741a93df229ef
Signed-off-by: Martin Trigaux (mat) <mat@odoo.com>
2020-07-23 11:32:39 +00:00
Xavier Morel add22ec8ef [FIX] base: change password wizard should be restricted to ERP managers
ACLs on the wizard lines should match that of the wizard, otherwise
ERP managers can see the action but get an error as soon as they open
the wizard.

Since ERP managers have write access on arbitrary users, that's
probably the right group to use.

Task 2275134

closes odoo/odoo#53007

X-original-commit: 657d44f08c402bc0547b7cbb01c2d447e641d062
Signed-off-by: Xavier Morel (xmo) <xmo@odoo.com>
2020-06-16 06:04:48 +00:00
Martin Trigaux 8f57863707 [IMP] *: remove access to ir.property
Only administrators can access properties and configure them.
ir.property may contain sensitive information and should only be
accessed via code call to specific methods
2020-05-26 15:50:11 +02:00
Martin Trigaux ccc98e0169 [IMP] base: remove read access to ir.ui.view
Only system users should be able to access directly ir.ui.view records
Other users should use helper methods like fields_view_get or render
to interact with view records (or use sudo)

Give read access to views to publisher
He needs to call read_template on some views like
'web_editor.colorpicker' in edition mode

Restrict ACL on website.page
Apply the same ACL than on ir.ui.view as the model inherits from it.
Give access to designer to modify views
2020-05-14 13:59:10 +02:00
Mitali Patel c248594ee5 [IMP] base: allow restricting / removing exports right
Add a new group allowing administrators to remove the ability for
users to bulk-export data from the database. It's pretty minor as
technically the user can still access the underlying object through
the basic methods but it's still a bit of a roadblock.

Users can export by default.

Task 2170900

closes odoo/odoo#45400

Signed-off-by: Xavier Morel (xmo) <xmo@odoo.com>
2020-04-01 13:07:50 +00:00
Victor Feyens 532c083cbb [IMP] *: remove global field definition in ir rules xml
It is a computed field, there is no need to manually set its value.
2020-03-20 16:15:40 +01:00
Romain Derie 96d3fa4e01 [IMP] base, website: add ir.ui.view action to compare arch (wizard)
This commit adds the possibility to compare a view arch to another one.
The result will be shown in a diff viewer (github like).

This is following what was done at #32009

task-2190072

closes odoo/odoo#44646

Signed-off-by: Jérémy Kersten (jke) <jke@openerp.com>
2020-03-17 15:58:45 +00:00
Martin Trigaux 65530dfd6a [ADD] *: add ir.model.access on all transient models
Following changes needing ir.model.access on transient models too.
Remove groups declaration on the action to move it to ir.model.access
when possible.
Rules are strict by default with no unlink access by default and high
priviledge asked. Adaptations may be needed later.
Write access is given as a wizard may need to be modified in case the
action triggers an error and the user has to correct a value

account*: use account.group_account_user for all transient by default
	  remove account.print.journal relic
stock*: use stock.group_stock_user by default
survey: survey user can send invitations
mail: allow any employee to execute wizards
      additional verifications are made to ensure they are executed
      only on the documents the user has access to you
      give portal access to mail.compose.message as portal still does
      some actions like posting messages on the forum
      add ir.rule to avoid reading somebody else messages
      increase the query count because of undeterminist count
crm: saleman for lead2opp, manager for massmailing
     partner manager for actions linked to partners
     avoid a write in test_lead_lost
sms: any employee can send sms
mrp: mrp user can execute wizards
     give unlink access as making write during do_produce operation
base_import: employees can import files
delivery: stock user can deliver
event_sale: sale user can configure the wizards
	    event user inherit from  sale rights
gamification: employee can give badge
google_service: resolve FIXME
hr: add specific rights
    manager can set a plan according to group on button
    anyone who can write on an employee can register a departure
hr_expense: set rights based on buttons
hr_holidays: an approver can make a summary report
hr_recruitment: recruiter can refuse a candidate
hr_timesheet: can use the wizard if can create a timesheet
l10n_eu_service: managers can create fiscal positions
mass_mailing: same group as on mass.mailing.list
membership: accountant can create invoice from membership
payment: accountant can create a link
	 as the source is an account.move
	 keep the payment.acquirer.onboarding.wizard to system user
	 only as it is called during company configuration
point_of_sale: PoS manager only can use wizards
	       never create closing_balance_confirm_wizard records
product_expiry: stock user has rights on stock.picking
product_margin: access from accounting menus
repair: same rules as for above models
sale: set ir.rule for self wizard only
      add rule from model introduced in payment to add salesman group
sale_crm: saleman can create a quotation from a lead
sale_coupon: any saleman can generate coupon
	     add self ir.rule
sale_product_configurator: salesman can select product variants
snailmail: employee can send letters
website: designers can write on website
website_crm_partner_assign: same rule as group on action
website_sale: sale ACL as for payment.acquirer.onboarding.wizard
website_slides: anyone can send invitation

base: base.language.*: allow employee (cf lang_install)
      change.password.user: can not read change password wizard of
      other users
      test.*: no access is needed

Courtesy of Damien Bouvy, William Andre and Antoine Prieëls for review
of acl
2020-02-04 17:54:18 +01:00
Damien Bouvy 39c00a28df [FIX] base: don't hide internal users behind rules
Example:
  User 1 has access to company A
  User 2 has access to company B
  Customer 1 is shared, has user 2 as their Salesperson
  Try to create a SO for Customer 1 as User 1
      => access rights issue, the quote is trying to set User 2
	 as the salesman of the quote but cannot because of
	base.res_users_rule

This commit makes this flow possible by sharing users
if they're not portal.

closes odoo/odoo#43190

X-original-commit: ebc8d85d383643c1d4d2aa6723bc7a589c7d1c68
Signed-off-by: Damien Bouvy (dbo) <dbo@odoo.com>
2020-01-13 10:51:01 +00:00
Damien Bouvy bd5305a51b [FIX] base: better multi-company rules for partners
Commit d86c2c5883 removed the multi-company partner rule because it
interfered with the users rule. Indeed, interference between the user's
default company and its corresponding partner's company made it possible
to have users that were basically unselectable in relational fields if
you were not viewing more than one company at the same time.

However, this generates a lot of frustrations and tickets for Odoo
users, since having everything shared by default is annoying and a clear
departure from the expected behaviour.

This commit tries to mitigates this fix's side-effects by re-introducing
the multi-company rules but by not applying it to partners who are linked
to a non-share user (basically, any partner who has a user that is not
a portal user). That way, customers and vendors remain filtered by the
multi-company rules and only partners of internal users bypass the rule.
This is still a side-effect, and might raise a few eyebrows (why is this
partner visible even though it is in another company?), but the
trade-off seems to be worth it since it fixes the original issue with a
far smaller behaviour change.

Fixes #41720.

closes odoo/odoo#42592

X-original-commit: 2390ba60b8bd624daaea2e6d4e3fd85ef1b1faeb
Signed-off-by: Damien Bouvy (dbo) <dbo@odoo.com>
2020-01-02 13:31:28 +00:00
Arnold Moyaux d86c2c5883 [FIX] base: res_users in multi company
Usecase to reproduce:
- User1 in company A and company B (default company A)
- User2 in company A and company B (default company A)

As user1 select company B in company switcher.
-> You never see user2 as he's hidden by a record rule.

This issue was present in older version when disabling the “Common Contact Book” feature,
because it was then enabling the faulty record rule. Since [1], this faulty record rule is
always enabled.
(Note that res.partner record rules are applied to res.user through _inherits)

We chose to remove the faulty record rules so that the present usecase is now working,
but the drawback is that you now see partners from other companies.

Also remove [2] that try to fix the issue and become useless if the
rule is removed.

[1] commit 25714692b2
[2] commit d6c65aa4d4

closes odoo/odoo#37712

Signed-off-by: Arnold Moyaux <amoyaux@users.noreply.github.com>
2019-10-01 13:42:50 +00:00
RomainLibert d6c65aa4d4 [FIX] base: allow users to read themselves in multicompany
You should always be able to read your own user whatever the company you
are logged into

closes odoo/odoo#36190

Signed-off-by: Yannick Tivisse (yti) <yti@odoo.com>
2019-08-28 13:47:39 +00:00
Raphael Collet 9920f20e4c [IMP] models: ORM speedup
This branch is the combination of several optimizations in the ORM:

* store field values once in the cache: the cache reflects more
faithfully the database, only fields that explicitly depend on the
context have an extra indirection in the cache;

* delay recomputations by default: use method `recompute` to explicitly
flush out pending recomputations;

* delay updates in method `write`: updates are stored in a data
structure that can be flushed efficiently to the database with method
`flush` (which also flush out recomputations);

* make method `modified` take advantage of inverse fields to inverse
dependencies;

* filter records by evaluating a domain on records in Python;

* a computed field with `readonly=False` behaves like a normal field
with an onchange method;

* computed fields are computed in superuser mode by default.

Work done by Toufik Ben Jaa, Raphael Collet, Denis Ledoux and Fabien
Pinckaers.

closes odoo/odoo#35659

Signed-off-by: Denis Ledoux <beledouxdenis@users.noreply.github.com>
2019-08-20 12:43:59 +00:00
Martin TrigauxandRaphaël Collet 7593b887df [REF] fields: use ir.model.fields.selection
The selection values of a selection field are now stored in database in the
model ir.model.fields.selection

This will allow to have a modular approche on selections and each selection
is now linked to the module that declared it.
Previously to this change, the selections were linked to the field, meaning
uninstalling a module had no impact on the selections stored on database.

With this change, the selections will now be translated in the correct module
(having an external id) and the records having a used selection will now be
reset to null.

closes odoo/odoo#30228

Signed-off-by: Martin Trigaux (mat) <mat@odoo.com>


Co-authored-by: Raphaël Collet <rco@odoo.com>
2019-08-19 11:44:34 +00:00
Prakash Prajapati 25714692b2 [IMP] base: remove the 'Shared contacts book' general setting
The Common partner contact setting is removed from general settings because its
behavior wasn't really clean from a technical point of view
(disabling the rule on partner access) and wouldn't work as well with new
multi-company logic.

The default logic of sharing partner will be kept, but when someone wants to
limit partner sharing, he will do so partner by partner, by
setting the company_id.
Also, the default company_id on a partner will be blank so default partner
will be a sharable by multi-company.

when the partner is created at the time of user creation then the partner's
company will be the same as user's company.and when the partner is created at
the time of company creation(partner related to company) then the company of
partner will be newly created company.

task-2024446
Closes: #35266
2019-08-16 11:14:58 +00:00
Julien MougenotandLucas Perais ed18095127 [IMP] base: Configure document layout
The onboarding modal for setting up the few base fields of a company
has now been moved to a wizard
It is accessible from the general settings, but also in the onboarding
section of sale and account modules.

The following company settings are editable with that wizard:

- Set report **layout**:
The user can chose the overall look of the report. The current choices
are : *Standard* (default), *Background*, *Boxed* and *Clean*.

- Set company **logo**:
Changes the company logo.

- Set report **colors**:
The user can set the primary and secondary colors of the report through
a newly added widget allowing to pick a custom color.
When changing the **logo**, colors are automatically set to its most dominant
colors.
> A "Reset colors" button also triggers the color calculation.

- Set report **font**:
Changes the overall font of the report. Only Google Fonts are used
for enhanced compatibility.

- Company **tagline**, also called "header"
- **Footer**
- **Paper format**
- Report **preview**:
A mockup of a final report
Automatically updates when changing **layout**, **logo**, **colors** or **font**

Co-authored by: Julien Mougenot <jum@odoo.com>

closes odoo/odoo#33863

Signed-off-by: VincentSchippefilt <VincentSchippefilt@users.noreply.github.com>


Co-authored-by: Lucas Perais <lpe@odoo.com>
2019-07-29 08:29:26 +00:00
Martin Trigaux dd2fae2ead [IMP] base: remove decimal.precision.test model
It should not be a standard model but a test model
2019-07-03 11:16:24 +00:00
Martin Trigaux a1eb000c93 [IMP] base: remove read access to decimal.precision
There is no reason to interact directly with it.
The method precision_get is done in SQL and ormcached, it is better to use it
2019-07-03 11:16:24 +00:00
Mitali Patel 0c5121a979 [IMP] decimal_precision: integrate into base
The decimal precision feature makes sense to be an ORM feature, no need to be
in a specific module

Previous syntax was
    from odoo.addons import decimal_precision as dp
    fields.Float(digits=dp.get_precision('Foo'))

and now is:
    fields.Float(digits='Foo')

Remove the possibility to have a callable method on the digits attribute (it
was only used for precision anyway) and directly retrieve the digits on the
decimal.precision model

Rename the method digits to get_digits to avoid confusion between the field
attribute when declaring a field and the method to retrieve the precision

Task id: 48198
2019-07-03 11:15:48 +00:00
Yannick Tivisse 2996e7645f [IMP] base: Remove group toggle_multi_company
Fp request
2019-06-04 14:01:42 +02:00
Yannick Tivisse a5b6f31cf2 [IMP] base: Contextualize the multi company
Purpose
=======

Allow the user to select the allowed companies for which he wants to see records
on top of selecting his current company.

It is confusing for users to see the records from the company he is connected to
and the records of the children companies.

Instead of using the hierarchy of companies to access records across companies,
the user can now select (from his set of allowed companies) the companies for
which he wants to access records.

/!\ This means that the user will interact with records from company A when in
company B.
Example: a SO has been created and confirmed in A. When in B, I create the
invoice from it.

Specifications
==============

1/ Deprecate the parent/children hierarchy on the res.company model. The fields are
kept on the res.company model to ensure the retro-compatibility, but won't be used
accross the standard code anymore. The only functional usage for this mechanism
was to allow to see records from several companies by creating a virtual parent
company, which will be possible with the new mechanism.

2/ By default, a user will only see the records of the company he is connected
to (or records without a company). (It is still editable by the user if needed).
For that, put this information in the user context, to allow having different
configurations on different browser tabs. Instead of having domains like
['|',
('company_id', '=', False),
('company_id', 'child_of', user.company_id.id)]
you'll have something like
['|',
('company_id', '=', False),
('company_id', 'in', company_ids)]
Note that the 'company_ids' is a value that is passed in the evaluation
context on the record rule, as we already have user, or time.
company_ids is a list of the ids of all the enabled companies in the
user's context.

3/ Out of the generic improvements brought by this task, this will illustrate
issues that could exist since several versions. For example, it should not be
possible to create a scrap order for the company A with a package of the company
B, or it should not be possible to create an invoice on the company A with
payment terms from the company B. Before the version 12.0, it was easy to
encounter this kind of issues as the admin was the SUPERUSER_ID. A positive side
effect of the fact that the SUPERUSER_ID has become an inactive user was to
make it more difficult to introduce mismatch on the records, but haven't solved
the issue, as it was still possible to do it with parent companies
configuration. Some of these issues have been fixed in this commit, but all the
business flows should be re-tested to check if an ir.rule should be introduced
(eg: a multi company rule for stock.quand.package), if the company of a record
is correctly transfered to another record created from the first record (eg:
From a SO, create an invoice and a payment, the company of the sales order
should be transfered on the invoice and the payment, even if the company of the
sales order is A and I'm logged into the company B with the company A enabled.

4/ Currently, if I click on a button on a notification email (example 'View
Task'), I face a traceback if I'm not logged into the company of the record.
Now, if you click on a button and if you have access to the record, the correct
company will be automatically set.

5/ If I display a kanban view with several records from several companies (and
an image), all the images should be displayed.

6/ Currently if you copy paste an url, this will crash if you're not in the
correct company. This won't be fixed because it's quite impossible to do it in
a clean way. This task brings a workaround. Copy/Paste -> Traceback -> Log into
the correct company, re-copy/paste -> Ok.

7/ 2 property methods have been added on the environment to retrieve the company
on which the user is logged in and the companies the user enabled, on a specific
tab.
That way, when creating a record, instead of doing
default=lambda self: self.env.user.company_id
do
default=lambda self: self.env.company_id
On the other hand, to retrieve the enabled companies, do
companies = self.env.company_ids

8/ Modify the Company Switcher widget to allow to log into another company
WITHOUT writing on the res.users (and thus bringing cache invalidation issues
and so on). Also allow to enable several companies and see records from several
companies, and independantly of the other browser's tabs.

9/ When focusing on a tab, save the current company configuration on the local
storage. That way, when doing 'CTRL+T' or a middle click, the context is
propagated to the new tab.

10/ Improve the error message in case of multi company access errors. Now, when
the user is in debug mode, display the related names of the records and the name
of the user who brings the issue.

11/ Remove the context erasing when writing on a res.users
This is probably coming from the migration to new API of the base module.
The context was not propagated at this moment, which was a common mistake at
that time. When migrating the module, probably by using the 'black box' method,
as the context was not propagated, it was erased on the new version. This is
now an issue because the context (i.e. the enabled companies) was erased when
writing on a res.users, leading to tracebacks.
See: https://github.com/odoo/odoo/commit/7eab8e26d3d46c53f4be924d6a34e80a66e74960#diff-4c2e738ee8f64f11806c889ea097b5e7R624

12/ Fix the crash manager on redirect warnings. The issue is the following
- Create an invoice on a company without a configured CoA.
- Set a partner
- On the onchange_partner_id, a redirect warning is raised to propose you
to configure a CoA
- Click on 'Go to the configuration panel'
- A generic warning says something like 'Do you want to discard your changes?'
- Click on yes, the page refreshes, but not on the redirect action.
Now, set correctly the action on the hash, and reload instead. The breadcrumb is
lost for example, but you reach the correct action at least.

13/ Introduce a res.group to enable/disable the multi company per tab
feature.

14/ To help the users to know which tab is in which company, add the
possibility to have a favicon per company. When creating a company,
the classical 'O' icon is colored by default in a random color.

15/ Remove the company switcher on the frontend. This was mainly there
to allow a user to swicth to the company linked to the website.
This behavior is now transparent to the user. If the website A is
activated, then the company set on the context is the company of the
website.

16/ Deprecated the _company_default_get method on the res.company
model. Remove the method _get_company on the res.users model.

17/ Add 'allowed_company_ids' and 'current_company_id' on the pyeval
context. You can now use those variables on domains in the views to
access directly to the activated company.ies on the current tab.

TaskID: 1960971

closes odoo/odoo#32341

Signed-off-by: Yannick Tivisse (yti) <yti@odoo.com>
2019-05-13 08:57:49 +00:00
Yannick Tivisse 62c9dedafd [IMP] base: Remove useless ACL rules
Now that portal users don't have access to the backend, it doesn't make
sense to give the read access on attachments, as this is the role of
the specific controllers to provide this access according to the business
logic.

For the record, these rules have been introduced at:
https://github.com/odoo/odoo/commit/61065b6d04248aa496765e1035c4c90cbdc38de7
https://github.com/odoo/odoo/commit/f3fa266d115ac9d4723164af10f8dee40821b290

closes odoo/odoo#32134

Signed-off-by: Yannick Tivisse (yti) <yti@odoo.com>
2019-03-29 12:00:25 +00:00
jbm-odoo ec07e72845 [IMP] base,*: Reorganize access rights groups
Purpose
=======

Access group terminology is missleading. Yous have to be manager to administrate
an application. This task consists to rename groups to be understandable for everyone.

Groups should be reorganised on the users form to be more explicit.

Specification
=============

1/ Rename 'Manager' to 'Administrator' in users groups.
2/ Define a hierarchy on access groups by using the category_id in the manifests
   A category 'Operations/Project' will create a category Project with a parent
   category 'Operations', and something smart is already developed (in modules/db.py)
   to avoid duplicating categories.
3/ Add a group in expenses to be able to approve expenses reports for my team.
4/ Add a group in timesheets to be able to approve timesheets for my team.
5/ Remove partially the useless crap in ir_module_category_data.xml
6/ Sort access rights groups on users form according to its parent category

closes odoo/odoo#29362

Signed-off-by: "Yannick Tivisse (yti)" <yti@odoo.com>
2019-03-05 09:08:12 +00:00