from flask import make_response, redirect
from requests import post, get
import json #used for github oauth

def githubCallback(request, GITHUB_CLIENT_SECRET, GITHUB_CLIENT_ID, s):
    try:
        code = request.args.get("code")
        url = "https://github.com/login/oauth/access_token" #The baseurl
        params = {'client_id': GITHUB_CLIENT_ID, 'client_secret': GITHUB_CLIENT_SECRET, 'code': code} #As paramtere we send the client id and the client secret which we get from github when registering an application and the user code from before
        oauth_token = post(url,params).text.split("access_token=")[1].split("&")[0] #Send a post request with the parameters from

        headers = {'Authorization': 'token ' + oauth_token,} #Useragent doesn't matters, but is set here
        githubResponse = get("https://api.github.com/user", headers=headers).text
        userID = str(json.loads(githubResponse)['id'])
        username = str(json.loads(githubResponse)['login'])

        resp = make_response(redirect('/')) #redirect the user at the end back to the main page
        resp.set_cookie('userID', s.dumps("github_" + userID)) #set the cookies with username and userid
        resp.set_cookie('username', s.dumps(username))
        return resp
    except:
        print("Authentication failed")