Skip to content

Instantly share code, notes, and snippets.

@jbweston
Last active January 25, 2018 15:08
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 jbweston/389fad330108f12c816b21da162fb123 to your computer and use it in GitHub Desktop.
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
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