|
| 1 | +from flask import Flask, redirect, url_for, session, request, jsonify |
| 2 | +from flask_oauthlib.client import OAuth |
| 3 | + |
| 4 | + |
| 5 | +app = Flask(__name__) |
| 6 | +app.debug = True |
| 7 | +app.secret_key = 'development' |
| 8 | +oauth = OAuth() |
| 9 | + |
| 10 | +github = oauth.remote_app( |
| 11 | + 'github', |
| 12 | + consumer_key='a11a1bda412d928fb39a', |
| 13 | + consumer_secret='92b7cf30bc42c49d589a10372c3f9ff3bb310037', |
| 14 | + request_token_params={'scope': 'user:email'}, |
| 15 | + base_url='https://api.github.com/', |
| 16 | + request_token_url=None, |
| 17 | + access_token_method='POST', |
| 18 | + access_token_url='https://github.com/login/oauth/access_token', |
| 19 | + authorize_url='https://github.com/login/oauth/authorize' |
| 20 | +) |
| 21 | + |
| 22 | + |
| 23 | +@app.route('/') |
| 24 | +def index(): |
| 25 | + if 'github_token' in session: |
| 26 | + me = github.get('user') |
| 27 | + return jsonify(me) |
| 28 | + return redirect(url_for('login')) |
| 29 | + |
| 30 | + |
| 31 | +@app.route('/login') |
| 32 | +def login(): |
| 33 | + return github.authorize(callback=url_for('authorized', _external=True)) |
| 34 | + |
| 35 | + |
| 36 | +@app.route('/logout') |
| 37 | +def logout(): |
| 38 | + session.pop('github_token', None) |
| 39 | + return redirect(url_for('index')) |
| 40 | + |
| 41 | + |
| 42 | +@app.route('/login/authorized') |
| 43 | +@github.authorized_handler |
| 44 | +def authorized(resp): |
| 45 | + if resp is None: |
| 46 | + return 'Access denied: reason=%s error=%s' % ( |
| 47 | + request.args['error_reason'], |
| 48 | + request.args['error_description'] |
| 49 | + ) |
| 50 | + session['github_token'] = (resp['access_token'], '') |
| 51 | + me = github.get('user') |
| 52 | + return jsonify(me) |
| 53 | + |
| 54 | + |
| 55 | +@github.tokengetter |
| 56 | +def get_github_oauth_token(): |
| 57 | + return session.get('github_token') |
| 58 | + |
| 59 | + |
| 60 | +if __name__ == '__main__': |
| 61 | + app.run() |
0 commit comments