From 29ad80248039b6881cd55fa9b9ae78620df436b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dan=20Michael=20O=2E=20Hegg=C3=B8?= <danmichaelo@gmail.com> Date: Sat, 29 Apr 2017 00:30:34 +0200 Subject: [PATCH] [#149] Fetch login token using the tokens module For MediaWiki >= 1.27, fetch login tokens from the tokens module using `action=query&meta=tokens`. --- mwclient/client.py | 4 +++- tests/test_client.py | 27 +++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/mwclient/client.py b/mwclient/client.py index 4f03903..e0816b1 100644 --- a/mwclient/client.py +++ b/mwclient/client.py @@ -482,6 +482,8 @@ class Site(object): 'lgname': self.credentials[0], 'lgpassword': self.credentials[1] } + if self.version[:2] >= (1, 27): + kwargs['lgtoken'] = self.get_token('login') if self.credentials[2]: kwargs['lgdomain'] = self.credentials[2] while True: @@ -502,7 +504,7 @@ class Site(object): if self.version[:2] >= (1, 24): # The 'csrf' (cross-site request forgery) token introduced in 1.24 replaces # the majority of older tokens, like edittoken and movetoken. - if type not in {'watch', 'patrol', 'rollback', 'userrights'}: + if type not in {'watch', 'patrol', 'rollback', 'userrights', 'login'}: type = 'csrf' if type not in self.tokens: diff --git a/tests/test_client.py b/tests/test_client.py index 4e4c328..caaa881 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -366,6 +366,33 @@ class TestClientApiMethods(TestCase): assert call_args[1] == mock.call('login', 'POST', lgname='myusername', lgpassword='mypassword') assert call_args[2] == mock.call('login', 'POST', lgname='myusername', lgpassword='mypassword', lgtoken=login_token) + def test_login_flow_2(self): + + login_token = 'abc+\\' + self.site.version = (1, 29, 0, '-wmf', 21) + + def side_effect(*args, **kwargs): + if kwargs.get('meta') == 'tokens': + return { + 'query': {'tokens': {'logintoken': login_token}} + } + else: + assert kwargs['lgtoken'] == login_token + return { + 'login': {'result': 'Success'} + } + + self.api.side_effect = side_effect + + with mock.patch('mwclient.client.Site.site_init'): + self.site.login('myusername', 'mypassword') + + call_args = self.api.call_args_list + + assert len(call_args) == 3 + assert call_args[1] == mock.call('query', 'POST', meta='tokens', type='login') + assert call_args[2] == mock.call('login', 'POST', lgname='myusername', lgpassword='mypassword', lgtoken=login_token) + class TestClientUploadArgs(TestCase): -- GitLab