|
import os |
|
import json |
|
import requests |
|
from urllib.parse import urlparse |
|
from flask import Flask, redirect, request, render_template, jsonify |
|
|
|
|
|
app = Flask(__name__, template_folder=os.path.dirname( |
|
os.path.abspath(__file__))) |
|
|
|
CLIENT_ID = "Enter your client id" |
|
CLIENT_SECRET = "Enter your client secret" |
|
SCOPE = "user" # use whatever scope you need |
|
|
|
STATE = "state-prevent-csrf" |
|
REDIRECT_URI = "http://localhost:8080/auth/github" |
|
ALLOW_SIGNUP = "true" |
|
|
|
|
|
|
|
@app.route('/', methods=['post', 'get']) |
|
def index(): |
|
if request.method == 'GET': |
|
return render_template("index.html") |
|
elif request.method == 'POST': |
|
username = request.form.get('username') |
|
return redirect(f'https://github.com/login/oauth/authorize?login={username}&client_id={CLIENT_ID}&redirect_uri={REDIRECT_URI}&allow_signup={ALLOW_SIGNUP}&state={STATE}&scope={SCOPE}') |
|
else: |
|
return '404', 404 |
|
|
|
|
|
@app.route('/auth/github') |
|
def github_auth(): |
|
authorization_code = request.args.get('code') |
|
state = request.args.get('state') |
|
print(authorization_code) |
|
print(state) |
|
if state != STATE: |
|
return "state doesn't match", 400 |
|
if authorization_code is None: |
|
return 'authorization code not available', 400 |
|
access_token_url = f'https://github.com/login/oauth/access_token?client_id={CLIENT_ID}&client_secret={CLIENT_SECRET}&code={authorization_code}' |
|
print(access_token_url) |
|
res = requests.post(access_token_url, headers={ |
|
'Accept': 'application/json'}) |
|
data = res.json() |
|
user_data = None |
|
if 'access_token' in data.keys(): |
|
res = requests.get( |
|
"https://api.github.com/user", headers={'Authorization': 'token ' + data['access_token']}) |
|
user_data = res.json() |
|
|
|
return render_template("user-info.html", data=data, user_info=json.dumps(user_data, indent=2)) |
|
|
|
|
|
if __name__ == '__main__': |
|
app.run('localhost', 8080, debug=True) |