1 oauth2
Markus Bergholz edited this page 4 months ago
from bottle import route, request, HTTPResponse, static_file, run
from uuid import uuid4
import urllib
import requests

CLIENT_ID = "..."
REDIRECT_URI = "http://localhost:8080/callback"

def login():
	return {'login': make_authorization_url()}

def make_authorization_url():
	# Generate a random string for the state parameter
	# Save it for use later to prevent xsrf attacks
	state = str(uuid4())
	params = {"client_id": CLIENT_ID,
			  "response_type": "code",
			  "state": state,
			  "redirect_uri": REDIRECT_URI,
			  "duration": "temporary",
			  "scope": "identity"}

	url = "https://git.osuv.de/login/oauth/authorize?" + urllib.parse.urlencode(params)
	return url

# Left as an exercise to the reader.
# You may want to store valid states in a database or memcache,
# or perhaps cryptographically sign them and verify upon retrieval.
def save_created_state(state):
def is_valid_state(state):

def callback():
    code = request.query.get('code')
    state = request.query.get('state')

    if None not in [code, state]:
        data = {
            "client_id": CLIENT_ID,
            "client_secret": CLIENT_SECRET,
            "code": code,
            "grant_type": "authorization_code",
            "redirect_uri": REDIRECT_URI
        response = requests.post('https://git.osuv.de/login/oauth/access_token', data = data)
        retval = response.json()
        print("code: " + code)
        print("state: " + state)
        print("access_tolken: " + retval['access_token'])
        print("token_type: " + retval['token_type'])
        print("expires_in: {EXPIRE}".format(EXPIRE=retval['expires_in']))
        print("refresh_token: " + retval['refresh_token'])
        return {'access_token': retval['access_token']}

        test = requests.get('https://git.osuv.de/api/v1/user', 
                'Authorization': 'token {TOKEN}'.format(TOKEN=retval['access_token']),
                'Content-Type': 'application/json',
                'accept': 'application/json'

    return "got a code! {code}".format(code=code)

if __name__ == '__main__':
	run(host='', port=8080)