microsoft_outlook_mixin.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. # -*- coding: utf-8 -*-
  2. # Part of Odoo. See LICENSE file for full copyright and licensing details.
  3. import json
  4. import logging
  5. import time
  6. import requests
  7. from werkzeug.urls import url_encode, url_join
  8. from odoo import _, api, fields, models
  9. from odoo.exceptions import AccessError, UserError
  10. from odoo.tools.misc import hmac
  11. _logger = logging.getLogger(__name__)
  12. class MicrosoftOutlookMixin(models.AbstractModel):
  13. _name = 'microsoft.outlook.mixin'
  14. _description = 'Microsoft Outlook Mixin'
  15. _OUTLOOK_SCOPE = None
  16. is_microsoft_outlook_configured = fields.Boolean('Is Outlook Credential Configured',
  17. compute='_compute_is_microsoft_outlook_configured')
  18. microsoft_outlook_refresh_token = fields.Char(string='Outlook Refresh Token',
  19. groups='base.group_system', copy=False)
  20. microsoft_outlook_access_token = fields.Char(string='Outlook Access Token',
  21. groups='base.group_system', copy=False)
  22. microsoft_outlook_access_token_expiration = fields.Integer(string='Outlook Access Token Expiration Timestamp',
  23. groups='base.group_system', copy=False)
  24. microsoft_outlook_uri = fields.Char(compute='_compute_outlook_uri', string='Authentication URI',
  25. help='The URL to generate the authorization code from Outlook', groups='base.group_system')
  26. def _compute_is_microsoft_outlook_configured(self):
  27. Config = self.env['ir.config_parameter'].sudo()
  28. microsoft_outlook_client_id = Config.get_param('microsoft_outlook_client_id')
  29. microsoft_outlook_client_secret = Config.get_param('microsoft_outlook_client_secret')
  30. self.is_microsoft_outlook_configured = microsoft_outlook_client_id and microsoft_outlook_client_secret
  31. @api.depends('is_microsoft_outlook_configured')
  32. def _compute_outlook_uri(self):
  33. Config = self.env['ir.config_parameter'].sudo()
  34. base_url = self.get_base_url()
  35. microsoft_outlook_client_id = Config.get_param('microsoft_outlook_client_id')
  36. for record in self:
  37. if not record.id or not record.is_microsoft_outlook_configured:
  38. record.microsoft_outlook_uri = False
  39. continue
  40. record.microsoft_outlook_uri = url_join(self._get_microsoft_endpoint(), 'authorize?%s' % url_encode({
  41. 'client_id': microsoft_outlook_client_id,
  42. 'response_type': 'code',
  43. 'redirect_uri': url_join(base_url, '/microsoft_outlook/confirm'),
  44. 'response_mode': 'query',
  45. # offline_access is needed to have the refresh_token
  46. 'scope': 'offline_access %s' % self._OUTLOOK_SCOPE,
  47. 'state': json.dumps({
  48. 'model': record._name,
  49. 'id': record.id,
  50. 'csrf_token': record._get_outlook_csrf_token(),
  51. })
  52. }))
  53. def open_microsoft_outlook_uri(self):
  54. """Open the URL to accept the Outlook permission.
  55. This is done with an action, so we can force the user the save the form.
  56. We need him to save the form so the current mail server record exist in DB and
  57. we can include the record ID in the URL.
  58. """
  59. self.ensure_one()
  60. if not self.env.user.has_group('base.group_system'):
  61. raise AccessError(_('Only the administrator can link an Outlook mail server.'))
  62. if not self.is_microsoft_outlook_configured:
  63. raise UserError(_('Please configure your Outlook credentials.'))
  64. return {
  65. 'type': 'ir.actions.act_url',
  66. 'url': self.microsoft_outlook_uri,
  67. }
  68. def _fetch_outlook_refresh_token(self, authorization_code):
  69. """Request the refresh token and the initial access token from the authorization code.
  70. :return:
  71. refresh_token, access_token, access_token_expiration
  72. """
  73. response = self._fetch_outlook_token('authorization_code', code=authorization_code)
  74. return (
  75. response['refresh_token'],
  76. response['access_token'],
  77. int(time.time()) + int(response['expires_in']),
  78. )
  79. def _fetch_outlook_access_token(self, refresh_token):
  80. """Refresh the access token thanks to the refresh token.
  81. :return:
  82. access_token, access_token_expiration
  83. """
  84. response = self._fetch_outlook_token('refresh_token', refresh_token=refresh_token)
  85. return (
  86. response['refresh_token'],
  87. response['access_token'],
  88. int(time.time()) + int(response['expires_in']),
  89. )
  90. def _fetch_outlook_token(self, grant_type, **values):
  91. """Generic method to request an access token or a refresh token.
  92. Return the JSON response of the Outlook API and manage the errors which can occur.
  93. :param grant_type: Depends the action we want to do (refresh_token or authorization_code)
  94. :param values: Additional parameters that will be given to the Outlook endpoint
  95. """
  96. Config = self.env['ir.config_parameter'].sudo()
  97. base_url = self.get_base_url()
  98. microsoft_outlook_client_id = Config.get_param('microsoft_outlook_client_id')
  99. microsoft_outlook_client_secret = Config.get_param('microsoft_outlook_client_secret')
  100. response = requests.post(
  101. url_join(self._get_microsoft_endpoint(), 'token'),
  102. data={
  103. 'client_id': microsoft_outlook_client_id,
  104. 'client_secret': microsoft_outlook_client_secret,
  105. 'scope': 'offline_access %s' % self._OUTLOOK_SCOPE,
  106. 'redirect_uri': url_join(base_url, '/microsoft_outlook/confirm'),
  107. 'grant_type': grant_type,
  108. **values,
  109. },
  110. timeout=10,
  111. )
  112. if not response.ok:
  113. try:
  114. error_description = response.json()['error_description']
  115. except Exception:
  116. error_description = _('Unknown error.')
  117. raise UserError(_('An error occurred when fetching the access token. %s', error_description))
  118. return response.json()
  119. def _generate_outlook_oauth2_string(self, login):
  120. """Generate a OAuth2 string which can be used for authentication.
  121. :param user: Email address of the Outlook account to authenticate
  122. :return: The SASL argument for the OAuth2 mechanism.
  123. """
  124. self.ensure_one()
  125. now_timestamp = int(time.time())
  126. if not self.microsoft_outlook_access_token \
  127. or not self.microsoft_outlook_access_token_expiration \
  128. or self.microsoft_outlook_access_token_expiration < now_timestamp:
  129. if not self.microsoft_outlook_refresh_token:
  130. raise UserError(_('Please connect with your Outlook account before using it.'))
  131. (
  132. self.microsoft_outlook_refresh_token,
  133. self.microsoft_outlook_access_token,
  134. self.microsoft_outlook_access_token_expiration,
  135. ) = self._fetch_outlook_access_token(self.microsoft_outlook_refresh_token)
  136. _logger.info(
  137. 'Microsoft Outlook: fetch new access token. It expires in %i minutes',
  138. (self.microsoft_outlook_access_token_expiration - now_timestamp) // 60)
  139. else:
  140. _logger.info(
  141. 'Microsoft Outlook: reuse existing access token. It expires in %i minutes',
  142. (self.microsoft_outlook_access_token_expiration - now_timestamp) // 60)
  143. return 'user=%s\1auth=Bearer %s\1\1' % (login, self.microsoft_outlook_access_token)
  144. def _get_outlook_csrf_token(self):
  145. """Generate a CSRF token that will be verified in `microsoft_outlook_callback`.
  146. This will prevent a malicious person to make an admin user disconnect the mail servers.
  147. """
  148. self.ensure_one()
  149. _logger.info('Microsoft Outlook: generate CSRF token for %s #%i', self._name, self.id)
  150. return hmac(
  151. env=self.env(su=True),
  152. scope='microsoft_outlook_oauth',
  153. message=(self._name, self.id),
  154. )
  155. @api.model
  156. def _get_microsoft_endpoint(self):
  157. return self.env["ir.config_parameter"].sudo().get_param(
  158. 'microsoft_outlook.endpoint',
  159. 'https://login.microsoftonline.com/common/oauth2/v2.0/',
  160. )