Skip to content

Commit

Permalink
fix session login for non admin users
Browse files Browse the repository at this point in the history
  • Loading branch information
luffah committed May 24, 2021
1 parent d5589e6 commit 7dacbec
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 14 deletions.
45 changes: 32 additions & 13 deletions src/nextcloud/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
import requests
from .compat import encode_requests_password

import logging
_logger = logging.getLogger(__name__)


class NextCloudConnectionError(Exception):
""" A connection error occurred """
Expand Down Expand Up @@ -31,7 +34,7 @@ def __init__(self, url=None, user=None, password=None, auth=None, session_kwargs
self.auth = None
self.user = None
self._set_credentials(user, password, auth)
self.url = url
self.url = url.rstrip('/')
self._session_kwargs = session_kwargs or {}

def _set_credentials(self, user, password, auth):
Expand All @@ -41,12 +44,11 @@ def _set_credentials(self, user, password, auth):
self.user = user
else:
if isinstance(self.auth, tuple):
(self.user, password) = self.auth
self.auth = None
self.user = self.auth[0]
else:
if isinstance(self.auth, requests.auth.AuthBase):
self.user = self.auth.username
if not self.auth:
if not self.auth and (self.user and password):
self.auth = (self.user, encode_requests_password(password))

def request(self, method, url, **kwargs):
Expand Down Expand Up @@ -75,18 +77,35 @@ def login(self, user=None, password=None, auth=None, client=None):
self._set_credentials(user, password, auth)
self.session.auth = self.auth
if client:
try:
resp = client.with_attr(json_output=True).get_user()
if not resp.is_ok:
raise NextCloudLoginError(
'Failed to login to NextCloud', self.url, resp)
except requests.exceptions.SSLError as e:
self.logout()
raise e
except Exception as e:
self._check_session(client.with_attr(json_output=True), retry=3)


def _check_session(self, client=None, retry=None):
def _clear():
if self.session:
self.logout()

def _raise(e):
if retry:
_logger.warning('Retry session check (%s)', self.url)
return self._check_session(client, retry=retry - 1)
else:
_clear()
raise e

try:
resp = client.get_user()
if not resp.is_ok:
_raise(NextCloudLoginError(
'Failed to login to NextCloud', self.url, resp))
except requests.exceptions.SSLError as e:
_raise(e)
except NextCloudConnectionError as e:
_raise(e)
except Exception as e:
_clear()
raise e

def logout(self):
"""Log out the authenticated user and close the session.
Expand Down
2 changes: 1 addition & 1 deletion test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ case $1 in
NEXTCLOUD_ADMIN_PASSWORD=$NEXTCLOUD_ADMIN_PASSWORD \
NEXTCLOUD_ADMIN_USER=$NEXTCLOUD_ADMIN_USER \
NEXTCLOUD_VERSION=$NEXTCLOUD_VERSION \
pytest ..
pytest .
;;
*)
_usage
Expand Down

0 comments on commit 7dacbec

Please sign in to comment.