Files
CopilotTerminal/AuthToken.py
2023-05-24 12:11:49 +02:00

90 lines
3.0 KiB
Python

import json
import os
import time
import click
import requests
class AuthToken:
def __init__(self):
self.tokenfile = "token.json"
def save_oauth_token(self, token):
tokenfile_content = {}
# check if file extists
if os.path.exists(self.tokenfile):
with open(self.tokenfile, "r") as f:
tokenfile_content = json.load(f)
tokenfile_content["oauth_token"] = token
with open(self.tokenfile, "w") as f:
json.dump(tokenfile_content, f)
def get_oauth_token(self):
# check if token in tokenfile
if os.path.exists(self.tokenfile):
with open(self.tokenfile, "r") as f:
tokendict = json.load(f)
if "oauth_token" in tokendict:
return tokendict["oauth_token"]
# if not, check if the github copilot extension is installed on the system
path = os.path.expanduser("~/.config/github-copilot/hosts.json")
if os.path.exists(path):
with open(path, "r") as f:
hosts = json.load(f)
if "github.com" in hosts:
token = hosts["github.com"]["oauth_token"]
self.save_oauth_token(token)
return token
# if not, ask the user to enter the token
click.echo("Please enter your github access token (can be found in ~/.config/github-copilot/hosts.json):")
token = click.prompt("Token", type=str)
self.save_oauth_token(token)
return token
def save_github_api_token(self, token: str, expires_at):
tokenfile_content = {}
# check if file extists
if os.path.exists(self.tokenfile):
with open(self.tokenfile, "r") as f:
tokenfile_content = json.load(f)
tokenfile_content["token"] = token
tokenfile_content["expires_at"] = expires_at
with open(self.tokenfile, "w") as f:
json.dump(tokenfile_content, f)
def request_github_api_token(self):
# get the oauth token
oauth_token = self.get_oauth_token()
headers = {
'Authorization': f"Bearer {oauth_token}",
}
response = requests.get('https://api.github.com/copilot_internal/v2/token', headers=headers)
if response.status_code != 200:
return None
token = response.json()
self.save_github_api_token(token["token"], token["expires_at"])
return token["token"]
def get_github_api_token(self):
# check if token in tokenfile
if os.path.exists(self.tokenfile):
with open(self.tokenfile, "r") as f:
tokendict = json.load(f)
if "token" in tokendict and "expires_at" in tokendict:
if tokendict["expires_at"] > time.time():
return tokendict["token"]
# request new api token
return self.request_github_api_token()