Akron | ca9bd98 | 2016-12-06 16:59:57 +0100 | [diff] [blame^] | 1 | import config |
| 2 | |
| 3 | __author__ = 'hanl' |
| 4 | |
| 5 | from flask import Flask, redirect, url_for, session, request, jsonify |
| 6 | from flask_oauthlib.client import OAuth |
| 7 | |
| 8 | app = Flask(__name__) |
| 9 | app.debug = True |
| 10 | app.secret_key = 'development' |
| 11 | oauth = OAuth(app) |
| 12 | korap = oauth.remote_app( |
| 13 | 'korap', |
| 14 | consumer_key=config.OAUTH2_CLIENT_ID, |
| 15 | consumer_secret=config.OAUTH2_CLIENT_SECRET, |
| 16 | request_token_params={}, |
| 17 | base_url='https://localhost:8443/api/v0.1', |
| 18 | request_token_url=None, |
| 19 | access_token_method='POST', |
| 20 | access_token_url='https://localhost:8443/api/v0.1/oauth2/token', |
| 21 | # should be a website of this flask application |
| 22 | authorize_url='https://localhost:8443/api/v0.1/oauth2/authorize', |
| 23 | ) |
| 24 | |
| 25 | |
| 26 | @app.route('/') |
| 27 | def index(): |
| 28 | if 'dropbox_token' in session: |
| 29 | me = korap.get('user/info') |
| 30 | return jsonify(me.data) |
| 31 | return redirect(url_for('login')) |
| 32 | |
| 33 | |
| 34 | @app.route('/login') |
| 35 | def login(): |
| 36 | return korap.authorize(callback=url_for('authorized', _external=True)) |
| 37 | |
| 38 | |
| 39 | @app.route('/logout') |
| 40 | def logout(): |
| 41 | session.pop('korap_token', None) |
| 42 | return redirect(url_for('index')) |
| 43 | |
| 44 | |
| 45 | @app.route('/login/authorized') |
| 46 | def authorized(): |
| 47 | resp = korap.authorized_response() |
| 48 | if resp is None: |
| 49 | return 'Access denied: reason=%s error=%s' % ( |
| 50 | request.args['error'], |
| 51 | request.args['error_description'] |
| 52 | ) |
| 53 | session['korap_token'] = (resp['access_token'], '') |
| 54 | me = korap.get('user/info') |
| 55 | return jsonify(me.data) |
| 56 | |
| 57 | |
| 58 | @korap.tokengetter |
| 59 | def get_korap_oauth_token(): |
| 60 | return session.get('korap_token') |
| 61 | |
| 62 | |
| 63 | |
| 64 | if __name__ == '__main__': |
| 65 | app.run() |