-
Notifications
You must be signed in to change notification settings - Fork 11
feat: Login flow v2 #255
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
feat: Login flow v2 #255
Changes from 6 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
fab61c2
Implement Login flow v2.
ce8fd90
Edit Login flow v2 docstrings and remove extra endpoint.
1f714d4
Merge branch 'main' into feat/loginflow_v2
bagoont c36f390
Merge branch 'cloud-py-api:main' into feat/loginflow_v2
bagoont 1e0bcb8
Add login flow v2 docs and edit tests.
b06862e
Added an exact check for the 404 error code for the login flow v2 pol…
b24157f
Edit _ep_poll in Login flow v2 and remove extra statuc code check.
60a092b
Edit _ep_poll in Login flow v2 and remove extra status code check.
2cba348
Merge branch 'feat/loginflow_v2' of https://github.com/blvdek/nc_py_a…
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
.. py:currentmodule:: nc_py_api.loginflow_v2 | ||
|
||
LoginFlow V2 | ||
============ | ||
|
||
Login flow v2 is an authorization process for the standard Nextcloud client that allows each client to have their own set of credentials. | ||
|
||
.. autoclass:: _LoginFlowV2API | ||
:inherited-members: | ||
:members: | ||
|
||
.. autoclass:: Credentials | ||
:inherited-members: | ||
:members: | ||
|
||
.. autoclass:: LoginFlow | ||
:inherited-members: | ||
:members: |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -23,3 +23,6 @@ Internal | |
.. autoclass:: NcSessionApp | ||
:members: | ||
:inherited-members: | ||
|
||
.. autoclass:: NcSession | ||
:members: |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -16,3 +16,4 @@ Reference | |
ActivityApp | ||
Notes | ||
Session | ||
LoginFlowV2 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,161 @@ | ||
"""Login flow v2 API wrapper.""" | ||
|
||
import asyncio | ||
import json | ||
import time | ||
from dataclasses import dataclass | ||
|
||
import httpx | ||
|
||
from ._exceptions import check_error | ||
from ._session import AsyncNcSession, NcSession | ||
|
||
MAX_TIMEOUT = 60 * 20 | ||
|
||
|
||
@dataclass | ||
class LoginFlow: | ||
"""The Nextcloud Login flow v2 initialization response representation.""" | ||
|
||
def __init__(self, raw_data: dict) -> None: | ||
self.raw_data = raw_data | ||
|
||
@property | ||
def login(self) -> str: | ||
"""The URL for user authorization. | ||
|
||
Should be opened by the user in the default browser to authorize in Nextcloud. | ||
""" | ||
return self.raw_data["login"] | ||
|
||
@property | ||
def token(self) -> str: | ||
"""Token for a polling for confirmation of user authorization.""" | ||
return self.raw_data["poll"]["token"] | ||
|
||
@property | ||
def endpoint(self) -> str: | ||
"""Endpoint for polling.""" | ||
return self.raw_data["poll"]["endpoint"] | ||
|
||
def __repr__(self) -> str: | ||
return f"<{self.__class__.__name__} login_url={self.login}>" | ||
|
||
|
||
@dataclass | ||
class Credentials: | ||
"""The Nextcloud Login flow v2 response with app credentials representation.""" | ||
|
||
def __init__(self, raw_data: dict) -> None: | ||
self.raw_data = raw_data | ||
|
||
@property | ||
def server(self) -> str: | ||
"""The address of Nextcloud to connect to. | ||
|
||
The server may specify a protocol (http or https). If no protocol is specified https will be used. | ||
""" | ||
return self.raw_data["server"] | ||
|
||
@property | ||
def login_name(self) -> str: | ||
"""The username for authenticating with Nextcloud.""" | ||
return self.raw_data["loginName"] | ||
|
||
@property | ||
def app_password(self) -> str: | ||
"""The application password generated for authenticating with Nextcloud.""" | ||
return self.raw_data["appPassword"] | ||
|
||
def __repr__(self) -> str: | ||
return f"<{self.__class__.__name__} login={self.login_name} app_password={self.app_password}>" | ||
|
||
|
||
class _LoginFlowV2API: | ||
"""Class implementing Nextcloud Login flow v2.""" | ||
|
||
_ep_init: str = "/index.php/login/v2" | ||
_ep_poll: str = "/login/v2/poll" | ||
|
||
def __init__(self, session: NcSession) -> None: | ||
self._session = session | ||
|
||
def init(self, user_agent: str = "nc_py_api") -> LoginFlow: | ||
"""Init a Login flow v2. | ||
|
||
:param user_agent: Application name. Application password will be associated with this name. | ||
""" | ||
r = self._session.adapter.post(self._ep_init, headers={"user-agent": user_agent}) | ||
return LoginFlow(_res_to_json(r)) | ||
|
||
def poll(self, token: str, timeout: int = MAX_TIMEOUT, step: int = 1, overwrite_auth: bool = True) -> Credentials: | ||
"""Poll the Login flow v2 credentials. | ||
|
||
:param token: Token for a polling for confirmation of user authorization. | ||
:param timeout: Maximum time to wait for polling in seconds, defaults to MAX_TIMEOUT. | ||
:param step: Interval for polling in seconds, defaults to 1. | ||
:param overwrite_auth: If True current session will be overwritten with new credentials, defaults to True. | ||
:raises ValueError: If timeout more than 20 minutes. | ||
""" | ||
if timeout > MAX_TIMEOUT: | ||
msg = "Timeout can't be more than 20 minutes." | ||
raise ValueError(msg) | ||
for _ in range(timeout // step): | ||
r = self._session.adapter.post(self._ep_poll, data={"token": token}) | ||
if r.status_code == 200: | ||
break | ||
time.sleep(step) | ||
r_model = Credentials(_res_to_json(r)) | ||
if overwrite_auth: | ||
self._session.cfg.auth = (r_model.login_name, r_model.app_password) | ||
self._session.init_adapter(restart=True) | ||
self._session.init_adapter_dav(restart=True) | ||
return r_model | ||
|
||
|
||
class _AsyncLoginFlowV2API: | ||
"""Class implementing Async Nextcloud Login flow v2.""" | ||
|
||
_ep_init: str = "/index.php/login/v2" | ||
_ep_poll: str = "/login/v2/poll" | ||
bigcat88 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
||
def __init__(self, session: AsyncNcSession) -> None: | ||
self._session = session | ||
|
||
async def init(self, user_agent: str = "nc_py_api") -> LoginFlow: | ||
"""Init a Login flow v2. | ||
|
||
:param user_agent: Application name. Application password will be associated with this name. | ||
""" | ||
r = await self._session.adapter.post(self._ep_init, headers={"user-agent": user_agent}) | ||
return LoginFlow(_res_to_json(r)) | ||
|
||
async def poll( | ||
self, token: str, timeout: int = MAX_TIMEOUT, step: int = 1, overwrite_auth: bool = True | ||
) -> Credentials: | ||
"""Poll the Login flow v2 credentials. | ||
|
||
:param token: Token for a polling for confirmation of user authorization. | ||
:param timeout: Maximum time to wait for polling in seconds, defaults to MAX_TIMEOUT. | ||
:param step: Interval for polling in seconds, defaults to 1. | ||
:param overwrite_auth: If True current session will be overwritten with new credentials, defaults to True. | ||
:raises ValueError: If timeout more than 20 minutes. | ||
""" | ||
if timeout > MAX_TIMEOUT: | ||
raise ValueError("Timeout can't be more than 20 minutes.") | ||
for _ in range(timeout // step): | ||
r = await self._session.adapter.post(self._ep_poll, data={"token": token}) | ||
if r.status_code == 200: | ||
break | ||
await asyncio.sleep(step) | ||
r_model = Credentials(_res_to_json(r)) | ||
if overwrite_auth: | ||
self._session.cfg.auth = (r_model.login_name, r_model.app_password) | ||
self._session.init_adapter(restart=True) | ||
self._session.init_adapter_dav(restart=True) | ||
return r_model | ||
|
||
|
||
def _res_to_json(response: httpx.Response) -> dict: | ||
check_error(response) | ||
return json.loads(response.text) if response.status_code != 304 else {} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
import pytest | ||
|
||
from nc_py_api import NextcloudException | ||
|
||
|
||
def test_init_poll(nc_client): | ||
lf = nc_client.loginflow_v2.init() | ||
assert isinstance(lf.endpoint, str) | ||
assert isinstance(lf.login, str) | ||
assert isinstance(lf.token, str) | ||
with pytest.raises(NextcloudException) as exc_info: | ||
nc_client.loginflow_v2.poll(lf.token, 1) | ||
assert exc_info.value.status_code == 404 | ||
|
||
|
||
@pytest.mark.asyncio(scope="session") | ||
async def test_init_poll_async(anc_client): | ||
lf = await anc_client.loginflow_v2.init() | ||
assert isinstance(lf.endpoint, str) | ||
assert isinstance(lf.login, str) | ||
assert isinstance(lf.token, str) | ||
with pytest.raises(NextcloudException) as exc_info: | ||
await anc_client.loginflow_v2.poll(lf.token, 1) | ||
assert exc_info.value.status_code == 404 |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.