add example service

This commit is contained in:
Min RK
2016-05-27 16:11:37 +02:00
parent 84868a6475
commit ef9656eb8b
5 changed files with 99 additions and 0 deletions

View File

@@ -0,0 +1,20 @@
# Authenticating a service with JupyterHub
Uses `jupyterhub.services.HubAuthenticated` to authenticate requests with the Hub.
## Run
1. Launch JupyterHub and the `whoami service` with `source launch.sh`.
2. Visit http://127.0.0.1:8000/hub/whoami
After logging in with your local-system credentials, you should see a JSON dump of your user info:
```json
{
"admin": false,
"last_activity": "2016-05-27T14:05:18.016372",
"name": "queequeg",
"pending": null,
"server": "/user/queequeg"
}
```

View File

@@ -0,0 +1,6 @@
from getpass import getuser
import os
c.JupyterHub.api_tokens = {
os.environ['WHOAMI_HUB_API_TOKEN']: getuser(),
}

View File

@@ -0,0 +1,12 @@
# make some API tokens, one for the proxy, one for the service
export CONFIGPROXY_AUTH_TOKEN=`openssl rand -hex 32`
export WHOAMI_HUB_API_TOKEN=`openssl rand -hex 32`
# start JupyterHub
jupyterhub --no-ssl --ip=127.0.0.1 &
# give JupyterHub a moment to start
sleep 2
# start the whoami service as /hub/whoami
python whoami.py

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

View File

@@ -0,0 +1,61 @@
"""An example service authenticating with the Hub.
This serves `/hub/whoami/`, authenticated with the Hub, showing the user their own info.
"""
from getpass import getuser
import json
import os
import requests
from tornado.ioloop import IOLoop
from tornado.httpserver import HTTPServer
from tornado.web import RequestHandler, Application, authenticated
from jupyterhub.services.auth import HubAuthenticated, HubAuth
class WhoAmIHandler(HubAuthenticated, RequestHandler):
hub_users = {getuser()} # the users allowed to access me
def initialize(self, hub_auth):
super().initialize()
self.hub_auth = hub_auth
@authenticated
def get(self):
user_model = self.get_current_user()
self.set_header('content-type', 'application/json')
self.write(json.dumps(user_model, indent=1, sort_keys=True))
def add_route():
# add myself to the proxy
# TODO: this will be done by the Hub when the Hub gets service config
requests.post('http://127.0.0.1:8001/api/routes/hub/whoami',
data=json.dumps({
'target': 'http://127.0.0.1:9999',
}),
headers={
'Authorization': 'token %s' % os.environ['CONFIGPROXY_AUTH_TOKEN'],
}
)
def main():
# FIXME: remove when we can declare routes in Hub config
add_route()
hub_auth = HubAuth(
cookie_name='jupyter-hub-token',
api_token=os.environ['WHOAMI_HUB_API_TOKEN'],
login_url='http://127.0.0.1:8000/hub/login',
)
app = Application([
(r"/hub/whoami", WhoAmIHandler, dict(hub_auth=hub_auth)),
], login_url=hub_auth.login_url)
http_server = HTTPServer(app)
http_server.listen(9999)
IOLoop.current().start()
if __name__ == '__main__':
main()