Skip to content

Client mode: LDAP user_id bug fix #148

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Oct 15, 2023
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
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ This release contains some breaking changes in `users`, `notifications` API.

### Added

- `__repr__` method added for most objects(previously it was only present for `FsNode`).
- `__repr__` method added for most objects(previously it was only present for `FsNode`). #147

### Changed

Expand All @@ -21,6 +21,7 @@ This release contains some breaking changes in `users`, `notifications` API.
### Fixed

- `users.get_details` with empty parameter in some cases was raised exception.
- ClientMode: in case when LDAP was used as user backend, user login differs from user_id and most API failed with 404. #148

## [0.3.1 - 2023-10-07]

Expand Down
38 changes: 30 additions & 8 deletions nc_py_api/_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,15 +134,15 @@ class NcSessionBasic(ABC):
adapter: Client
adapter_dav: Client
cfg: BasicConfig
user: str
custom_headers: dict
_capabilities: dict
response_headers: HttpxHeaders
_user: str
_capabilities: dict

@abstractmethod
def __init__(self, **kwargs):
self._capabilities = {}
self.user = kwargs.get("user", "")
self._user = kwargs.get("user", "")
self.custom_headers = kwargs.get("headers", {})
self.limits = Limits(max_keepalive_connections=20, max_connections=20, keepalive_expiry=60.0)
self.init_adapter()
Expand All @@ -168,22 +168,33 @@ def _get_stream(self, path_params: str, headers: dict, **kwargs) -> Iterator[Res
"GET", f"{self.cfg.endpoint}{path_params}", headers=headers, timeout=timeout, **kwargs
)

def request_json(
def request(
self,
method: str,
path: str,
params: Optional[dict] = None,
data: Optional[Union[bytes, str]] = None,
json: Optional[Union[dict, list]] = None,
**kwargs,
) -> dict:
):
method = method.upper()
if params is None:
params = {}
params.update({"format": "json"})
headers = kwargs.pop("headers", {})
data_bytes = self.__data_to_bytes(headers, data, json)
r = self._ocs(method, f"{quote(path)}?{urlencode(params, True)}", headers, data_bytes, not_parse=True)
return self._ocs(method, f"{quote(path)}?{urlencode(params, True)}", headers, data_bytes, not_parse=True)

def request_json(
self,
method: str,
path: str,
params: Optional[dict] = None,
data: Optional[Union[bytes, str]] = None,
json: Optional[Union[dict, list]] = None,
**kwargs,
) -> dict:
r = self.request(method, path, params, data, json, **kwargs)
return loads(r.text) if r.status_code != 304 else {}

def ocs(
Expand Down Expand Up @@ -319,6 +330,17 @@ def _create_adapter(self) -> Client:
def update_server_info(self) -> None:
self._capabilities = self.ocs(method="GET", path="/ocs/v1.php/cloud/capabilities")

@property
def user(self) -> str:
"""Current user ID. Can be different from the login name."""
if isinstance(self, NcSession) and not self._user: # do not trigger for NextcloudApp
self._user = self.ocs(method="GET", path="/ocs/v1.php/cloud/user")["id"]
return self._user

@user.setter
def user(self, value: str):
self._user = value

@property
def capabilities(self) -> dict:
if not self._capabilities:
Expand Down Expand Up @@ -360,7 +382,7 @@ class NcSession(NcSessionBasic):

def __init__(self, **kwargs):
self.cfg = Config(**kwargs)
super().__init__(user=self.cfg.auth[0])
super().__init__()

def _create_adapter(self) -> Client:
return Client(auth=self.cfg.auth, follow_redirects=True, limits=self.limits, verify=self.cfg.options.nc_cert)
Expand Down Expand Up @@ -401,7 +423,7 @@ def _create_adapter(self) -> Client:
return adapter

def sign_request(self, headers: dict) -> None:
headers["AUTHORIZATION-APP-API"] = b64encode(f"{self.user}:{self.cfg.app_secret}".encode("UTF=8"))
headers["AUTHORIZATION-APP-API"] = b64encode(f"{self._user}:{self.cfg.app_secret}".encode("UTF=8"))

def sign_check(self, request: Request) -> None:
headers = {
Expand Down
4 changes: 2 additions & 2 deletions nc_py_api/nextcloud.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ def __init__(self, **kwargs):

@property
def user(self) -> str:
"""Returns current user name."""
"""Returns current user ID."""
return self._session.user


Expand Down Expand Up @@ -184,7 +184,7 @@ def scope_allowed(self, scope: ApiScope) -> bool:

@property
def user(self) -> str:
"""Property containing the current username.
"""Property containing the current user ID.

*System Applications* can set it and impersonate the user. For normal applications, it is set automatically.
"""
Expand Down
10 changes: 5 additions & 5 deletions tests/actual_tests/user_status_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,14 +106,14 @@ def test_set_predefined(nc, clear_at):


@pytest.mark.require_nc(major=27)
def test_get_back_status_from_from_empty_user(nc):
orig_user = nc._session.user
nc._session.user = ""
def test_get_back_status_from_from_empty_user(nc_app):
orig_user = nc_app._session.user
nc_app._session.user = ""
try:
with pytest.raises(ValueError):
nc.user_status.get_backup_status("")
nc_app.user_status.get_backup_status("")
finally:
nc._session.user = orig_user
nc_app._session.user = orig_user


@pytest.mark.require_nc(major=27)
Expand Down