|
| 1 | +"""Login flow v2 API wrapper.""" |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import json |
| 5 | +import time |
| 6 | +from dataclasses import dataclass |
| 7 | + |
| 8 | +import httpx |
| 9 | + |
| 10 | +from ._exceptions import check_error |
| 11 | +from ._session import AsyncNcSession, NcSession |
| 12 | + |
| 13 | +MAX_TIMEOUT = 60 * 20 |
| 14 | + |
| 15 | + |
| 16 | +@dataclass |
| 17 | +class LoginFlow: |
| 18 | + """The Nextcloud Login flow v2 initialization response representation.""" |
| 19 | + |
| 20 | + def __init__(self, raw_data: dict) -> None: |
| 21 | + self.raw_data = raw_data |
| 22 | + |
| 23 | + @property |
| 24 | + def login(self) -> str: |
| 25 | + """The URL for user authorization. |
| 26 | +
|
| 27 | + Should be opened by the user in the default browser to authorize in Nextcloud. |
| 28 | + """ |
| 29 | + return self.raw_data["login"] |
| 30 | + |
| 31 | + @property |
| 32 | + def token(self) -> str: |
| 33 | + """Token for a polling for confirmation of user authorization.""" |
| 34 | + return self.raw_data["poll"]["token"] |
| 35 | + |
| 36 | + @property |
| 37 | + def endpoint(self) -> str: |
| 38 | + """Endpoint for polling.""" |
| 39 | + return self.raw_data["poll"]["endpoint"] |
| 40 | + |
| 41 | + def __repr__(self) -> str: |
| 42 | + return f"<{self.__class__.__name__} login_url={self.login}>" |
| 43 | + |
| 44 | + |
| 45 | +@dataclass |
| 46 | +class Credentials: |
| 47 | + """The Nextcloud Login flow v2 response with app credentials representation.""" |
| 48 | + |
| 49 | + def __init__(self, raw_data: dict) -> None: |
| 50 | + self.raw_data = raw_data |
| 51 | + |
| 52 | + @property |
| 53 | + def server(self) -> str: |
| 54 | + """The address of Nextcloud to connect to. |
| 55 | +
|
| 56 | + The server may specify a protocol (http or https). If no protocol is specified https will be used. |
| 57 | + """ |
| 58 | + return self.raw_data["server"] |
| 59 | + |
| 60 | + @property |
| 61 | + def login_name(self) -> str: |
| 62 | + """The username for authenticating with Nextcloud.""" |
| 63 | + return self.raw_data["loginName"] |
| 64 | + |
| 65 | + @property |
| 66 | + def app_password(self) -> str: |
| 67 | + """The application password generated for authenticating with Nextcloud.""" |
| 68 | + return self.raw_data["appPassword"] |
| 69 | + |
| 70 | + def __repr__(self) -> str: |
| 71 | + return f"<{self.__class__.__name__} login={self.login_name} app_password={self.app_password}>" |
| 72 | + |
| 73 | + |
| 74 | +class _LoginFlowV2API: |
| 75 | + """Class implementing Nextcloud Login flow v2.""" |
| 76 | + |
| 77 | + _ep_init: str = "/index.php/login/v2" |
| 78 | + _ep_poll: str = "/index.php/login/v2/poll" |
| 79 | + |
| 80 | + def __init__(self, session: NcSession) -> None: |
| 81 | + self._session = session |
| 82 | + |
| 83 | + def init(self, user_agent: str = "nc_py_api") -> LoginFlow: |
| 84 | + """Init a Login flow v2. |
| 85 | +
|
| 86 | + :param user_agent: Application name. Application password will be associated with this name. |
| 87 | + """ |
| 88 | + r = self._session.adapter.post(self._ep_init, headers={"user-agent": user_agent}) |
| 89 | + return LoginFlow(_res_to_json(r)) |
| 90 | + |
| 91 | + def poll(self, token: str, timeout: int = MAX_TIMEOUT, step: int = 1, overwrite_auth: bool = True) -> Credentials: |
| 92 | + """Poll the Login flow v2 credentials. |
| 93 | +
|
| 94 | + :param token: Token for a polling for confirmation of user authorization. |
| 95 | + :param timeout: Maximum time to wait for polling in seconds, defaults to MAX_TIMEOUT. |
| 96 | + :param step: Interval for polling in seconds, defaults to 1. |
| 97 | + :param overwrite_auth: If True current session will be overwritten with new credentials, defaults to True. |
| 98 | + :raises ValueError: If timeout more than 20 minutes. |
| 99 | + """ |
| 100 | + if timeout > MAX_TIMEOUT: |
| 101 | + msg = "Timeout can't be more than 20 minutes." |
| 102 | + raise ValueError(msg) |
| 103 | + for _ in range(timeout // step): |
| 104 | + r = self._session.adapter.post(self._ep_poll, data={"token": token}) |
| 105 | + if r.status_code == 200: |
| 106 | + break |
| 107 | + time.sleep(step) |
| 108 | + r_model = Credentials(_res_to_json(r)) |
| 109 | + if overwrite_auth: |
| 110 | + self._session.cfg.auth = (r_model.login_name, r_model.app_password) |
| 111 | + self._session.init_adapter(restart=True) |
| 112 | + self._session.init_adapter_dav(restart=True) |
| 113 | + return r_model |
| 114 | + |
| 115 | + |
| 116 | +class _AsyncLoginFlowV2API: |
| 117 | + """Class implementing Async Nextcloud Login flow v2.""" |
| 118 | + |
| 119 | + _ep_init: str = "/index.php/login/v2" |
| 120 | + _ep_poll: str = "/index.php/login/v2/poll" |
| 121 | + |
| 122 | + def __init__(self, session: AsyncNcSession) -> None: |
| 123 | + self._session = session |
| 124 | + |
| 125 | + async def init(self, user_agent: str = "nc_py_api") -> LoginFlow: |
| 126 | + """Init a Login flow v2. |
| 127 | +
|
| 128 | + :param user_agent: Application name. Application password will be associated with this name. |
| 129 | + """ |
| 130 | + r = await self._session.adapter.post(self._ep_init, headers={"user-agent": user_agent}) |
| 131 | + return LoginFlow(_res_to_json(r)) |
| 132 | + |
| 133 | + async def poll( |
| 134 | + self, token: str, timeout: int = MAX_TIMEOUT, step: int = 1, overwrite_auth: bool = True |
| 135 | + ) -> Credentials: |
| 136 | + """Poll the Login flow v2 credentials. |
| 137 | +
|
| 138 | + :param token: Token for a polling for confirmation of user authorization. |
| 139 | + :param timeout: Maximum time to wait for polling in seconds, defaults to MAX_TIMEOUT. |
| 140 | + :param step: Interval for polling in seconds, defaults to 1. |
| 141 | + :param overwrite_auth: If True current session will be overwritten with new credentials, defaults to True. |
| 142 | + :raises ValueError: If timeout more than 20 minutes. |
| 143 | + """ |
| 144 | + if timeout > MAX_TIMEOUT: |
| 145 | + raise ValueError("Timeout can't be more than 20 minutes.") |
| 146 | + for _ in range(timeout // step): |
| 147 | + r = await self._session.adapter.post(self._ep_poll, data={"token": token}) |
| 148 | + if r.status_code == 200: |
| 149 | + break |
| 150 | + await asyncio.sleep(step) |
| 151 | + r_model = Credentials(_res_to_json(r)) |
| 152 | + if overwrite_auth: |
| 153 | + self._session.cfg.auth = (r_model.login_name, r_model.app_password) |
| 154 | + self._session.init_adapter(restart=True) |
| 155 | + self._session.init_adapter_dav(restart=True) |
| 156 | + return r_model |
| 157 | + |
| 158 | + |
| 159 | +def _res_to_json(response: httpx.Response) -> dict: |
| 160 | + check_error(response) |
| 161 | + return json.loads(response.text) |
0 commit comments