add CSRF token to API calls #7 #13

This commit is contained in:
Felix Lohmeier 2021-01-04 13:42:13 +01:00
parent 8a726d9a30
commit 21bf1f2adc
2 changed files with 17 additions and 2 deletions

View File

@ -6,7 +6,7 @@ The [OpenRefine Python Client from PaulMakepeace](https://github.com/PaulMakepea
This fork extends the command line interface (CLI) and is distributed as a convenient one-file-executable (Windows, Linux, macOS).
It is also available via Docker Hub, PyPI and Binder.
works with OpenRefine 2.7, 2.8, 3.0, 3.1, 3.2
works with OpenRefine 2.7, 2.8, 3.0, 3.1, 3.2, 3.3, 3.4, 3.4.1
## Download
@ -714,7 +714,7 @@ Note to myself: When releasing a new version...
4. Run functional tests with Linux executable
```sh
for v in 2.7 2.8 3.0 3.1 3.2; do
for v in 2.7 2.8 3.0 3.1 3.2 3.3 3.4 3.4.1; do
./tests-cli.sh $v openrefine-client_0-3-7_linux
done
```

View File

@ -53,6 +53,18 @@ class RefineServer(object):
server = self.url()
self.server = server[:-1] if server.endswith('/') else server
self.__version = None # see version @property below
self.token = None # CSRF token introduced in OpenRefine 3.3
self.get_csrf_token()
def get_csrf_token(self):
"""Return csrf token."""
try:
url = self.server + '/command/core/get-csrf-token'
response = json.loads(urllib2.urlopen(url).read())
self.token = response['token']
return self.token
except:
pass # fail silently to not disturb usage of OpenRefine <3.3
def urlopen(self, command, data=None, params=None, project_id=None):
"""Open a Refine URL and with optional query params and POST data.
@ -73,6 +85,9 @@ class RefineServer(object):
data['project'] = project_id
else:
params['project'] = project_id
# be lazy and send the token for each API call (even when not needed)
if self.token:
params['csrf_token'] = self.token
if params:
url += '?' + urllib.urlencode(params)
req = urllib2.Request(url)