Skip to content

Commit 55e16b6

Browse files
committed
feat: add session-aware re-login on token renewal failure
- Store cred_mngr and iri on WtSite instance for later re-login - Add WtSite._relogin() method to re-authenticate when session expires - Update try_and_renew_token decorators (WtSite and WtPage) to attempt full re-login when CSRF token refresh alone fails - Update WtPage.edit() retry loop to fall back to re-login on token refresh failure
1 parent 8f99363 commit 55e16b6

1 file changed

Lines changed: 62 additions & 13 deletions

File tree

‎src/osw/wtsite.py‎

Lines changed: 62 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,10 @@ def __init__(self, config: Union[WtSiteConfig, WtSiteLegacyConfig]):
9090

9191
scheme = "https"
9292

93+
# Store credentials for potential re-login on session timeout
94+
self._cred_mngr = None
95+
self._iri = None
96+
9397
if isinstance(config, WtSite.WtSiteLegacyConfig):
9498
self._site: mwclient.Site = config.site
9599
self._cred_mngr = None
@@ -105,6 +109,7 @@ def __init__(self, config: Union[WtSiteConfig, WtSiteLegacyConfig]):
105109
if "//" in config.iri:
106110
scheme = config.iri.split("://")[0]
107111
config.iri = config.iri.split("://")[1]
112+
self._iri = config.iri
108113
site_args = [config.iri]
109114
# increase pool_maxsize to improve performance with many requests to the same server
110115
# see: https://stackoverflow.com/questions/18466079/change-the-connection-pool-size-for-pythons-requests-module-when-in-threading # noqa
@@ -150,6 +155,31 @@ def __init__(self, config: Union[WtSiteConfig, WtSiteLegacyConfig]):
150155
self._page_cache = {}
151156
self._cache_enabled = False
152157

158+
def _relogin(self):
159+
"""Re-login to the wiki site using stored credentials.
160+
161+
This is used when the session has expired and a CSRF token refresh
162+
alone is not sufficient to restore the connection.
163+
"""
164+
if self._cred_mngr is None or self._iri is None:
165+
raise RuntimeError(
166+
"Cannot re-login: no credentials stored. "
167+
"This WtSite was created from a legacy config."
168+
)
169+
cred = self._cred_mngr.get_credential(
170+
CredentialManager.CredentialConfig(
171+
iri=self._iri,
172+
fallback=CredentialManager.CredentialFallback.none,
173+
)
174+
)
175+
if isinstance(cred, CredentialManager.UserPwdCredential):
176+
self._site.login(username=cred.username, password=cred.password)
177+
else:
178+
raise RuntimeError(
179+
"Re-login is only supported for username/password credentials."
180+
)
181+
del cred
182+
153183
@property
154184
def mw_site(self) -> mwclient.client.Site:
155185
"""Returns the mwclient.Site object of the WtSite instance"""
@@ -222,20 +252,26 @@ def from_credentials(
222252
return cls(WtSite.WtSiteLegacyConfig(site=site))
223253

224254
def try_and_renew_token(func):
225-
""" "Tries to execute the method call. If the auth token has expired already,
226-
the token is renewed and the method call is retried.
255+
"""Tries to execute the method call. If the auth token has expired already,
256+
the token is renewed and the method call is retried. If that also fails
257+
(e.g. because the session itself has expired), a full re-login is attempted.
227258
228-
This decorator should be used closest to to the funciton definition (before
259+
This decorator should be used closest to the function definition (before
229260
any other decorator).
230261
"""
231262

232263
def wrapper(self, *args, **kwargs):
233264
try:
234265
return func(self, *args, **kwargs)
235266
except mwclient.errors.APIError:
236-
# Refresh token for longer taking processes
237-
self._site.get_token("csrf", force=True)
238-
return func(self, *args, **kwargs)
267+
try:
268+
# First try: refresh the CSRF token
269+
self._site.get_token("csrf", force=True)
270+
return func(self, *args, **kwargs)
271+
except mwclient.errors.APIError:
272+
# Second try: full re-login (session may have expired)
273+
self._relogin()
274+
return func(self, *args, **kwargs)
239275

240276
return wrapper
241277

@@ -1358,19 +1394,25 @@ def init(self):
13581394

13591395
def try_and_renew_token(func):
13601396
"""Tries to execute the method call. If the auth token has expired already,
1361-
the token is renewed and the method call is retried.
1397+
the token is renewed and the method call is retried. If that also fails
1398+
(e.g. because the session itself has expired), a full re-login is attempted.
13621399
1363-
This decorator should be used closest to to the funciton definition (before
1400+
This decorator should be used closest to the function definition (before
13641401
any other decorator).
13651402
"""
13661403

13671404
def wrapper(self, *args, **kwargs):
13681405
try:
13691406
return func(self, *args, **kwargs)
13701407
except mwclient.errors.APIError:
1371-
# Refresh token for longer taking processes
1372-
self.wtSite._site.get_token("csrf", force=True)
1373-
return func(self, *args, **kwargs)
1408+
try:
1409+
# First try: refresh the CSRF token
1410+
self.wtSite._site.get_token("csrf", force=True)
1411+
return func(self, *args, **kwargs)
1412+
except mwclient.errors.APIError:
1413+
# Second try: full re-login (session may have expired)
1414+
self.wtSite._relogin()
1415+
return func(self, *args, **kwargs)
13741416

13751417
return wrapper
13761418

@@ -1691,8 +1733,15 @@ def edit(self, comment: str = None, mode="action-multislot", bot_edit: bool = Tr
16911733
if retry < max_retry:
16921734
retry += 1
16931735
print(f"Page edit failed: {e}. Retry ({retry}/{max_retry})")
1694-
# refresh token for longer running processes
1695-
self.wtSite._site.get_token("csrf", force=True)
1736+
try:
1737+
# refresh token for longer running processes
1738+
self.wtSite._site.get_token("csrf", force=True)
1739+
except Exception:
1740+
# token refresh failed, attempt full re-login
1741+
try:
1742+
self.wtSite._relogin()
1743+
except Exception:
1744+
pass # re-login failed, will retry anyway
16961745
sleep(5)
16971746

16981747
def _edit(

0 commit comments

Comments
 (0)