Skip to content

Commit

Permalink
Fix linting issues
Browse files Browse the repository at this point in the history
  • Loading branch information
mansab committed Sep 26, 2024
1 parent b621836 commit ad5ba4a
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 27 deletions.
2 changes: 1 addition & 1 deletion src/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,4 @@

GITHUB_TOKEN = os.environ.get("GITHUB_TOKEN")
GITHUB_APP_TOKEN = os.environ.get("GITHUB_APP_TOKEN")
APP_AUTH_ID = "Iv1.029716a4d1524dcd"
APP_AUTH_ID = "Iv1.029716a4d1524dcd"
40 changes: 27 additions & 13 deletions src/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,17 +53,23 @@ def get_token(logger):

if token is not None:
return token
elif args.mode == "pat-auth":
if args.mode == "pat-auth":
token = GITHUB_TOKEN
elif args.mode == "app-auth":
return token
if args.mode == "app-auth":
token = GITHUB_APP_TOKEN
if not token:
logger.info(f"Obtain the Github App token by accessing: http://localhost:8000/auth")
logger.info(f"and set GITHUB_APP_TOKEN as environment variable.")
raise Exception("Github APP token not found.")
logger.info("Obtain the Github App token by accessing: http://localhost:8000/auth")
logger.info("and set GITHUB_APP_TOKEN as environment variable.")
raise RuntimeError("Github APP token not found.")
return token

def authenticate_with_device_flow(logger):
"""Initiates Github Device Authentication flow
Returns:
token: Github App token for the authorized user
"""
device_code_url = "https://github.com/login/device/code"
client_id = APP_AUTH_ID
payload = {
Expand All @@ -76,7 +82,7 @@ def authenticate_with_device_flow(logger):
}

try:
response = requests.post(device_code_url, json=payload, headers=headers)
response = requests.post(device_code_url, json=payload, headers=headers, timeout=10)
if response.status_code == 200:
data = response.json()
device_code = data['device_code']
Expand All @@ -86,29 +92,37 @@ def authenticate_with_device_flow(logger):
logger.info(f"Activate GitHub authentication at: {verification_uri}")
logger.info(f"Enter activation code: {user_code}")

logger.info(f"Waiting 30 seconds for the user to authorize the device...")
logger.info("Waiting 30 seconds for the user to authorize the device...")
time.sleep(30)

token_url = "https://github.com/login/oauth/access_token"
token_response = requests.post(token_url, json={
"client_id": client_id,
"device_code": device_code,
"grant_type": "urn:ietf:params:oauth:grant-type:device_code"
}, headers={"Accept": "application/json"})
}, headers={"Accept": "application/json"}, timeout=10)

token_data = token_response.json()
token_value = token_data.get("access_token")

if token_value is not None:
logger.info("Successfully obtained access token.")
logger.info(f"Please set env var GITHUB_APP_TOKEN={token_value} and restart the app.")
else:
logger.error(f"Failed to obtain access token. Status: {token_response.status_code}, Response: {token_response.text}")
logger.info(
"Please set env var GITHUB_APP_TOKEN=%s and restart the app.",
token_value
)
return None
else:
logger.error(f"Failed to initiate device flow: {response.status_code} {response.text}")
logger.error(
"Failed to obtain access token. "
"Status: %s, Response: %s",
token_response.status_code,
token_response.text
)
return None

logger.error(f"Failed to initiate device flow: {response.status_code} {response.text}")
return None

except Exception as e:
logger.exception(f"Error during device flow authentication: {str(e)}")
return None
Expand Down
33 changes: 20 additions & 13 deletions src/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,13 +86,21 @@ def index():
def auth():
"""Endpoint for handling Device Flow authentication."""
try:
threading.Thread(target=authenticate_with_device_flow, args=(logger,)).start()

return make_response("Authentication process started. Please check your console for instructions.", 200)
except Exception as e:
threading.Thread(
target=authenticate_with_device_flow,
args=(logger,)
).start()

msg = (
"Authentication process started. "
"Please check your console for instructions."
)
return make_response(msg, 200)

except RuntimeError as e:
logger.error("An error occurred during authentication: %s", str(e))
return make_response("Authentication error.", 500)


@app.route('/health')
def health():
Expand Down Expand Up @@ -152,23 +160,22 @@ def limit():
'rate_limit': rate
}
logger.info("Request URI: %s Response Code: %d",
redact_token(request.full_path), response.status_code)
redact_token(request.full_path), response.status_code)
else:
logger.warning("Missing parameter(s) or Environment Variable")
logger.warning("Missing parameter(s) or Environment Variable")
response = {'status': 'ok', 'rate_limit': {
'error': 'Failed to retrieve rate limit information'}}

return jsonify(response)


@app.route('/token')
def token():
if access_token is None:
return jsonify({"error": "Token is not set."}), 401
return jsonify({"Token": access_token})

@app.route('/favicon.ico')
def favicon():
"""Handle favicon reuquests from browser
Returns:
http_status: 204
"""
return '', 204


Expand Down

0 comments on commit ad5ba4a

Please sign in to comment.