11# Copyright 2018 ACSONE SA/NV
22# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
33
4+ import secrets
5+
46from odoo import api , fields , models , tools
57from odoo .exceptions import AccessError , ValidationError
68from odoo .tools import consteq
@@ -13,6 +15,7 @@ class AuthApiKey(models.Model):
1315 name = fields .Char (required = True )
1416 key = fields .Char (
1517 required = True ,
18+ default = lambda self : self ._generate_random_key_value (),
1619 help = """The API key. Enter a dummy value in this field if it is
1720 obtained from the server environment configuration.""" ,
1821 )
@@ -31,6 +34,28 @@ class AuthApiKey(models.Model):
3134
3235 _name_uniq = models .Constraint ("unique(name)" , "Api Key name must be unique." )
3336
37+ @api .model
38+ def _generate_random_key_value (self ):
39+ """Return a random API key value.
40+
41+ The token is generated by the Odoo server instance so XML data and the
42+ UI button can create a secret without storing any default value in the
43+ module sources.
44+ """
45+ return secrets .token_urlsafe (32 )
46+
47+ def generate_random_key (self , api_key_ids = None ):
48+ """Generate a key for records that do not have one yet.
49+
50+ :param list api_key_ids: optional record IDs, mainly used by XML data
51+ function calls where the method is invoked on the model.
52+ :return: True when the operation completed.
53+ """
54+ api_keys = self .browse (api_key_ids ) if api_key_ids else self
55+ for api_key in api_keys .filtered (lambda record : not record .key ):
56+ api_key .key = api_key ._generate_random_key_value ()
57+ return True
58+
3459 @api .model
3560 def _retrieve_api_key (self , key ):
3661 return self .browse (self ._retrieve_api_key_id (key ))
0 commit comments