LUISGDUV commited on
Commit
6175b8b
·
verified ·
1 Parent(s): 0a95d51

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +310 -0
app.py CHANGED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, json, base64, hashlib, secrets, re
2
+ from datetime import datetime, timedelta
3
+ from typing import List
4
+
5
+ import gradio as gr
6
+ from fastapi import UploadFile, File, Form, HTTPException, Header, Depends
7
+ from pydantic import BaseModel
8
+ import requests as rq
9
+
10
+ # ================= CONFIG =================
11
+ GITHUB_TOKEN = os.getenv("GITHUB_TOKEN", "")
12
+ GITHUB_USER = os.getenv("GITHUB_USER", "LUISGDUV")
13
+ GITHUB_REPO = os.getenv("GITHUB_REPO", "Protix-host")
14
+ DB_FOLDER = os.getenv("DB_FOLDER", "ProtixHost Database")
15
+ BASE_DOMAIN = os.getenv("BASE_DOMAIN", "ProtixHost.sytes.net")
16
+ SECRET_KEY = os.getenv("SECRET_KEY", "troque-esta-chave")
17
+ LIMITE_PADRAO = int(os.getenv("LIMITE_PADRAO", "10"))
18
+
19
+ GH_API = "https://api.github.com"
20
+ GH_HEADERS = {
21
+ "Authorization": f"token {GITHUB_TOKEN}",
22
+ "Accept": "application/vnd.github+json",
23
+ }
24
+
25
+ # ================= HELPERS =================
26
+ def hash_pass(pwd):
27
+ salt = secrets.token_hex(16)
28
+ return f"{salt}${hashlib.sha256((salt + pwd).encode()).hexdigest()}"
29
+
30
+ def check_pass(pwd, stored):
31
+ try:
32
+ salt, h = stored.split("$")
33
+ return hashlib.sha256((salt + pwd).encode()).hexdigest() == h
34
+ except Exception:
35
+ return False
36
+
37
+ def create_token(email):
38
+ payload = {"email": email, "exp": (datetime.utcnow() + timedelta(days=30)).isoformat()}
39
+ data = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode()
40
+ sig = hashlib.sha256((data + SECRET_KEY).encode()).hexdigest()[:32]
41
+ return f"{data}.{sig}"
42
+
43
+ def verify_token(token):
44
+ try:
45
+ data, sig = token.split(".")
46
+ if sig != hashlib.sha256((data + SECRET_KEY).encode()).hexdigest()[:32]:
47
+ return None
48
+ p = json.loads(base64.urlsafe_b64decode(data))
49
+ if datetime.fromisoformat(p["exp"]) < datetime.utcnow():
50
+ return None
51
+ return p["email"]
52
+ except Exception:
53
+ return None
54
+
55
+ def auth_user(authorization: str = Header(None)):
56
+ if not authorization or not authorization.startswith("Bearer "):
57
+ raise HTTPException(401, "Não autenticado")
58
+ email = verify_token(authorization[7:])
59
+ if not email:
60
+ raise HTTPException(401, "Token inválido ou expirado")
61
+ return email
62
+
63
+ def gh_get(path):
64
+ return rq.get(
65
+ f"{GH_API}/repos/{GITHUB_USER}/{GITHUB_REPO}/contents/{path}",
66
+ headers=GH_HEADERS, timeout=30
67
+ )
68
+
69
+ def gh_read_json(path):
70
+ r = gh_get(path)
71
+ if r.status_code != 200:
72
+ return None
73
+ return json.loads(base64.b64decode(r.json()["content"]).decode())
74
+
75
+ def gh_put(path, content, message="update"):
76
+ r = gh_get(path)
77
+ sha = r.json().get("sha") if r.status_code == 200 else None
78
+ payload = {"message": message, "content": base64.b64encode(content).decode()}
79
+ if sha:
80
+ payload["sha"] = sha
81
+ return rq.put(
82
+ f"{GH_API}/repos/{GITHUB_USER}/{GITHUB_REPO}/contents/{path}",
83
+ headers=GH_HEADERS, json=payload, timeout=60
84
+ )
85
+
86
+ def gh_delete(path, message="delete"):
87
+ r = gh_get(path)
88
+ if r.status_code != 200:
89
+ return None
90
+ return rq.delete(
91
+ f"{GH_API}/repos/{GITHUB_USER}/{GITHUB_REPO}/contents/{path}",
92
+ headers=GH_HEADERS,
93
+ json={"message": message, "sha": r.json()["sha"]},
94
+ timeout=30
95
+ )
96
+
97
+ def user_path(email):
98
+ safe = email.lower().replace("@", "_at_").replace("/", "_")
99
+ return f"{DB_FOLDER}/usuarios/{safe}"
100
+
101
+ def get_user(email):
102
+ return gh_read_json(f"{user_path(email)}/user.json")
103
+
104
+ def save_user(email, data, msg="update"):
105
+ return gh_put(
106
+ f"{user_path(email)}/user.json",
107
+ json.dumps(data, indent=2, ensure_ascii=False).encode(),
108
+ msg
109
+ )
110
+
111
+ # ================= MODELS =================
112
+ class RegisterBody(BaseModel):
113
+ nome: str
114
+ email: str
115
+ senha: str
116
+
117
+ class LoginBody(BaseModel):
118
+ email: str
119
+ senha: str
120
+
121
+ # ================= GRADIO UI =================
122
+ def _info():
123
+ return (
124
+ "ProtixHost API rodando ✅\n\n"
125
+ "Endpoints:\n"
126
+ "POST /api/register\n"
127
+ "POST /api/login\n"
128
+ "GET /api/me\n"
129
+ "GET /api/sites\n"
130
+ "POST /api/deploy\n"
131
+ "DELETE /api/sites/{nome}\n"
132
+ "GET /api/health\n\n"
133
+ "Docs: /docs"
134
+ )
135
+
136
+ demo = gr.Interface(
137
+ fn=_info,
138
+ inputs=[],
139
+ outputs="text",
140
+ title="ProtixHost API",
141
+ description="Backend rodando. Endpoints em /api/*",
142
+ )
143
+
144
+ # ⚠️ ESSENCIAL: pega o FastAPI interno do Gradio ANTES de lançar
145
+ app = demo.app
146
+
147
+ # ================= ROTAS (prefixo /api) =================
148
+ @app.get("/api/health")
149
+ def health():
150
+ return {
151
+ "status": "ok",
152
+ "service": "ProtixHost API",
153
+ "github": f"{GITHUB_USER}/{GITHUB_REPO}",
154
+ "dominio": BASE_DOMAIN,
155
+ }
156
+
157
+ @app.post("/api/register")
158
+ def register(body: RegisterBody):
159
+ email = body.email.lower().strip()
160
+ if not email or not body.senha or not body.nome:
161
+ raise HTTPException(400, "Dados incompletos")
162
+ if "@" not in email:
163
+ raise HTTPException(400, "E-mail inválido")
164
+ if get_user(email):
165
+ raise HTTPException(400, "E-mail já cadastrado")
166
+
167
+ user = {
168
+ "nome": body.nome,
169
+ "email": email,
170
+ "senha": hash_pass(body.senha),
171
+ "limite_sites": LIMITE_PADRAO,
172
+ "sites": [],
173
+ "criado_em": datetime.utcnow().isoformat(),
174
+ }
175
+ r = save_user(email, user, f"Criar usuário {email}")
176
+ if r.status_code not in (200, 201):
177
+ raise HTTPException(500, f"Erro GitHub: {r.text[:200]}")
178
+
179
+ return {
180
+ "token": create_token(email),
181
+ "user": {
182
+ "nome": user["nome"],
183
+ "email": email,
184
+ "limite_sites": LIMITE_PADRAO,
185
+ "total_sites": 0,
186
+ },
187
+ }
188
+
189
+ @app.post("/api/login")
190
+ def login(body: LoginBody):
191
+ email = body.email.lower().strip()
192
+ user = get_user(email)
193
+ if not user or not check_pass(body.senha, user["senha"]):
194
+ raise HTTPException(401, "E-mail ou senha incorretos")
195
+ return {
196
+ "token": create_token(email),
197
+ "user": {
198
+ "nome": user["nome"],
199
+ "email": email,
200
+ "limite_sites": user.get("limite_sites", LIMITE_PADRAO),
201
+ "total_sites": len(user.get("sites", [])),
202
+ },
203
+ }
204
+
205
+ @app.get("/api/me")
206
+ def me(email: str = Depends(auth_user)):
207
+ user = get_user(email)
208
+ if not user:
209
+ raise HTTPException(404, "Usuário não encontrado")
210
+ return {
211
+ "nome": user["nome"],
212
+ "email": email,
213
+ "limite_sites": user.get("limite_sites", LIMITE_PADRAO),
214
+ "total_sites": len(user.get("sites", [])),
215
+ "sites": user.get("sites", []),
216
+ }
217
+
218
+ @app.get("/api/sites")
219
+ def list_sites(email: str = Depends(auth_user)):
220
+ user = get_user(email)
221
+ if not user:
222
+ raise HTTPException(404, "Usuário não encontrado")
223
+ return {
224
+ "sites": user.get("sites", []),
225
+ "limite": user.get("limite_sites", LIMITE_PADRAO),
226
+ "total": len(user.get("sites", [])),
227
+ }
228
+
229
+ @app.post("/api/deploy")
230
+ async def deploy(
231
+ tipo: str = Form(...),
232
+ nome_site: str = Form(...),
233
+ arquivos: List[UploadFile] = File(...),
234
+ email: str = Depends(auth_user),
235
+ ):
236
+ tipo = tipo.lower().strip()
237
+ if tipo not in ("frontend", "backend", "both"):
238
+ raise HTTPException(400, "Tipo deve ser: frontend, backend ou both")
239
+
240
+ nome_site = nome_site.strip().lower()
241
+ if not re.match(r"^[a-z0-9](?:[a-z0-9-]{1,28}[a-z0-9])?$", nome_site):
242
+ raise HTTPException(400, "Nome inválido (3-30 chars: a-z, 0-9, hífen)")
243
+
244
+ user = get_user(email)
245
+ if not user:
246
+ raise HTTPException(404, "Usuário não encontrado")
247
+
248
+ sites = user.get("sites", [])
249
+ limite = user.get("limite_sites", LIMITE_PADRAO)
250
+
251
+ if len(sites) >= limite:
252
+ raise HTTPException(400, f"Limite de {limite} sites atingido")
253
+ if any(s["nome"] == nome_site for s in sites):
254
+ raise HTTPException(400, "Você já tem um site com esse nome")
255
+
256
+ sub = {"frontend": "frontend", "backend": "backend", "both": "site"}[tipo]
257
+ saved = []
258
+ for f in arquivos:
259
+ raw = await f.read()
260
+ safe = os.path.basename(f.filename or "")
261
+ if not safe:
262
+ continue
263
+ path = f"{user_path(email)}/sites/{nome_site}/{sub}/{safe}"
264
+ r = gh_put(path, raw, f"Upload {safe} -> {nome_site}")
265
+ if r.status_code in (200, 201):
266
+ saved.append(safe)
267
+
268
+ if not saved:
269
+ raise HTTPException(500, "Nenhum arquivo foi salvo")
270
+
271
+ novo = {
272
+ "nome": nome_site,
273
+ "tipo": tipo,
274
+ "url": f"{BASE_DOMAIN}/{nome_site}",
275
+ "arquivos": saved,
276
+ "criado_em": datetime.utcnow().isoformat(),
277
+ }
278
+ sites.append(novo)
279
+ user["sites"] = sites
280
+ save_user(email, user, f"Novo site {nome_site}")
281
+
282
+ return {
283
+ "ok": True,
284
+ "site": novo,
285
+ "url": f"https://{BASE_DOMAIN}/{nome_site}",
286
+ "espera_segundos": 40,
287
+ }
288
+
289
+ @app.delete("/api/sites/{nome_site}")
290
+ def delete_site(nome_site: str, email: str = Depends(auth_user)):
291
+ user = get_user(email)
292
+ if not user:
293
+ raise HTTPException(404, "Usuário não encontrado")
294
+
295
+ sites = user.get("sites", [])
296
+ site = next((s for s in sites if s["nome"] == nome_site), None)
297
+ if not site:
298
+ raise HTTPException(404, "Site não encontrado")
299
+
300
+ sub = {"frontend": "frontend", "backend": "backend", "both": "site"}[site["tipo"]]
301
+ for arq in site.get("arquivos", []):
302
+ gh_delete(f"{user_path(email)}/sites/{nome_site}/{sub}/{arq}")
303
+
304
+ user["sites"] = [s for s in sites if s["nome"] != nome_site]
305
+ save_user(email, user, f"Remover site {nome_site}")
306
+ return {"ok": True}
307
+
308
+ # ================= ⚠️ ESSENCIAL: LAUNCH =================
309
+ # Sem isso o container morre com Exit code 0.
310
+ demo.launch()