-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate_github_client.py
More file actions
271 lines (220 loc) · 8.82 KB
/
create_github_client.py
File metadata and controls
271 lines (220 loc) · 8.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
"""
🚀 CometX - GitHub OAuth App Creator
Creates GitHub OAuth App automatically via API
"""
import requests
import json
import os
from datetime import datetime
# ========================================
# Configuration
# ========================================
GITHUB_TOKEN = os.getenv("GITHUB_TOKEN", "") # Personal Access Token with 'admin:org' or 'write:org' scope
GITHUB_USERNAME = "gratech-sa" # Your GitHub username or organization
# OAuth App Details
APP_NAME = f"CometX-Automation-{datetime.now().strftime('%Y%m%d-%H%M%S')}"
HOMEPAGE_URL = "https://ai.gratech.sa"
CALLBACK_URL = "http://localhost:3000/callback"
DESCRIPTION = "CometX Automation Bot - GitHub OAuth Client"
# ========================================
# Functions
# ========================================
def create_oauth_app():
"""Create GitHub OAuth App via API"""
if not GITHUB_TOKEN:
print("❌ Error: GITHUB_TOKEN not set!")
print("\n📝 To create token:")
print("1. Go to: https://github.com/settings/tokens")
print("2. Click 'Generate new token (classic)'")
print("3. Select scopes: write:org, admin:org")
print("4. Copy token and set: set GITHUB_TOKEN=your_token_here")
return None
print("🚀 Creating GitHub OAuth App...")
print(f"📛 Name: {APP_NAME}")
print(f"🌐 Homepage: {HOMEPAGE_URL}")
print(f"🔗 Callback: {CALLBACK_URL}\n")
url = f"https://api.github.com/user/applications/oauth2_authorizations"
# Note: GitHub API doesn't have direct endpoint to create OAuth Apps
# We need to use the Settings UI or GitHub Apps API instead
# Let's create a GitHub App instead (more powerful)
print("⚠️ Note: Creating GitHub App (more powerful than OAuth App)")
app_url = "https://api.github.com/user/repos" # This is for testing API access
headers = {
"Authorization": f"token {GITHUB_TOKEN}",
"Accept": "application/vnd.github+json"
}
# Test token first
test_response = requests.get("https://api.github.com/user", headers=headers)
if test_response.status_code != 200:
print(f"❌ Token validation failed: {test_response.status_code}")
print(f"Response: {test_response.text}")
return None
user_data = test_response.json()
print(f"✅ Authenticated as: {user_data['login']}\n")
# GitHub Apps creation endpoint
create_url = "https://api.github.com/user/apps"
app_data = {
"name": APP_NAME,
"url": HOMEPAGE_URL,
"hook_attributes": {
"url": f"{HOMEPAGE_URL}/webhook"
},
"redirect_url": CALLBACK_URL,
"description": DESCRIPTION,
"public": False,
"default_permissions": {
"issues": "write",
"contents": "write",
"pull_requests": "write",
"metadata": "read"
},
"default_events": ["push", "pull_request", "issues"]
}
print("🔄 Sending request to GitHub API...")
response = requests.post(create_url, headers=headers, json=app_data)
if response.status_code in [201, 200]:
app = response.json()
print("\n✅ GitHub App Created Successfully!\n")
print("=" * 60)
print(f"📛 App Name: {app.get('name')}")
print(f"🆔 App ID: {app.get('id')}")
print(f"🔑 Client ID: {app.get('client_id')}")
print(f"🌐 URL: {app.get('html_url')}")
print("=" * 60)
print("\n📝 Next Steps:")
print("1. Go to app settings to generate Client Secret")
print("2. Download private key (.pem file)")
print(f"3. Install app: {app.get('html_url')}/installations/new")
# Save to file
with open("github_app_details.json", "w") as f:
json.dump(app, f, indent=2)
print("\n💾 Details saved to: github_app_details.json")
return app
else:
print(f"\n❌ Failed to create app: {response.status_code}")
print(f"Response: {response.text}")
# Try alternative: Generate installation guide
print("\n" + "=" * 60)
print("🔧 MANUAL SETUP REQUIRED")
print("=" * 60)
print("\nGitHub API doesn't allow direct OAuth App creation.")
print("Please follow these steps:\n")
print("Option A: Create OAuth App (Simple)")
print("-" * 40)
print("1. Go to: https://github.com/settings/developers")
print("2. Click 'OAuth Apps' → 'New OAuth App'")
print(f"3. Application name: {APP_NAME}")
print(f"4. Homepage URL: {HOMEPAGE_URL}")
print(f"5. Authorization callback URL: {CALLBACK_URL}")
print("6. Click 'Register application'")
print("7. Copy Client ID and generate Client Secret\n")
print("Option B: Create GitHub App (Advanced)")
print("-" * 40)
print("1. Go to: https://github.com/settings/apps/new")
print(f"2. GitHub App name: {APP_NAME}")
print(f"3. Homepage URL: {HOMEPAGE_URL}")
print(f"4. Callback URL: {CALLBACK_URL}")
print("5. Set permissions (Issues, Contents, PRs)")
print("6. Create app → Download private key")
print("7. Install app on your repos\n")
return None
def generate_oauth_script(client_id, client_secret):
"""Generate Flask OAuth script"""
script = f'''"""
CometX - GitHub OAuth Integration
Generated: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
"""
from flask import Flask, redirect, request, session, url_for
import requests
import secrets
import os
# Configuration
CLIENT_ID = "{client_id}"
CLIENT_SECRET = "{client_secret}"
AUTHORIZE_URL = "https://github.com/login/oauth/authorize"
TOKEN_URL = "https://github.com/login/oauth/access_token"
USER_API = "https://api.github.com/user"
app = Flask(__name__)
app.secret_key = secrets.token_hex(16)
@app.route("/")
def index():
return \'\'\\'
<h1>🚀 CometX GitHub OAuth</h1>
<a href="/login">تسجيل دخول GitHub</a>
\'\'\'
@app.route("/login")
def login():
state = secrets.token_urlsafe(16)
session["oauth_state"] = state
params = {{
"client_id": CLIENT_ID,
"redirect_uri": url_for("callback", _external=True),
"scope": "read:user user:email repo",
"state": state
}}
query = "&".join([f"{{k}}={{v}}" for k, v in params.items()])
return redirect(f"{{AUTHORIZE_URL}}?{{query}}")
@app.route("/callback")
def callback():
state = request.args.get("state")
code = request.args.get("code")
if state != session.get("oauth_state"):
return "❌ Invalid state", 400
headers = {{"Accept": "application/json"}}
data = {{
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
"code": code,
"redirect_uri": url_for("callback", _external=True)
}}
token_response = requests.post(TOKEN_URL, headers=headers, data=data).json()
access_token = token_response.get("access_token")
if not access_token:
return f"❌ Token error: {{token_response}}", 400
user_response = requests.get(
USER_API,
headers={{"Authorization": f"token {{access_token}}"}}
).json()
return f\'\'\\'
<h1>✅ تم الدخول بنجاح!</h1>
<p>المستخدم: {{user_response.get("login")}}</p>
<p>البريد: {{user_response.get("email")}}</p>
<p>Token: <code>{{access_token[:20]}}...</code></p>
\'\'\'
if __name__ == "__main__":
print("🚀 Starting CometX OAuth Server...")
print("📍 Open: http://localhost:3000")
app.run(port=3000, debug=True)
'''
with open("github_oauth_server.py", "w", encoding="utf-8") as f:
f.write(script)
print("✅ OAuth server script created: github_oauth_server.py")
print("\n🚀 To run:")
print(" python github_oauth_server.py")
# ========================================
# Main Execution
# ========================================
if __name__ == "__main__":
print("=" * 60)
print("🚀 CometX - GitHub Client Creator")
print("=" * 60)
print()
# Check if token is provided
if not GITHUB_TOKEN:
print("⚠️ No GITHUB_TOKEN found in environment")
print("\n📝 Quick Setup:")
print("1. Get token from: https://github.com/settings/tokens")
print("2. Run: set GITHUB_TOKEN=your_token_here")
print("3. Run this script again: python create_github_client.py")
print("\n" + "=" * 60)
# Provide manual instructions anyway
create_oauth_app()
else:
# Try to create via API
result = create_oauth_app()
if result:
# Generate OAuth script with the client ID
client_id = result.get("client_id")
if client_id:
generate_oauth_script(client_id, "YOUR_CLIENT_SECRET_HERE")
print("\n✅ Done!")