Thanks to visit codestin.com
Credit goes to github.com

Skip to content

finishing github app installtion token #4

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
LICENSE
README.md
.gitignore

7 changes: 5 additions & 2 deletions Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,12 @@ verify_ssl = true
name = "pypi"

[packages]
jwt = "==1.3.1"
requests = "==2.32.2"
jwt = "==1.3.1"
cryptography = "==42.0.5"

[dev-packages]
python-dotenv = "==1.0.1"

[requires]
python_version = "3"
python_version = "3"
22 changes: 17 additions & 5 deletions Pipfile.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,7 @@
# github-access-using-githubapp
github-access-using-githubapp


# Reference

[generating-an-installation-access-token](https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/generating-an-installation-access-token-for-a-github-app#generating-an-installation-access-token)
66 changes: 61 additions & 5 deletions generate_jwt.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
import time
import argparse
import os

import requests
from dotenv import load_dotenv

def create_jwt(private_key, app_id):
"""
Expand All @@ -12,7 +13,7 @@ def create_jwt(private_key, app_id):
:return:
"""
# Open PEM
# with open(pem_path, 'rb') as pem_file:
# with open(private_key, 'rb') as pem_file:
# signing_key = jwk_from_pem(pem_file.read())
signing_key = jwk_from_pem(private_key.encode('utf-8'))

Expand All @@ -30,27 +31,82 @@ def create_jwt(private_key, app_id):
encoded_jwt = jwt_instance.encode(payload, signing_key, alg='RS256')

# Set JWT as environment variable
os.environ["GITHUB_JWT"] = encoded_jwt
# os.environ["GITHUB_JWT"] = encoded_jwt

print(f"JWT set as environment variable: JWT={encoded_jwt}")
# print(f"JWT token created successfully")
return encoded_jwt

def get_app_installation_id(jwt:str, github_account_type:str):
"""
returns github app installation id on user and org accounts
:param jwt:
:return:
"""
GITHUB_REPOSITORY = os.getenv('GITHUB_REPOSITORY')
GITHUB_REPOSITORY_OWNER = os.getenv('GITHUB_REPOSITORY_OWNER')
org_url = f'https://api.github.com/repos/{GITHUB_REPOSITORY}/installation'
user_url = f'https://api.github.com/users/{GITHUB_REPOSITORY_OWNER}/installation'
if github_account_type == 'user':
url = user_url
else:
url = org_url
headers = {
"Accept": "application/vnd.github+json",
"Authorization": f"Bearer {jwt}",
"X-GitHub-Api-Version": "2022-11-28"
}
response = requests.get(url= url, headers=headers)

if response.status_code == 200:
print(f'Okay. Received proper response.Got installation id')
response_json = response.json()
elif response.status_code == 301:
print(f'Moved permanently. Cant get a response')
else:
print(f'Resource Not Found!')

# Installation id of github app
installation_id = response_json['id']
return installation_id

def generate_token_by_post_call(installation_id:int, jwt:str):
"""
create a app installation token by doing a rest api post call with permissions for application
:return:
"""
url = f'https://api.github.com/app/installations/{installation_id}/access_tokens'
headers = {
"Accept": "application/vnd.github+json",
"Authorization": f"Bearer {jwt}",
"X-GitHub-Api-Version": "2022-11-28"
}
response = requests.post(url=url, headers=headers)
response_json = response.json()
if response.status_code == 201:
print(f'Github app installation token generate succcessfully, expires at {response_json["expires_at"]}')
os.environ['GH_TOKEN'] = response_json['token']

def main():
"""
to test the code
:return:
"""
load_dotenv()
parser = argparse.ArgumentParser(description="Create JWT for GitHub App authentication")
parser.add_argument("--github_app_private_key",required=True, type=str, help="Github App Private key")
parser.add_argument("--github_account_type",required=True, choices=['user','organization'], help="Github account whether user account ot github org")
parser.add_argument("--github_app_id",required=True, type=str, help="Your GitHub App ID")
args = parser.parse_args()

private_key = args.github_app_private_key
app_id = args.github_app_id
github_account_type = args.github_account_type

# function call
create_jwt(private_key, app_id)
jwt = create_jwt(private_key=private_key, app_id=app_id)
installation_id = get_app_installation_id(jwt=jwt, github_account_type=github_account_type)
generate_token_by_post_call(installation_id=installation_id, jwt=jwt)


if __name__ == "__main__":
main()