Skip to content

Commit

Permalink
feat: add repo register (#216)
Browse files Browse the repository at this point in the history
- 在安装 GitHub App 的时候注册仓库
  • Loading branch information
RaoHai authored Aug 18, 2024
2 parents d61333b + 0463495 commit 3d74fd4
Show file tree
Hide file tree
Showing 4 changed files with 85 additions and 6 deletions.
2 changes: 1 addition & 1 deletion server/dao/authorizationDAO.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,4 @@ def create(self, data: Authorization):
return False, {"message": "User creation failed"}
except Exception as e:
print("Error: ", e)
return {"message": "User creation failed"}
return False, {"message": "User creation failed"}
28 changes: 28 additions & 0 deletions server/dao/repositoryConfigDAO.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@

import json
from dao.BaseDAO import BaseDAO
from models.repository import RepositoryConfig
from supabase.client import Client, create_client

from petercat_utils.db.client.supabase import get_client

class RepositoryConfigDAO(BaseDAO):
client: Client

def __init__(self):
super().__init__()
self.client = get_client()

def create(self, data: RepositoryConfig):
print('supabase github_repo_config creation', data.model_dump())
try:
authorization = self.client.from_("github_repo_config")\
.insert(data.model_dump())\
.execute()
if authorization:
return True, {"message": "GithubRepoConfig created successfully"}
else:
return False, {"message": "GithubRepoConfig creation failed"}
except Exception as e:
print("Error: ", e)
return False, {"message": "GithubRepoConfig creation failed"}
8 changes: 8 additions & 0 deletions server/models/repository.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from datetime import datetime
from typing import Optional
from pydantic import BaseModel

class RepositoryConfig(BaseModel):
repo_name: str
robot_id: Optional[str]
created_at: datetime
53 changes: 48 additions & 5 deletions server/routers/github.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
from fastapi import APIRouter, BackgroundTasks, Header, Request
from typing import Annotated
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Header, Request, status
import logging
from fastapi.responses import RedirectResponse
import requests
import time
from github import Auth
from github import Auth, Github, Organization
from auth.get_user_info import get_user_access_token
from dao.authorizationDAO import AuthorizationDAO
from dao.repositoryConfigDAO import RepositoryConfigDAO
from models.repository import RepositoryConfig
from models.authorization import Authorization
from utils.github import get_handler, get_private_key
from petercat_utils import get_env_variable
Expand Down Expand Up @@ -51,13 +55,25 @@ def get_app_installations_access_token(installation_id: str, jwt: str):
)

return resp.json()

def get_installation_repositories(access_token: str):
url = f"https://api.github.com/installation/repositories"
print("get_installation_repositories", url)
resp = requests.get(url, headers={
'X-GitHub-Api-Version': '2022-11-28',
'Accept': 'application/vnd.github+json',
'Authorization': f"Bearer {access_token}"
})
return resp.json()

# https://github.com/login/oauth/authorize?client_id=Iv1.c2e88b429e541264
@router.get("/app/installation/callback")
def github_app_callback(code: str, installation_id: str, setup_action: str):
authorizationDAO = AuthorizationDAO()
authorization_dao = AuthorizationDAO()
repository_config_dao = RepositoryConfigDAO()
if setup_action != "install":
return { "success": False, "message": f"Invalid setup_action value {setup_action}" }
elif authorizationDAO.exists(installation_id=installation_id):
elif authorization_dao.exists(installation_id=installation_id):
return { "success": False, "message": f"Installation_id {installation_id} Exists" }
else:
jwt = get_jwt()
Expand All @@ -69,9 +85,14 @@ def github_app_callback(code: str, installation_id: str, setup_action: str):
created_at=int(time.time())
)

success, message = authorizationDAO.create(authorization)
success, message = authorization_dao.create(authorization)
print(f"github_app_callback: success={success}, message={message}")

installed_repositories = get_installation_repositories(access_token=access_token['token'])
for repo in installed_repositories["repositories"]:
repository_config = RepositoryConfig(repo_name=repo["full_name"], robot_id="", created_at=int(time.time()))
repository_config_dao.create(repository_config)

return RedirectResponse(url=f'{WEB_URL}/github/installed?message={message}', status_code=302)

@router.post("/app/webhook")
Expand Down Expand Up @@ -102,3 +123,25 @@ async def github_app_webhook(
else:
print("Failed, Unsupported GitHub event")
return {"success": False, "message": "Unsupported GitHub event"}

@router.get("/user/organizations")
async def get_user_organizations(user_access_token: Annotated[str | None, Depends(get_user_access_token)] = None):
if user_access_token is None:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Github Login needed")
auth = Auth.Token(token=user_access_token)
g = Github(auth=auth)
user = g.get_user()
orgs = user.get_orgs()

return [org.raw_data for org in orgs]

@router.get("/orgs/{org_id}/repos")
async def get_org_repos(org_id: str, user_access_token: Annotated[str | None, Depends(get_user_access_token)] = None):
if user_access_token is None:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Github Login needed")
auth = Auth.Token(token=user_access_token)
g = Github(auth=auth)
org = g.get_organization(org_id)
repos = org.get_repos()
print(f"repos={repos}")
return [repo.raw_data for repo in repos]

0 comments on commit 3d74fd4

Please sign in to comment.