Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,26 @@ Changelog
---------


3.0.x (unreleased)
~~~~~~~~~~~~~~~~~~

* Add argument ``session_id`` to :class:`Client` and :meth:`Client.login`
to reuse an authenticated browser session, with its ``session_id``
cookie. It is useful when password login is disabled, for example with
OAuth sign-in. Command line option ``--session-id``.

* Reuse the Webclient session of each user, when switching user or
environment, instead of authenticating again. When switching database,
the previous session is not terminated anymore.

* :meth:`Env.session_destroy` terminates the session of its environment,
instead of the current session.

* The Superuser environment reuses its session. When this session is
terminated, it raises an error, instead of switching another session to
Superuser. Call :meth:`Env.sudo` again.


3.0.6 (2026-11-18)
~~~~~~~~~~~~~~~~~~

Expand Down
11 changes: 11 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,17 @@ Connect to the Odoo server::
~$ odooly --env devel


When password login is disabled (e.g. OAuth sign-in), login in the browser
and reuse the value of its ``session_id`` cookie (in the browser developer
tools, under *Application > Cookies* or *Storage > Cookies*)::

~$ odooly --env devel --session-id 0123456789abcdef

The browser session is shared: Odooly does not log out, unless
``env.session_destroy()`` is called. Note that ``env.sudo()`` turns
the browser session into a Superuser session, until it is terminated.


This is a sample session::

>>> env['res.users']
Expand Down
8 changes: 8 additions & 0 deletions docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ Odooly - client for Odoo

The Odooly library communicates with any `Odoo server`_ using the Webclient API.
If an ``api_key`` is configured, it will use the JSON-2 endpoint with Odoo 19.
If a ``session_id`` is provided, it will reuse this browser session (e.g. OAuth sign-in).
It can also connect through the `deprecated external RPC interface`_ (JSON-RPC).

It provides both a :ref:`fully featured low-level API <client-and-services>`,
Expand Down Expand Up @@ -50,6 +51,13 @@ Authentication methods per Odoo version, and per API:
example ``/web/webclient/version_info``. The ``/web/database/*``
endpoints are public, although they require the Master password as argument.

.. note:: As an alternative to Login, the Webclient API accepts the ``session_id``
cookie of a browser session, with :meth:`Client.login` or the
``--session-id`` command line option. It is useful when password login is
disabled, for example with OAuth sign-in. The session is shared: Odooly
does not log out, unless :meth:`Env.session_destroy` is called.
:meth:`Env.sudo` turns the browser session into a Superuser session.


Contents:

Expand Down
88 changes: 80 additions & 8 deletions odooly/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,17 +34,20 @@ class Client:
The `db` is the name of the database and the `user` should exist in the
table ``res.users``. If the `password` is not provided, it will be
asked on login.

As an alternative, the `session_id` of an authenticated Webclient
session can be provided.
"""
_use_call_button = False
_printer = None

def __init__(self, server, db=None, user=None, password=None, api_key=None):
def __init__(self, server, db=None, user=None, password=None, api_key=None, session_id=None):
self._http = HTTPSession()
self._session_uid = None
self._session_uid = self._session_info = None
self._set_services(server, db)
self.env = Env(self)
if user: # Try to login
self.login(user, password=password, api_key=api_key, database=db)
if user or session_id: # Try to login
self.login(user, password=password, api_key=api_key, database=db, session_id=session_id)

def _set_services(self, server, db):
if isinstance(server, list):
Expand Down Expand Up @@ -153,6 +156,37 @@ def dispatch_web(method, params):
def __repr__(self):
return f"<Client '{self._server}?db={self.env.db_name or ''}'>"

def _set_session(self, session_info, session_id=None):
"""Set the ``session_id`` HTTP cookie and the uid of the current session."""
self._http.set_cookie(self._server, 'session_id', session_id)
self._session_uid = session_info and session_info['uid']
self._session_info = session_info

def _get_session_id(self):
"""Return the ``session_id`` HTTP cookie of the current session."""
return self._http.get_cookie(self._server, 'session_id')

def _load_session(self, session_id):
"""Attach an authenticated Webclient session, and return its info.

The `session_id` is the value of the ``session_id`` cookie.
Return None if the session is invalid or expired.
"""
if not self.web:
return
if self._session_info and session_id == self._get_session_id():
session_info = self._session_info
self._session_info = None
return session_info
self._http.set_cookie(self._server, 'session_id', session_id)
try:
session_info = self.web_session.get_session_info()
except ServerError: # odoo.http.SessionExpiredException
self._set_session(None)
return
self._set_session(session_info, session_id)
return session_info

def _authenticate(self, db, login, password, api_key):
if api_key and not password and self.version_info >= 19.0:
json2_api = Json2(self, db, api_key)
Expand All @@ -165,6 +199,7 @@ def _authenticate(self, db, login, password, api_key):
return info

def _authenticate_session(self, db, login, password):
self._set_session(None) # Do not authenticate on the shared session
info = {'uid': None}
try:
if db:
Expand Down Expand Up @@ -210,20 +245,53 @@ def _authenticate_web(self, **kw):
def _authenticate_system(self):
__, session_info = self._request_parse('/web/become')
self._session_uid = session_info.get('uid')
self._session_info = None # The session has changed
if self._session_uid != 1:
raise Error("Cannot become Superuser")
return session_info

def _authenticate_rpc(self, db, uid, login, password):
# The password is asked by Env._check_user_password, which caches it
if not uid:
uid = self.common.login(db, login, password)
session_info = {'uid': uid}
if uid:
args = db, uid, password, 'res.users', 'context_get', ()
session_info['user_context'] = self._object.execute_kw(*args)
return session_info

def _select_database(self, db_list):
return db_list[0] if len(db_list) == 1 else None

def login(self, user, password=None, database=None, api_key=None):
def login(self, user, password=None, database=None, api_key=None, session_id=None):
"""Switch `user` and (optionally) `database`.

If the `password` is not available, it will be asked.

As an alternative, the `session_id` of an authenticated Webclient
session can be provided: it is the value of the ``session_id``
cookie of a browser session. Use it when the password login is
disabled, for example when the user signs in with OAuth.
The session is shared with the browser: Odooly does not authenticate
again on this session, and it does not log out, unless
:meth:`Env.session_destroy` is called. Note that :meth:`Env.sudo`
turns the browser session into a Superuser session.
The `user` and the `database` are optional: if provided, they must
match the session.
"""
env = self.env
if not env.db_name or (database and env.db_name != database):
session_info = None
if session_id: # Reuse a Webclient session
if not (session_info := self._load_session(session_id)):
raise Error("Error: Invalid or expired session")
if database and database != session_info['db']:
self._set_session(None)
raise Error(f"Error: Session is bound to database {session_info['db']!r}")
if user and user != session_info['username']:
self._set_session(None)
raise Error(f"Error: Session is bound to user {session_info['username']!r}")
(user, database) = (session_info['username'], session_info['db'])
if not session_id and (not env.db_name or (database and env.db_name != database)):
try:
dbs = self.database.list()
except Exception:
Expand All @@ -235,9 +303,13 @@ def login(self, user, password=None, database=None, api_key=None):
if dbs and database not in dbs:
raise Error(f"Database {database!r} does not exist: {dbs}")
if database and env.db_name != database:
if self._session_uid:
env.session_destroy()
if env.db_name and self._session_uid and not session_info:
self._set_session(None) # Do not reuse the session on another database
env = Env(self, database)
if session_info:
# Saved like any other session: Env._check_user_password reuses it
auth_cache = env._cache_get('auth', dict)
auth_cache[user] = (session_info['uid'], None, session_id)
try:
self.env = env(user=user, password=password, api_key=api_key)
except Exception:
Expand Down
110 changes: 85 additions & 25 deletions odooly/environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,20 +97,56 @@ def __bool__(self):
def __repr__(self):
return f"<Env '{self.user.login if self.uid else ''}@{self.db_name}'>"

@classmethod
def _ask_password(cls, user):
return getpass(f"Password for '{color_bold(user)}': ")

def _reuse_session(self, login, session_id, password=None):
"""Attach the session `session_id`, if it is still valid for `login`."""
info = self.client._load_session(session_id)
if info and (
info['username'] != login or
(self.db_name and info['db'] != self.db_name)
):
# The session has changed, e.g. with /web/become
self.client._set_session(None)
if info['username'] == SYSTEM_USER and not password:
# A browser session cannot be restored without a new sign-in
raise Error(f"Error: Session of {login!r} is now Superuser. "
"Log out with session_destroy()")
info = None
return info

def _check_user_password(self, user, password, api_key):
if self.client._object and not self.db_name:
raise Error('Error: Not connected')
assert isinstance(user, str) and user
if user == SYSTEM_USER and self.uid and not password:
info = self.client._authenticate_system()
return info['uid'], password, info
# Read from cache
auth_cache = self._cache_get('auth', dict)
(uid, pwcache) = auth_cache.get(user) or (None, None)
(uid, pwcache, session_id) = auth_cache.get(user) or (None, None, None)
password = password or pwcache
if session_id:
# Saved session: attach again, if it is still valid
if session_info := self._reuse_session(user, session_id, password):
auth_cache[user] = (session_info['uid'], password, session_id)
return session_info['uid'], password, session_info
if not password and user != SYSTEM_USER:
print(f"Session expired for {user!r}")
if user == SYSTEM_USER and self.uid and not password:
# Become Superuser from the session of this environment
self._ensure_session()
session_id = self.client._get_session_id()
info = self.client._authenticate_system()
if session_id:
# Cache the Superuser session, for reuse and session_destroy()
auth_cache[SYSTEM_USER] = (info['uid'], None, session_id)
(__, pw, sid) = auth_cache.get(self.user.login) or (None, None, None)
if sid == session_id and not pw:
print("Session is now Superuser. To undo: env.session_destroy()")
return info['uid'], password, info
# Ask for password
if not password and not api_key:
password = getpass(f"Password for '{color_bold(user)}': ")
password = self._ask_password(user)
if not self.client._object:
try: # Standard Web or JSON-2 authentication
info = self.client._authenticate(self.db_name, user, password, api_key)
Expand All @@ -120,11 +156,8 @@ def _check_user_password(self, user, password, api_key):
raise Error('Error: Database does not exist')
raise
else: # Login through RPC Service (deprecated)
if not uid:
uid = self.client.common.login(self.db_name, user, api_key or password)
if uid:
args = self.db_name, uid, api_key or password, 'res.users', 'context_get', ()
info = {'uid': uid, 'user_context': self.client._object.execute_kw(*args)}
info = self.client._authenticate_rpc(self.db_name, uid, user, api_key or password)
uid = info['uid']
if not uid: # Failed
if user in auth_cache:
del auth_cache[user]
Expand All @@ -138,8 +171,10 @@ def _check_user_password(self, user, password, api_key):
if not self.uid:
# Cache the unauthenticated Env and the client
self._cache_set(Env, self)
# Update credentials in cache
auth_cache[user] = uid, password
# Update credentials in cache, with the Webclient session if any
# (after JSON-2 or JSON-RPC login, the cookie can belong to another user)
session_id = self.client._get_session_id() if uid == self.client._session_uid else None
auth_cache[user] = uid, password, session_id
return uid, password, info

def set_api_key(self, api_key, store=True):
Expand Down Expand Up @@ -282,7 +317,7 @@ def _identitycheck(self, result):
result = None
while not result:
try:
password = password or getpass(f"Password for '{color_bold(self.user.login)}': ")
password = password or self._ask_password(self.user.login)
except (KeyboardInterrupt, EOFError):
print()
raise Error("Security Control - FAILED")
Expand All @@ -306,11 +341,14 @@ def _identitycheck(self, result):

def _ensure_session(self):
if self.uid != self.client._session_uid:
password = self._cache_get('auth')[self.user.login][1]
auth_cache = self._cache_get('auth')
(__, password, session_id) = auth_cache.get(self.user.login) or (None, None, None)
if self.user.login == SYSTEM_USER and not password:
self.client._authenticate_system()
if not (session_id and self._reuse_session(SYSTEM_USER, session_id)):
self.client._set_session(None)
raise Error("Error: Superuser session is terminated")
else:
self.session_authenticate(password=password)
self.session_authenticate(password=password, session_id=session_id)
return self

def _call_kw(self, model, method, args, kw=None):
Expand Down Expand Up @@ -548,16 +586,25 @@ def upgrade_cancel(self):
"""Press button ``Cancel Upgrade/Install/Uninstall``."""
return self._upgrade((), button='cancel', quiet=True)

def session_authenticate(self, login=None, password=None):
def session_authenticate(self, login=None, password=None, session_id=None):
"""Create a Webclient session for current user."""
if not login:
login = self.user.login
params = {
'db': self.db_name,
'login': login,
'password': password or getpass(f"Password for '{color_bold(login)}': "),
}
self.session_info = self.client._authenticate_session(**params)
# Reuse the session, if it is still valid
info = session_id and self._reuse_session(login, session_id, password)
if not info:
params = {
'db': self.db_name,
'login': login,
'password': password or self._ask_password(login),
}
info = self.client._authenticate_session(**params)
# Update the session in cache
auth_cache = self._cache_get('auth', dict)
if info.get('uid') and login in auth_cache:
(uid, pw) = auth_cache[login][:2]
auth_cache[login] = (uid, pw, self.client._get_session_id())
self.session_info = info
# When database name is discovered, copy cached data
if (
not self.db_name and
Expand All @@ -572,14 +619,27 @@ def session_authenticate(self, login=None, password=None):
print(f'Session authenticated for {login!r}' if self.session_info['uid'] else 'Failed')

def session_destroy(self):
"""Terminate current Webclient session."""
self.client._session_uid = None
"""Terminate the Webclient session of this environment.

A browser session is terminated too: the browser is logged out.
"""
auth = self.uid and self._cache_get('auth', dict).get(self.user.login)
session_id = auth and auth[2]
if session_id:
if session_id != self.client._get_session_id():
# Attach the session of this environment, even if it changed (/web/become)
if not self.client._load_session(session_id):
return # Already terminated
elif self.uid != self.client._session_uid:
return # The current session belongs to another environment
try:
return self.client.web_session.destroy()
except ServerError as exc:
# Ignore: odoo.http.SessionExpiredException
if exc.args[0]['code'] != 100:
raise
finally:
self.client._set_session(None)

def generate_api_key(self, expiration_date=DEFAULT):
"""Generate an API Key and configure environment to use it.
Expand Down
Loading