main.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. # -*- coding: utf-8 -*-
  2. # Part of Odoo. See LICENSE file for full copyright and licensing details.
  3. import json
  4. import logging
  5. from werkzeug.exceptions import Forbidden
  6. from werkzeug.urls import url_encode
  7. from odoo import _, http
  8. from odoo.exceptions import UserError
  9. from odoo.http import request
  10. from odoo.tools import consteq
  11. _logger = logging.getLogger(__name__)
  12. class GoogleGmailController(http.Controller):
  13. @http.route('/google_gmail/confirm', type='http', auth='user')
  14. def google_gmail_callback(self, code=None, state=None, error=None, **kwargs):
  15. """Callback URL during the OAuth process.
  16. Gmail redirects the user browser to this endpoint with the authorization code.
  17. We will fetch the refresh token and the access token thanks to this authorization
  18. code and save those values on the given mail server.
  19. """
  20. if not request.env.user.has_group('base.group_system'):
  21. _logger.error('Google Gmail: non-system user trying to link an Gmail account.')
  22. raise Forbidden()
  23. if error:
  24. return _('An error occur during the authentication process.')
  25. try:
  26. state = json.loads(state)
  27. model_name = state['model']
  28. rec_id = state['id']
  29. csrf_token = state['csrf_token']
  30. except Exception:
  31. _logger.error('Google Gmail: Wrong state value %r.', state)
  32. raise Forbidden()
  33. model = request.env[model_name]
  34. if not issubclass(type(model), request.env.registry['google.gmail.mixin']):
  35. # The model must inherits from the "google.gmail.mixin" mixin
  36. raise Forbidden()
  37. record = model.browse(rec_id).exists()
  38. if not record:
  39. raise Forbidden()
  40. if not csrf_token or not consteq(csrf_token, record._get_gmail_csrf_token()):
  41. _logger.error('Google Gmail: Wrong CSRF token during Gmail authentication.')
  42. raise Forbidden()
  43. try:
  44. refresh_token, access_token, expiration = record._fetch_gmail_refresh_token(code)
  45. except UserError:
  46. return _('An error occur during the authentication process.')
  47. record.write({
  48. 'google_gmail_access_token': access_token,
  49. 'google_gmail_access_token_expiration': expiration,
  50. 'google_gmail_authorization_code': code,
  51. 'google_gmail_refresh_token': refresh_token,
  52. })
  53. url_params = {
  54. 'id': rec_id,
  55. 'model': model_name,
  56. 'view_type': 'form'
  57. }
  58. url = '/web?#' + url_encode(url_params)
  59. return request.redirect(url)