habulaj commited on
Commit
a54bb56
·
verified ·
1 Parent(s): e955ead

Update routes/users.py

Browse files
Files changed (1) hide show
  1. routes/users.py +9 -17
routes/users.py CHANGED
@@ -2,7 +2,7 @@ import os
2
  import logging
3
  import asyncio
4
  import aiohttp
5
- from fastapi import APIRouter, HTTPException, Header, Depends
6
  from functools import lru_cache
7
  from typing import List, Dict, Any
8
 
@@ -48,7 +48,6 @@ async def verify_admin_token(user_token: str) -> str:
48
  }
49
 
50
  async with aiohttp.ClientSession() as session:
51
- # Verificar se o token é válido
52
  async with session.get(f"{SUPABASE_URL}/auth/v1/user", headers=headers) as response:
53
  if response.status != 200:
54
  raise HTTPException(status_code=401, detail="Token inválido ou expirado")
@@ -58,7 +57,6 @@ async def verify_admin_token(user_token: str) -> str:
58
  if not user_id:
59
  raise HTTPException(status_code=400, detail="ID do usuário não encontrado")
60
 
61
- # Usar cache para verificar se é admin
62
  is_admin = await asyncio.to_thread(get_cached_admin_status, user_id)
63
 
64
  if not is_admin:
@@ -66,13 +64,10 @@ async def verify_admin_token(user_token: str) -> str:
66
 
67
  return user_id
68
 
69
- async def get_recent_users(limit: int = 10) -> List[Dict[str, Any]]:
70
  """Obtém os usuários mais recentes da plataforma"""
71
  try:
72
- # URL para obter os usuários mais recentes, ordenados por data de criação (decrescente)
73
  users_url = f"{SUPABASE_URL}/rest/v1/User?select=name&order=created_at.desc&limit={limit}"
74
-
75
- # Modificar os headers para garantir que a resposta seja tratada como UTF-8
76
  headers = SUPABASE_HEADERS.copy()
77
  headers["Accept"] = "application/json; charset=utf-8"
78
 
@@ -82,7 +77,6 @@ async def get_recent_users(limit: int = 10) -> List[Dict[str, Any]]:
82
  logger.error(f"❌ Erro ao obter usuários recentes: {response.status}")
83
  return []
84
 
85
- # Forçar a decodificação como UTF-8
86
  text = await response.text(encoding='utf-8')
87
  import json
88
  users_data = json.loads(text)
@@ -93,23 +87,21 @@ async def get_recent_users(limit: int = 10) -> List[Dict[str, Any]]:
93
  logger.error(f"❌ Erro ao obter usuários recentes: {str(e)}")
94
  return []
95
 
96
- @router.get("/admin/users/recent")
97
  async def get_recent_users_endpoint(
98
- user_token: str = Header(None, alias="User-key")
 
99
  ):
100
  """
101
- Endpoint para obter os 10 usuários mais recentes da plataforma
102
  """
103
  try:
104
- # Verificar se é um administrador
105
  user_id = await verify_admin_token(user_token)
106
-
107
- # Obter os 10 usuários mais recentes
108
- recent_users = await get_recent_users(10)
109
 
110
  return {
111
- "recent_users": recent_users,
112
- "count": len(recent_users)
113
  }
114
 
115
  except HTTPException as he:
 
2
  import logging
3
  import asyncio
4
  import aiohttp
5
+ from fastapi import APIRouter, HTTPException, Header, Depends, Query
6
  from functools import lru_cache
7
  from typing import List, Dict, Any
8
 
 
48
  }
49
 
50
  async with aiohttp.ClientSession() as session:
 
51
  async with session.get(f"{SUPABASE_URL}/auth/v1/user", headers=headers) as response:
52
  if response.status != 200:
53
  raise HTTPException(status_code=401, detail="Token inválido ou expirado")
 
57
  if not user_id:
58
  raise HTTPException(status_code=400, detail="ID do usuário não encontrado")
59
 
 
60
  is_admin = await asyncio.to_thread(get_cached_admin_status, user_id)
61
 
62
  if not is_admin:
 
64
 
65
  return user_id
66
 
67
+ async def get_recent_users(limit: int = 50) -> List[Dict[str, Any]]:
68
  """Obtém os usuários mais recentes da plataforma"""
69
  try:
 
70
  users_url = f"{SUPABASE_URL}/rest/v1/User?select=name&order=created_at.desc&limit={limit}"
 
 
71
  headers = SUPABASE_HEADERS.copy()
72
  headers["Accept"] = "application/json; charset=utf-8"
73
 
 
77
  logger.error(f"❌ Erro ao obter usuários recentes: {response.status}")
78
  return []
79
 
 
80
  text = await response.text(encoding='utf-8')
81
  import json
82
  users_data = json.loads(text)
 
87
  logger.error(f"❌ Erro ao obter usuários recentes: {str(e)}")
88
  return []
89
 
90
+ @router.get("/admin/users")
91
  async def get_recent_users_endpoint(
92
+ user_token: str = Header(None, alias="User-key"),
93
+ limit: int = Query(50, ge=1, le=100)
94
  ):
95
  """
96
+ Endpoint para obter os usuários mais recentes da plataforma
97
  """
98
  try:
 
99
  user_id = await verify_admin_token(user_token)
100
+ users = await get_recent_users(limit)
 
 
101
 
102
  return {
103
+ "users": users,
104
+ "count": len(users)
105
  }
106
 
107
  except HTTPException as he: