Skip to content

Instantly share code, notes, and snippets.

Created September 8, 2012 12:34
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
def index_view(request):
"""Render a link to log the user in using Bouncer."""
# Generate the login URL, with the right client id and callback URL. You
# could also add a `state` parameter for CSRF protection.
settings = request.registry.settings
params = {
'client_id': settings.get('client_id'),
'redirect_uri': request.route_url('callback'),
'response_type': 'code'
login_url = '{0}?{1}'.format(AUTHORIZE_ENDPOINT, urlencode(params))
# Render a hyperlink.
markup = u"""
<h1>Sign In</h1>
<p><a href="{0}">Sign in with Bouncer</a>.</p>
return Response(markup.format(login_url))
def callback_view(request):
"""Handle the authorization response:
* use the code to get a token
* use the token to get the user data
* redirect to the user view
# Handle errors, e.g.: with a try again link...
error = request.params.get('error')
if error:
markup = u"""
<p><a href="/">Try that again</a></p>.
return Response(markup.format(request.params))
# Otherwise we will have an authorization code. N.b.: You might want to
# validate and check the `state` param here...
code = request.params.get('code')
# Use the authorization code to get an access token.
settings = request.registry.settings
params = {
'code': code,
'grant_type': 'authorization_code',
'redirect_uri': request.route_url('callback')
auth = (settings.get('client_id'), settings.get('client_secret'))
response = requests.get(TOKEN_ENDPOINT, params=params, auth=auth)
token_data = response.json
# Use the token to get the user's data.
auth = BearerAuth(token_data['access_token'])
response = requests.get(USER_ENDPOINT, auth=auth)
user_data = response.json.get('data')
# At this point you might log the user in, save the data, etc. We'll just
# redirect to /user/:username.
username = user_data.get('username')
url = request.route_url('user', username=username)
return HTTPFound(location=location)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment