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
@@ -12,7 +14,6 @@ class AuthApiKey(models.Model):
1214
1315 name = fields .Char (required = True )
1416 key = fields .Char (
15- required = True ,
1617 help = """The API key. Enter a dummy value in this field if it is
1718 obtained from the server environment configuration.""" ,
1819 )
@@ -31,6 +32,28 @@ class AuthApiKey(models.Model):
3132
3233 _name_uniq = models .Constraint ("unique(name)" , "Api Key name must be unique." )
3334
35+ @api .model
36+ def _generate_random_key_value (self ):
37+ """Return a random API key value.
38+
39+ The token is generated by the Odoo server instance so XML data and the
40+ UI button can create a secret without storing any default value in the
41+ module sources.
42+ """
43+ return secrets .token_urlsafe (32 )
44+
45+ def generate_random_key (self , api_key_ids = None ):
46+ """Generate a key for records that do not have one yet.
47+
48+ :param list api_key_ids: optional record IDs, mainly used by XML data
49+ function calls where the method is invoked on the model.
50+ :return: True when the operation completed.
51+ """
52+ api_keys = self .browse (api_key_ids ) if api_key_ids else self
53+ for api_key in api_keys .filtered (lambda record : not record .key ):
54+ api_key .key = api_key ._generate_random_key_value ()
55+ return True
56+
3457 @api .model
3558 def _retrieve_api_key (self , key ):
3659 return self .browse (self ._retrieve_api_key_id (key ))
0 commit comments