oauth/client.py
author durandn
Mon, 11 Apr 2016 16:47:09 +0200
changeset 63 6bfac7c633a0
parent 32 eb9e83610c99
permissions -rw-r--r--
Added permission management into metaeducation (instead of it being in renkanmanager) + more logging around auth code + corrected client.py for oauth server so it sends the correct content-type when using client credentials

from flask import Flask, url_for, session, request, jsonify, render_template, redirect
from flask_oauthlib.client import OAuth
from settings.client_settings import ClientSettings
import base64
import requests
import json

app = Flask(__name__)
app.debug = True
app.secret_key = 'secret'
app.config.from_object(ClientSettings)
oauth = OAuth(app)

remote = oauth.remote_app(
    'remote',
    consumer_key=app.config.get("CLIENT_ID", ""),
    consumer_secret=app.config.get("CLIENT_SECRET", ""),
    request_token_params=app.config.get("REQUEST_TOKEN_PARAMS", ""),
    base_url=app.config.get("BASE_URL", ""),
    request_token_url=app.config.get("REQUEST_TOKEN_URL", ""),
    access_token_url=app.config.get("ACCESS_TOKEN_URL", ""),
    authorize_url=app.config.get("AUTHORIZE_URL", "")
)


@app.route('/')
def index():
    if 'remote_oauth_authorizationcode' not in session:
        next_url = request.args.get('next') or request.referrer or None
        return remote.authorize(
            callback=url_for('authorized', next=next_url, _external=True)
        )
    if 'me' not in session:
        resp = remote.get('user/InfoComplete')
        print("authcode resp data: "+str(resp.data))
        me = resp.data.get("displayName", "")
        session["me"] = me
        id = resp.data.get("id", "")
        session["me_id"] = id
    if 'remote_oauth_clientcredentials' not in session:
        auth_string = bytes(app.config["CLIENT_ID"]+':'+app.config['CLIENT_SECRET'], "utf-8")
        auth_code = base64.b64encode(auth_string).decode("utf-8")
        resp = requests.post(app.config["ACCESS_TOKEN_URL"]+"?grant_type=client_credentials&scope=basic", data={}, headers={
            'Authorization': 'Basic %s' % auth_code,
        })
        if resp is None:
            return 'Access denied: reason=%s error=%s' % (
                request.args['error_reason'],
                request.args['error_description']
            )
        session['remote_oauth_clientcredentials'] = (json.loads(resp.text)['access_token'], '')
        resp = remote.get('user/InfoComplete')
        print("clientcredentials resp data: "+str(resp.data))
        server = resp.data.get("displayName", "")
        session["server"] = server
    return render_template('client/index.html', current_user_id=session["me_id"], current_username=session["me"], oauth_username=session["server"])

@app.route('/renkan-request')
def renkan_request():
    if 'remote_oauth_clientcredentials' in session:
        resp = requests.post(
            app.config["CREATE_RENKAN_ENDPOINT"]+"?act_as="+str(session.get("me_id", "anonymous")), 
            json.dumps({"title": "RENKAN_FROM_GED"}),
            headers={
                'Authorization': 'Bearer %s' % session['remote_oauth_clientcredentials'][0],
                'renkan-act-as': session.get("me_id", "anonymous"),
                'content-type': "application/json"
            }
        )
        print("%r : %r" %(resp.status_code, json.loads(resp.text)))
    return redirect('/')

@app.route('/authorized')
def authorized():
    resp = remote.authorized_response()
    if resp is None:
        return 'Access denied: reason=%s error=%s' % (
            request.args['error_reason'],
            request.args['error_description']
        )
    session['remote_oauth_authorizationcode'] = (resp['access_token'], '')
    
    return redirect('/')


@remote.tokengetter
def get_oauth_token():
    print("referrer : "+request.referrer)
    if 'remote_oauth_clientcredentials' in session and 'server' not in session:
        return session['remote_oauth_clientcredentials']
    else:
        return session.get('remote_oauth_authorizationcode', '')



if __name__ == '__main__':
    import os
    os.environ['DEBUG'] = 'true'
    os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = 'true'
    app.run(host='localhost', port=8000)