Skip to content
Snippets Groups Projects
googlecallback.py 1.54 KiB
Newer Older
  • Learn to ignore specific revisions
  • Jonas Leder's avatar
    Jonas Leder committed
    #!/usr/bin/env python3
    
    from flask import make_response, redirect
    from requests import post, get
    
    def googleCallback(request, GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, url_scheme, domain, s):
        try:
            code = request.args.get("code")
            url = "https://www.googleapis.com/oauth2/v4/token" #The baseurl
            headers = {'Content-Type': 'application/x-www-form-urlencoded',}
            params = {'client_id': GOOGLE_CLIENT_ID, 'client_secret': GOOGLE_CLIENT_SECRET, 'code': code, "grant_type": "authorization_code", "redirect_uri": url_scheme + "://" + domain[0] + "/user/google-callback"} #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
            access_token = post(url,params, headers=headers).text.split('access_token": "')[1].split('"')[0]
            authorization_header = {"Authorization": "OAuth %s" % access_token}
            r = get("https://www.googleapis.com/oauth2/v2/userinfo", headers=authorization_header)
            userID = r.text.split('"id": "')[1].split('"')[0]
            name = r.text.split('"name": "')[1].split('"')[0]
            resp = make_response(redirect('/')) #redirect the user at the end back to the main page
            resp.set_cookie('userID', s.dumps("google_" + userID)) #set the cookies with username and userid
            resp.set_cookie('username', s.dumps(name))
            return resp
        except:
    
            print("Authentication failed")
            
    if (__name__ == "__main__"):
        print("This file is not made fore direct call, please run the main.py")
        exit()