You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
1.9 KiB

  1. # -*- coding: utf-8 -*-
  2. # Copyright 2016 Florent de Labarre
  3. # Copyright 2017 Camptocamp
  4. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)
  5. from odoo import api, fields, models
  6. class AuthOauthMultiToken(models.Model):
  7. """Define a set of tokens."""
  8. _name = 'auth.oauth.multi.token'
  9. _description = 'OAuth2 token'
  10. _order = 'id desc'
  11. EMPTY_OAUTH_TOKEN = '****************************'
  12. oauth_access_token = fields.Char(
  13. string='OAuth Access Token',
  14. readonly=True,
  15. copy=False
  16. )
  17. user_id = fields.Many2one(
  18. comodel_name='res.users',
  19. string='User',
  20. required=True
  21. )
  22. active_token = fields.Boolean('Active')
  23. @api.model
  24. def create(self, vals):
  25. """Override to validate tokens."""
  26. token = super(AuthOauthMultiToken, self).create(vals)
  27. token._oauth_validate_multi_token()
  28. return token
  29. @api.model
  30. def _oauth_user_tokens(self, user_id, active=True):
  31. """Retrieve tokens for given user.
  32. :param user_id: Odoo ID of the user
  33. :param active: retrieve active or inactive tokens
  34. """
  35. return self.search([
  36. ('user_id', '=', user_id),
  37. ('active_token', '=', active)
  38. ])
  39. def _oauth_validate_multi_token(self):
  40. """Check current user's token and clear them if max number reached."""
  41. user_tokens = self._oauth_user_tokens(self.user_id.id)
  42. max_token = self.user_id.oauth_access_max_token
  43. if user_tokens and len(user_tokens) > max_token:
  44. # clear last token
  45. user_tokens[max_token - 1]._oauth_clear_token()
  46. @api.multi
  47. def _oauth_clear_token(self):
  48. """Disable current token records."""
  49. self.write({
  50. 'oauth_access_token': self.EMPTY_OAUTH_TOKEN,
  51. 'active_token': False
  52. })