Last active
January 25, 2018 15:08
-
-
Save jbweston/389fad330108f12c816b21da162fb123 to your computer and use it in GitHub Desktop.
A mixin class for Jupyterhub deployments that uses a Google docs spreadsheet for whitelisting
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import csv | |
import subprocess | |
from tornado import gen, AsyncHTTPClient | |
@gen.coroutine | |
def get_whitelist(sheets_url, usernames_field): | |
# Get CSV from sheet | |
client = AsyncHTTPClient() | |
resp = yield client.fetch(sheets_url) | |
raw_csv = resp.body.decode('utf-8', 'replace').split('\n') | |
reader = csv.reader(raw_csv) | |
# Extract column index of usernames | |
headers = next(reader) | |
try: | |
username_column = headers.index(usernames_field) | |
except ValueError: | |
raise ValueError('header field "{}" not found in sheet {}' | |
.format(usernames_field, sheets_url)) | |
usernames = [row[username_column] for row in reader] | |
return usernames | |
class SheetWhitelister: | |
sheets_url = 'https://docs.google.com/spreadsheets/d/xxxxxx' | |
usernames_column = 'Github username' | |
@gen.coroutine | |
def check_whitelist(self, username): | |
if super().check_whitelist(username): | |
return True | |
try: | |
whitelist = yield get_whitelist(self.sheets_url, | |
self.usernames_column) | |
self.log.info('Retrieved users from spreadsheet: {}' | |
.format(whitelist)) | |
self.whitelist.update(whitelist) | |
except Exception: | |
self.log.error('Failed to fetch usernames from spreadsheet', | |
exc_info=True) | |
return (username in self.whitelist) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment