LUISGDUV commited on
Commit
cfe4a47
·
verified ·
1 Parent(s): 6f3695c

Create app.py

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