Files
odoo_source/addons/microsoft_outlook/controllers/main.py
T
std-odoo bcdf9e12a8 [ADD] fetchmail_outlook, microsoft_outlook: add OAuth authentication
Purpose
=======
As it has been done for Gmail, we want to add the OAuth authentication
for the incoming / outgoing mail server.

Specifications
==============
The user has to create a project on Outlook and fill the credentials
in Odoo. Once it's done, he can create an incoming / outgoing mail
server.

For the authentication flow is a bit different from Gmail. For Outlook
the user is redirected to Outlook where he'll accept the permission.
Once it's done, he's redirected again to the mail server form view and
the tokens are automatically added on the mail server.

Technical
=========
There are 3 tokens used for the OAuth authentication.
1. The authentication code. This one is only used to get the refresh
   token and the first access token. It's the code returned by the user
   browser during the authentication flow.
2. The refresh token. This one will never change once the user is
   authenticated. This token is used to get new access token once they
   are expired.
3. The access token. Those tokens have an expiration date (1 hour) and
   are used in the XOAUTH2 protocol to authenticate the IMAP / SMTP
   connection.

During the authentication process, we can also give a state that will
be returned by the user browser. This state contains
1. The model and the ID of the mail server (as the same mixin manage
   both incoming and outgoing mail server)
2. A CSRF token which sign those values and is verified once the browser
   redirect the user to the Odoo database. This is useful so a malicious
   user can not send a link to an admin to disconnect the mail server.

Task-2751996

X-original-commit: 18dad5b13b0af81ef2089fc039b3a866a2895a53
Part-of: odoo/odoo#87731
2022-04-01 13:37:16 +02:00

77 lines
2.8 KiB
Python

# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import json
import logging
import werkzeug
from werkzeug.exceptions import Forbidden
from odoo import http
from odoo.exceptions import UserError
from odoo.http import request
from odoo.tools import consteq
_logger = logging.getLogger(__name__)
class MicrosoftOutlookController(http.Controller):
@http.route('/microsoft_outlook/confirm', type='http', auth='user')
def microsoft_outlook_callback(self, code=None, state=None, error_description=None, **kwargs):
"""Callback URL during the OAuth process.
Outlook redirects the user browser to this endpoint with the authorization code.
We will fetch the refresh token and the access token thanks to this authorization
code and save those values on the given mail server.
"""
if not request.env.user.has_group('base.group_system'):
_logger.error('Microsoft Outlook: Non system user try to link an Outlook account.')
raise Forbidden()
try:
state = json.loads(state)
model_name = state['model']
rec_id = state['id']
csrf_token = state['csrf_token']
except Exception:
_logger.error('Microsoft Outlook: Wrong state value %r.', state)
raise Forbidden()
if error_description:
return request.render('microsoft_outlook.microsoft_outlook_oauth_error', {
'error': error_description,
'model_name': model_name,
'rec_id': rec_id,
})
model = request.env[model_name]
if not issubclass(type(model), request.env.registry['microsoft.outlook.mixin']):
# The model must inherits from the "microsoft.outlook.mixin" mixin
raise Forbidden()
record = model.browse(rec_id).exists()
if not record:
raise Forbidden()
if not csrf_token or not consteq(csrf_token, record._get_outlook_csrf_token()):
_logger.error('Microsoft Outlook: Wrong CSRF token during Outlook authentication.')
raise Forbidden()
try:
refresh_token, access_token, expiration = record._fetch_outlook_refresh_token(code)
except UserError as e:
return request.render('microsoft_outlook.microsoft_outlook_oauth_error', {
'error': str(e.name),
'model_name': model_name,
'rec_id': rec_id,
})
record.write({
'microsoft_outlook_refresh_token': refresh_token,
'microsoft_outlook_access_token': access_token,
'microsoft_outlook_access_token_expiration': expiration,
})
return werkzeug.utils.redirect(f'/web?#id={rec_id}&model={model_name}&view_type=form', 303)