robinroy03/github-bot
0
1from datetime import datetime2import jwt3import requests4import base645 6 7def decode_string(base64_string: str) -> str:8 """Decodes a Base64 string.9 10 NOTE:11 This workaround was required because .env cannot handle multi-line strings, so it was required to convert it to a single line. There are mutliple ways to achieve the same result.12 """13 14 base64_bytes = base64_string.encode('utf-8')15 string_bytes = base64.b64decode(base64_bytes)16 string = string_bytes.decode('utf-8')17 return string18 19 20def get_installation_access_token(21 signing_key: str, app_id: str, installation_id: str22) -> str:23 """24 Obtain and return a GitHub installation access token.25 26 Arguments:27 signing_key: base64 encoded signing key (you'll get this from the .env)28 app_id: The application ID29 installation_id: The ID of the app installation.30 31 Returns:32 The installation access token obtained from GitHub.33 """34 35 # Refer https://github.com/orgs/community/discussions/4818636 # Refer https://stackoverflow.com/questions/77325437/how-do-i-get-an-github-app-installation-token-to-authenticate-cloning-a-reposito37 now = int(datetime.now().timestamp())38 39 signing_key = decode_string(signing_key)40 signing_key = jwt.jwk_from_pem(signing_key.encode())41 payload = {"iat": now, "exp": now + 600, "iss": app_id}42 jwt_instance = jwt.JWT()43 encoded_jwt = jwt_instance.encode(payload, signing_key, alg="RS256")44 45 response = requests.post(46 "https://api.github.com/app/installations/" f"{installation_id}/access_tokens",47 headers={48 "Authorization": f"Bearer {encoded_jwt}",49 "Accept": "application/vnd.github+json",50 "X-GitHub-Api-Version": "2022-11-28",51 },52 )53 if not 200 <= response.status_code < 300:54 raise RuntimeError(55 "Unable to get token. Status code was "56 f"{response.status_code}, body was {response.text}."57 )58 59 return response.json()["token"]60 61 62if __name__ == "__main__":63 import os64 65 print(get_installation_access_token(66 os.environ.get('CHATBOT_PUB_KEY'),67 os.environ.get('APP_ID'),68 os.environ.get('INSTALLATION_ID') 69 ))