Skip to content

Instantly share code, notes, and snippets.

@webmaniak
Last active March 17, 2021 16:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save webmaniak/cb5cc697d7cc99d194ae1253452f3b52 to your computer and use it in GitHub Desktop.
Save webmaniak/cb5cc697d7cc99d194ae1253452f3b52 to your computer and use it in GitHub Desktop.
ODK Collect: create a mobile user authentication QR Code in Python
import base64
import json
import qrcode
import qrcode.image.svg as qrsvg
import zlib
def make_odk_auth_qrcode(server_url, app_user_token, project_id):
"""
Creates a QR Code containing base server settings to connect to ODK.
:param server_url: the URL to the ODK Central server
:param app_user_token: the token of the mobile user
:param project_id: the ID of the project for which the mobile user has rights.
"""
endpoint_url = f'{server_url}/v1/key/{app_user_token}/projects/{project_id}'
# Create ODK settings, parse them to JSON, compress them and encode them in b64
odk_settings = {
'general': {
'server_url': f'{endpoint_url}',
},
'admin': {},
}
json_settings = json.dumps(odk_settings)
bytes_settings = zlib.compress(json_settings.encode('UTF-8'))
encoded_settings = base64.b64encode(bytes_settings)
# Generate the QR Code
qr = qrcode.make(encoded_settings)
# Save the resulting QR Code
# See this StackOverflow post if you wish to keep the resulting file in memory:
# https://stackoverflow.com/questions/46593477/convert-pil-image-object-to-file-object/51553992
qr.save('qrcode.jpg', 'JPEG')
if __name__ == '__main__':
# Sample usage (resulting 'qrcode.jpg' file can be scanned by ODK Collect)
# Note: you'll need python-qrcode installed (see instructions here: https://pypi.org/project/qrcode/)
make_odk_auth_qrcode(
'https://odk.example.com',
'HRpcpt0OQ1tFEjfj3zZltFgnjeIYgnuTMXyTi7ZWaw4c!V$c6depxeJW4jU3j4mX',
11,
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment