From ce30bfe65a9ecde61598aee300ef381fa65fff88 Mon Sep 17 00:00:00 2001 From: Magnesium12 Date: Sun, 16 Oct 2022 01:50:22 +0530 Subject: [PATCH] feat(github): Add Github OAuth for the bot. --- bot/github/oauth.py | 47 +++++++++++++++++++++++++++++++++++++++++++++ main.py | 12 ++++++++++++ requirements.txt | 1 + 3 files changed, 60 insertions(+) create mode 100644 bot/github/oauth.py diff --git a/bot/github/oauth.py b/bot/github/oauth.py new file mode 100644 index 0000000..e57f186 --- /dev/null +++ b/bot/github/oauth.py @@ -0,0 +1,47 @@ +import json + +import requests +from bottle import redirect, request + +client_id = '9cfb35031c71d9f6e013' +client_secret = '2e7e793b001390e9f2c9dd2e0033747bff890896' +redirect_uri = 'http://localhost:5556/github/oauth/redirect' +scopes = 'admin:repo_hook' +auth_url = 'https://github.com/login/oauth/authorize/?client_id=' + client_id + '&redirect_uri=' + redirect_uri + '&scope=' + scopes +get_token_url = 'https://github.com/login/oauth/access_token' + + +def redirector() -> None: + redirect(auth_url) + + +def authorizer() -> str: + auth_code: str = request.query.get('code') + if auth_code: + token: str = exchanger(auth_code) + return f"Access-token = {token}" + else: + return "Authorization failed!" + + +def exchanger(code: str) -> str: + parameters = { + 'code': code, + 'client_id': client_id, + 'client_secret': client_secret, + 'redirect_uri': redirect_uri + } + payload: str = json.dumps(parameters) + header: dict[str, str] = { + 'Content-Type': 'application/json', + 'Accept': 'application/json' + } + + r = requests.post(get_token_url, data=payload, headers=header) + + if r.status_code != 200: + return "Failed to get Access-Token" + else: + data = r.json() + token = data['access_token'] + return token diff --git a/main.py b/main.py index ea839f8..b2a4032 100644 --- a/main.py +++ b/main.py @@ -22,6 +22,7 @@ from sentry_sdk.integrations.bottle import BottleIntegration from bot.github.github_parsers import GitHubPayloadParser +from bot.github.oauth import authorizer, redirector from bot.models.github.event import GitHubEvent from bot.slack import SlackBot from bot.utils.log import Logger @@ -79,6 +80,17 @@ def manage_slack_commands() -> dict | None: return response +@get("/github/oauth") +def initiate_oauth() -> None: + redirector() + + +@get("/github/oauth/redirect") +def get_access_token() -> str: + token = authorizer() + return token + + if __name__ == "__main__": load_dotenv(Path(".") / ".env") debug: bool = os.environ["DEBUG"] == "1" diff --git a/requirements.txt b/requirements.txt index 0a0cf27..dc9e605 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,5 @@ bottle==0.12.20 python-dotenv==0.19.2 +requests==2.28.1 sentry-sdk[bottle]==0.16.2 slackclient==2.9.3