Spaces:
Sleeping
Sleeping
File size: 6,030 Bytes
2255148 43775f0 b0e428c 1d45c43 4ebdc27 43c35ee 2255148 4ebdc27 2255148 43775f0 2255148 b0e428c 5a7e7d1 43c35ee 5a7e7d1 43c35ee 5a7e7d1 43c35ee 5a7e7d1 43c35ee 5a7e7d1 0869c00 b0e428c 2255148 43c35ee 2255148 852db71 43775f0 852db71 43775f0 b0e428c 43775f0 b0e428c 43775f0 b0e428c 43775f0 b0e428c 2255148 43775f0 f4afa6c 13d0482 f4afa6c 13d0482 d3fa0d6 0869c00 d3fa0d6 0869c00 d93063e d3fa0d6 ab2a43a dae8296 43c35ee 5a7e7d1 dae8296 4ba76dd dae8296 6dccafb 43c35ee 5a7e7d1 6dccafb a46d887 c801353 e1b3bdb c801353 e1b3bdb c801353 a46d887 ab2a43a | 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 | from flask import Flask, request, jsonify, abort
from flask_cors import CORS
from supabase_client import supabase
import uuid
import secrets
from datetime import datetime, timedelta
import pytz
import os
from jose import jwt
import requests
from functools import wraps
SUPABASE_URL = os.environ["SUPABASE_URL"]
app = Flask(__name__)
CORS(app)
def require_role(role):
def decorator(f):
@wraps(f)
def decorated(*args, **kwargs):
if not hasattr(request, "user"):
return jsonify({"error": "Usuário não autenticado"}), 401
user_role = request.user.get("role")
if user_role != role:
return jsonify({"error": "Permissão negada"}), 403
return f(*args, **kwargs)
return decorated
return decorator
def login_required(f):
@wraps(f)
def decorated(*args, **kwargs):
auth_header = request.headers.get("Authorization")
if not auth_header:
return jsonify({"error": "Token de usuário ausente"}), 401
try:
token = auth_header.split(" ")[1]
# valida JWT
user = supabase.auth.get_user(token)
user_id = user.user.id
# busca dados do usuário na tabela users
result = supabase.table("users") \
.select("id, nome, role") \
.eq("id", user_id) \
.single() \
.execute()
if not result.data:
return jsonify({"error": "Usuário não registrado"}), 403
# anexamos ao request
request.user = result.data
except Exception as e:
print("Erro auth:", e)
return jsonify({"error": "Token inválido"}), 401
return f(*args, **kwargs)
return decorated
def auditoria(processo_id,result,reason):
ip = request.headers.get("X-Forwarded-For", request.remote_addr)
user_agent = request.headers.get("User-Agent")
supabase.table("acessos").insert({
"processo_id": processo_id,
"ip": ip,
"user_agent": user_agent,
"success": result,
"reason": reason
}).execute()
@app.route("/api/processo", methods=["POST"])
@login_required
def criar_processo():
tz = pytz.timezone("America/Sao_Paulo")
payload = request.get_json()
tipo = payload.get("viewType")
data = payload.get("data")
nome_arquivo = payload.get("nome_arquivo")
token = secrets.token_urlsafe(16)
expires_at = datetime.now(tz) + timedelta(hours=48) # Expira em 48 horas
if not payload:
abort(400, "JSON inválido")
if tipo not in ["homologacao", "classificacao"]:
abort(400, "Tipo inválido")
if not isinstance(data, list):
abort(400, "Payload inválido")
result = supabase.table("processos").insert({
"tipo": tipo,
"edital": nome_arquivo,
"payload": data,
"token": token,
"expires_at": expires_at.isoformat()
}).execute()
processo_id = result.data[0]["id"]
return jsonify({
"id": processo_id,
"token": token
})
@app.route("/api/processo/<processo_id>", methods=["GET"])
def obter_processo(processo_id):
result = supabase.table("processos") \
.select("tipo, edital, payload, decisions, token, created_at, expires_at, last_mod") \
.eq("id", processo_id) \
.single() \
.execute()
processo = result.data
now = datetime.now(pytz.timezone("America/Sao_Paulo"))
token = request.args.get("t")
if not token:
msg = "Token ausente"
auditoria(processo_id,False,msg)
abort(403, msg)
if not result.data:
msg = "Dados Inválidos"
auditoria(processo_id,False,msg)
abort(404, msg)
if processo["token"] != token:
msg = "Token inválido"
auditoria(processo_id,False,msg)
abort(403, msg)
if processo["expires_at"] and now > datetime.fromisoformat(processo["expires_at"]):
msg = "Link expirado"
auditoria(processo_id,False,msg)
abort(410, msg)
msg = "Dados do processo carregados com sucesso"
auditoria(processo_id,True,msg)
return jsonify({
"tipo": processo["tipo"],
"edital": processo["edital"],
"payload": processo["payload"],
"decisions": processo["decisions"],
})
@app.route("/api/admin/processos", methods=["GET"])
@login_required
@require_role("admin")
def listar_processos():
result = supabase.table("processos") \
.select("""
id,
tipo,
edital,
token,
created_at,
expires_at,
last_mod,
acessos:acessos(count)
""") \
.order("created_at", desc=True) \
.execute()
return jsonify(result.data)
@app.route("/api/admin/revogar/<processo_id>", methods=["POST"])
@login_required
@require_role("admin")
def revogar_processo(processo_id):
token = request.headers.get("X-Admin-Token")
if token != os.environ.get("ADMIN_TOKEN"):
abort(403)
supabase.table("processos") \
.update({"expires_at": datetime.now(pytz.timezone("America/Sao_Paulo")).isoformat()}) \
.eq("id", processo_id) \
.execute()
return jsonify({"ok": True})
@app.route("/api/me", methods=["GET"])
def me():
auth_header = request.headers.get("Authorization")
if not auth_header:
return jsonify({"error": "Sem token"}), 401
token = auth_header.split(" ")[1]
try:
user = supabase.auth.get_user(token)
except Exception as e:
print("Erro token:", e)
return jsonify({"error": "Token inválido"}), 401
user_id = user.user.id
result = supabase.table("users") \
.select("id, nome, role") \
.eq("id", user_id) \
.single() \
.execute()
return jsonify(result.data)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=7860) |