3

I'm using Github-Flask to authenitcate users on my app. I use github.authorize(scope='user:email'). How can I get the logged in user's email?

github = GitHub(app)
user = None

@app.route('/login')
def login():
   if user.username: 
      return redirect(url_for('index'))

   return github.authorize(scope='user:email')

@github.access_token_getter
def token_getter():
   if user is not None:
      return user.github_access_token

@app.route('/github-callback')
@github.authorized_handler
def authorized(oauth_token):
    if oauth_token is None:
       flask.flash("Authorization failed.")
       return redirect(url_for('index'))

   global user
   user.username = oauth_token
   return redirect(url_for('index'))
davidism
  • 121,510
  • 29
  • 395
  • 339
Ajax1234
  • 69,937
  • 8
  • 61
  • 102

1 Answers1

3

The login route is only redirecting to GitHub's authorization page, it has no way to access the user data yet because the user isn't logged in. Once you get to the authorized callback, you can make API calls to GitHub.

In the authorized route, use github.get to call the user API endpoint.

data = github.get('user')
email = data['email']

Also, do not use global user to store the logged in user. See Are global variables thread safe in flask? Instead, store the user id in session, and load the user into g, as shown in GitHub-Flask's full example.

davidism
  • 121,510
  • 29
  • 395
  • 339