第 4 章:安全性 - 简介
在上一章中,我们创建了第一个表用于存储业务数据。在Odoo这样的商业应用程序中,第一个要考虑的问题是谁可以访问数据。Odoo提供允许访问的安全机制,允许特定用户访问数据。
Odoo是一个高度数据驱动的系统。尽管行为是使用Python代码自定义的,但 module 的价值在于它在加载时设置的数据。加载数据的一种方法是通过 CSV 文件。一个例子是在安装基础模块时加载的国家/地区列表。
"id","country_id:id","name","code"
state_au_1,au,"Australian Capital Territory","ACT"
state_au_2,au,"New South Wales","NSW"
state_au_3,au,"Northern Territory","NT"
state_au_4,au,"Queensland","QLD"
...
id是外部标识符。它可以用来引用记录 (不知道其数据库内标识符)。
country_id:id使用其外部标识符引用国家/地区。
name是状态的名称。
code是州代码。
这三个字段在模型中定义:
class CountryState(models.Model):
_description = "Country state"
_name = 'res.country.state'
_order = 'code'
country_id = fields.Many2one('res.country', string='Country', required=True)
name = fields.Char(string='State Name', required=True,
help='Administrative divisions of a country. E.g. Fed. State, Departement, Canton')
code = fields.Char(string='State Code', help='The state code.', required=True)
按照惯例,导入数据的文件位于模块的data文件夹中。当数据与安全性相关,则位于文件夹security中。当数据与视图和操作(我们稍后会介绍),它位于views文件夹中。 此外,所有这些文件都必须在__manifest__.py文件中声明。
所以我们模块的目录结构如下:
addons/estate
├──data
├── models
│ ├── estate_property.py
│ └── __init__.py
├── security
├── views
├── __init__.py
└── __manifest__.py
请注意,只有在安装或更新模块时才会加载数据文件的内容。
为什么这一切对安全性很重要?因为模型的所有安全配置都是通过 data 文件,我们将在下一节中看到。
当模型上未定义访问权限时, Odoo确定没有用户可以访问数据。 它甚至在日志中被通知:
WARNING rd-demo odoo.modules.loading: The models ['estate.property'] have no access rules in module estate, consider adding some, like:
id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink
访问权限定义为ir.model.access模型的记录。每个访问权限与一个模型、一个组(全局访问无组)和一组权限相关联:create、read、write和unlink。这些访问权限通常定义在名为ir.model.access.csv的 CSV 文件中。
下面是我们前面的一个例子:test_model
id,name,model_id/id,group_id/id,perm_read,perm_write,perm_create,perm_unlink
access_test_model,access_test_model,model_test_model,base.group_user,1,0,0,0
id是外部标识符。
name是ir.model.access的名称。
model_id/id指适用访问权限的模型。
group_id/id指访问权限适用的组。
perm_read,perm_write,perm_create,perm_unlink:读取、写入、创建和取消链接权限。
结合上面的例子,给我们之前创建的estate_property模型创建权限:
在estate/security/ir.model.access.csv文件里加入以下权限控制:
id,name,model_id/id,group_id/id,perm_read,perm_write,perm_create,perm_unlink
access_estate_property,access_estate_property,model_estate_property,base.group_user,1,1,1,1
创建权限后,重启Odoo服务器,如果控制台未出现WARNING,则说明创建权限成功!
第4章:安全性-简介