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,7 @@ class AuthApiKey(models.Model):
1214
1315 name = fields .Char (required = True )
1416 key = fields .Char (
15- required = True ,
17+ default = lambda self : self . _generate_random_key_value () ,
1618 help = """The API key. Enter a dummy value in this field if it is
1719 obtained from the server environment configuration.""" ,
1820 )
@@ -31,6 +33,34 @@ class AuthApiKey(models.Model):
3133
3234 _name_uniq = models .Constraint ("unique(name)" , "Api Key name must be unique." )
3335
36+ @api .constrains ("key" )
37+ def _check_key_required (self ):
38+ for api_key in self :
39+ if not api_key .key :
40+ raise ValidationError (self .env ._ ("The API key is required." ))
41+
42+ @api .model
43+ def _generate_random_key_value (self ):
44+ """Return a random API key value.
45+
46+ The token is generated by the Odoo server instance so XML data and the
47+ UI button can create a secret without storing any default value in the
48+ module sources.
49+ """
50+ return secrets .token_urlsafe (32 )
51+
52+ def generate_random_key (self , api_key_ids = None ):
53+ """Generate a key for records that do not have one yet.
54+
55+ :param list api_key_ids: optional record IDs, mainly used by XML data
56+ function calls where the method is invoked on the model.
57+ :return: True when the operation completed.
58+ """
59+ api_keys = self .browse (api_key_ids ) if api_key_ids else self
60+ for api_key in api_keys .filtered (lambda record : not record .key ):
61+ api_key .key = api_key ._generate_random_key_value ()
62+ return True
63+
3464 @api .model
3565 def _retrieve_api_key (self , key ):
3666 return self .browse (self ._retrieve_api_key_id (key ))
0 commit comments