This commit is the 12th commit of a comprehensive refactor of our HTTP framework. See odoo/odoo#78857 for complete historic, discussions and rationnals. The web module is twofold, on one side there are many controllers: /, /web, /web/login, /web/database/selector, /web/dataset/call_kw, etc, on the other side there is `session_info`: the method responsible to create the web client's environ. This module is kinda an exception as it is (with base) a server wide module. In the case of the HTTP framework, it means that the controllers of web are always accessible, i.e. going to / or /web/login will never return a 404 Not Found even if the user is not connected to a database. This is both a blessing and a curse. It is a blessing because the controllers are always accessible it means that a new users can freely access those routes. It is a curse because *any* user can access them, even user who don't have a session yet thus who are not connected to a database yet. From a developer standpoint, we have to put extra care to correct serve users with and without a database. An example is the /web/login route, the login/password pair is stored in a database, without database it is impossible to validate a user login but users can still access this route without db. To solve this problem, there is the `ensure_db` function. This function attempts to find a database using various sources (?db= query-string, session db, mono db) and to save it on the user session. In case no db is found, the user is redirected to the database selector. In a way, this function grants a database to the user in a seamingly experience. In a way, this function brings a welcome differentiation between `auth='none'` with a database and `auth='none'` without a database. Such differentiation only matters for the server wide modules as "regular" module controllers are only accessible via the ir.http routing map, i.e. it is not possible to declare a nodb controller outside of server wide modules. An important changement is the `session.authenticate` method, before it was possible to call the method when the cursor was not yet initialized, authenticate would open a cursor against the given database, setup a registry and an environment and ultimately save everything on the current request. Because the cursor is now greedily created, it is no more possible to update the request environment when authenticating on another database. PR: odoo#78857 Task: 2571224
125 lines
5.0 KiB
Python
125 lines
5.0 KiB
Python
# -*- coding: utf-8 -*-
|
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
|
|
|
import json
|
|
|
|
import requests
|
|
|
|
from odoo import api, fields, models
|
|
from odoo.exceptions import AccessDenied, UserError
|
|
from odoo.addons.auth_signup.models.res_users import SignupError
|
|
|
|
from odoo.addons import base
|
|
base.models.res_users.USER_PRIVATE_FIELDS.append('oauth_access_token')
|
|
|
|
class ResUsers(models.Model):
|
|
_inherit = 'res.users'
|
|
|
|
oauth_provider_id = fields.Many2one('auth.oauth.provider', string='OAuth Provider')
|
|
oauth_uid = fields.Char(string='OAuth User ID', help="Oauth Provider user_id", copy=False)
|
|
oauth_access_token = fields.Char(string='OAuth Access Token', readonly=True, copy=False)
|
|
|
|
_sql_constraints = [
|
|
('uniq_users_oauth_provider_oauth_uid', 'unique(oauth_provider_id, oauth_uid)', 'OAuth UID must be unique per provider'),
|
|
]
|
|
|
|
@api.model
|
|
def _auth_oauth_rpc(self, endpoint, access_token):
|
|
return requests.get(endpoint, params={'access_token': access_token}).json()
|
|
|
|
@api.model
|
|
def _auth_oauth_validate(self, provider, access_token):
|
|
""" return the validation data corresponding to the access token """
|
|
oauth_provider = self.env['auth.oauth.provider'].browse(provider)
|
|
validation = self._auth_oauth_rpc(oauth_provider.validation_endpoint, access_token)
|
|
if validation.get("error"):
|
|
raise Exception(validation['error'])
|
|
if oauth_provider.data_endpoint:
|
|
data = self._auth_oauth_rpc(oauth_provider.data_endpoint, access_token)
|
|
validation.update(data)
|
|
return validation
|
|
|
|
@api.model
|
|
def _generate_signup_values(self, provider, validation, params):
|
|
oauth_uid = validation['user_id']
|
|
email = validation.get('email', 'provider_%s_user_%s' % (provider, oauth_uid))
|
|
name = validation.get('name', email)
|
|
return {
|
|
'name': name,
|
|
'login': email,
|
|
'email': email,
|
|
'oauth_provider_id': provider,
|
|
'oauth_uid': oauth_uid,
|
|
'oauth_access_token': params['access_token'],
|
|
'active': True,
|
|
}
|
|
|
|
@api.model
|
|
def _auth_oauth_signin(self, provider, validation, params):
|
|
""" retrieve and sign in the user corresponding to provider and validated access token
|
|
:param provider: oauth provider id (int)
|
|
:param validation: result of validation of access token (dict)
|
|
:param params: oauth parameters (dict)
|
|
:return: user login (str)
|
|
:raise: AccessDenied if signin failed
|
|
|
|
This method can be overridden to add alternative signin methods.
|
|
"""
|
|
oauth_uid = validation['user_id']
|
|
try:
|
|
oauth_user = self.search([("oauth_uid", "=", oauth_uid), ('oauth_provider_id', '=', provider)])
|
|
if not oauth_user:
|
|
raise AccessDenied()
|
|
assert len(oauth_user) == 1
|
|
oauth_user.write({'oauth_access_token': params['access_token']})
|
|
return oauth_user.login
|
|
except AccessDenied as access_denied_exception:
|
|
if self.env.context.get('no_user_creation'):
|
|
return None
|
|
state = json.loads(params['state'])
|
|
token = state.get('t')
|
|
values = self._generate_signup_values(provider, validation, params)
|
|
try:
|
|
login, _ = self.signup(values, token)
|
|
return login
|
|
except (SignupError, UserError):
|
|
raise access_denied_exception
|
|
|
|
@api.model
|
|
def auth_oauth(self, provider, params):
|
|
# Advice by Google (to avoid Confused Deputy Problem)
|
|
# if validation.audience != OUR_CLIENT_ID:
|
|
# abort()
|
|
# else:
|
|
# continue with the process
|
|
access_token = params.get('access_token')
|
|
validation = self._auth_oauth_validate(provider, access_token)
|
|
# required check
|
|
if not validation.get('user_id'):
|
|
# Workaround: facebook does not send 'user_id' in Open Graph Api
|
|
if validation.get('id'):
|
|
validation['user_id'] = validation['id']
|
|
else:
|
|
raise AccessDenied()
|
|
|
|
# retrieve and sign in user
|
|
login = self._auth_oauth_signin(provider, validation, params)
|
|
if not login:
|
|
raise AccessDenied()
|
|
# return user credentials
|
|
return (self.env.cr.dbname, login, access_token)
|
|
|
|
def _check_credentials(self, password, env):
|
|
try:
|
|
return super(ResUsers, self)._check_credentials(password, env)
|
|
except AccessDenied:
|
|
passwd_allowed = env['interactive'] or not self.env.user._rpc_api_keys_only()
|
|
if passwd_allowed and self.env.user.active:
|
|
res = self.sudo().search([('id', '=', self.env.uid), ('oauth_access_token', '=', password)])
|
|
if res:
|
|
return
|
|
raise
|
|
|
|
def _get_session_token_fields(self):
|
|
return super(ResUsers, self)._get_session_token_fields() | {'oauth_access_token'}
|