Novo Ambiente | Atualização 3
This commit is contained in:
parent
d2c8745c45
commit
02ddd529be
|
|
@ -8,7 +8,7 @@ from .routes.auth import auth
|
||||||
from .routes.perfil import perfil
|
from .routes.perfil import perfil
|
||||||
from .routes.montagem import montagem
|
from .routes.montagem import montagem
|
||||||
from .routes.zabbix import zabbix
|
from .routes.zabbix import zabbix
|
||||||
from .routes.zammad import zammad
|
from .routes.integrator import zammad
|
||||||
# Inicializa o MySQL
|
# Inicializa o MySQL
|
||||||
mysql = MySQL()
|
mysql = MySQL()
|
||||||
|
|
||||||
|
|
|
||||||
Binary file not shown.
Binary file not shown.
|
|
@ -25,7 +25,7 @@ class Config:
|
||||||
LDAP_PASSWORD = os.getenv('LDAP_PASSWORD', '123Mudar') # Senha do usuário LDAP
|
LDAP_PASSWORD = os.getenv('LDAP_PASSWORD', '123Mudar') # Senha do usuário LDAP
|
||||||
|
|
||||||
#Api Zammad
|
#Api Zammad
|
||||||
zammad_api_url = 'http://10.10.253.59/api/v1'
|
zammad_api_url = 'http://zammad.itguys.com.br/api/v1'
|
||||||
zammad_token = 'L081vJ19kood2uDlTSSt59LWBaewT9-a-MH_VKno8RY'
|
zammad_token = 'L081vJ19kood2uDlTSSt59LWBaewT9-a-MH_VKno8RY'
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
|
@ -81,7 +81,6 @@ def login():
|
||||||
# Separar nome de usuário e domínio
|
# Separar nome de usuário e domínio
|
||||||
try:
|
try:
|
||||||
username, domain = username_full.split('@')
|
username, domain = username_full.split('@')
|
||||||
print(f" Domínio extraído: {domain}") # <-- Adiciona este print
|
|
||||||
except ValueError:
|
except ValueError:
|
||||||
return jsonify({'msg': 'Formato de usuário inválido. Use "usuario@dominio.com".'}), 400
|
return jsonify({'msg': 'Formato de usuário inválido. Use "usuario@dominio.com".'}), 400
|
||||||
|
|
||||||
|
|
@ -91,13 +90,11 @@ def login():
|
||||||
cur.execute("SELECT idempresa, ip_dominio FROM empresa WHERE dominio = %s", (domain,))
|
cur.execute("SELECT idempresa, ip_dominio FROM empresa WHERE dominio = %s", (domain,))
|
||||||
empresa_result = cur.fetchone()
|
empresa_result = cur.fetchone()
|
||||||
|
|
||||||
|
|
||||||
if not empresa_result:
|
if not empresa_result:
|
||||||
return jsonify({'msg': 'Domínio não encontrado no banco de dados'}), 404
|
return jsonify({'msg': 'Domínio não encontrado no banco de dados'}), 404
|
||||||
|
|
||||||
id_empresa, ip_dominio = empresa_result
|
id_empresa, ip_dominio = empresa_result
|
||||||
|
|
||||||
|
|
||||||
# Verificar se o usuário está associado à empresa no MySQL
|
# Verificar se o usuário está associado à empresa no MySQL
|
||||||
with mysql.connection.cursor() as cur:
|
with mysql.connection.cursor() as cur:
|
||||||
cur.execute("SELECT empresa_id, dominio FROM view_usuario_empresa WHERE usuario = %s AND dominio = %s", (username, domain))
|
cur.execute("SELECT empresa_id, dominio FROM view_usuario_empresa WHERE usuario = %s AND dominio = %s", (username, domain))
|
||||||
|
|
@ -111,8 +108,8 @@ def login():
|
||||||
return jsonify({'msg': 'Erro no banco de dados'}), 500
|
return jsonify({'msg': 'Erro no banco de dados'}), 500
|
||||||
|
|
||||||
# Conexão LDAP com autenticação
|
# Conexão LDAP com autenticação
|
||||||
ldap_server = f'ldap://{"itguys.com.br:389"}' # Altere para 'ldaps://{ip_dominio}:636' se LDAPS for usado
|
ldap_server = f'ldap://{"itguys.com.br:389"}'
|
||||||
ldap_user = f'{domain}\\{username}' # Formato DOMAIN\username
|
ldap_user = f'{domain}\\{username}'
|
||||||
|
|
||||||
try:
|
try:
|
||||||
server = ldap3.Server(ldap_server, get_info=ldap3.ALL)
|
server = ldap3.Server(ldap_server, get_info=ldap3.ALL)
|
||||||
|
|
@ -123,17 +120,16 @@ def login():
|
||||||
authentication=ldap3.SIMPLE
|
authentication=ldap3.SIMPLE
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
if conn.bind():
|
if conn.bind():
|
||||||
token = jwt.encode({
|
token = jwt.encode({
|
||||||
'user': username_full,
|
'user': username_full,
|
||||||
|
'domain': domain, # Incluindo o domínio no payload
|
||||||
'exp': datetime.utcnow() + timedelta(hours=1)
|
'exp': datetime.utcnow() + timedelta(hours=1)
|
||||||
}, current_app.config['SECRET_KEY'], algorithm="HS256")
|
}, current_app.config['SECRET_KEY'], algorithm="HS256")
|
||||||
|
|
||||||
conn.unbind()
|
conn.unbind()
|
||||||
logging.info(f"Login bem-sucedido para usuário: {username_full}")
|
logging.info(f"Login bem-sucedido para usuário: {username_full}")
|
||||||
return jsonify({'msg': 'Login bem-sucedido', 'token': token}), 200
|
return jsonify({'msg': 'Login bem-sucedido', 'token': token, 'domain': domain}), 200
|
||||||
else:
|
else:
|
||||||
conn.unbind()
|
conn.unbind()
|
||||||
logging.warning(f"Falha na autenticação LDAP para o usuário: {username_full}")
|
logging.warning(f"Falha na autenticação LDAP para o usuário: {username_full}")
|
||||||
|
|
@ -151,6 +147,3 @@ def login():
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,19 @@
|
||||||
|
from flask import Blueprint, jsonify, request
|
||||||
|
from .zammad import listar_tickets # Importa a função do zammad.py
|
||||||
|
from .auth import token_required # Importa o decorador de autenticação
|
||||||
|
|
||||||
|
zammad = Blueprint('zammad',__name__)
|
||||||
|
|
||||||
|
@zammad.route('/tickets', methods=['GET'])
|
||||||
|
@token_required
|
||||||
|
def tickets(data):
|
||||||
|
# O decorador token_required já valida o token e retorna os dados do payload
|
||||||
|
domain = data.get('domain') # Extraído do token
|
||||||
|
|
||||||
|
if not domain:
|
||||||
|
return jsonify({"error": "Domínio não encontrado no token"}), 400
|
||||||
|
|
||||||
|
tickets, status_code = listar_tickets(domain)
|
||||||
|
return jsonify(tickets), status_code
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -1,41 +1,39 @@
|
||||||
from flask import Blueprint, jsonify, request
|
|
||||||
import requests
|
import requests
|
||||||
|
|
||||||
# Blueprint para rotas relacionadas ao Zammad
|
base_url = "http://zammad.itguys.com.br/api/v1"
|
||||||
zammad = Blueprint('zammad', __name__)
|
zammad_token = "kT0IXO8aVhPoTLcMRNL290rqd9jbRhhM0zf8MgBo3n00NLChToSU6rOGnMgWA0M2"
|
||||||
|
|
||||||
# Configurações da API do Zammad
|
def listar_tickets(domain):
|
||||||
base_url = "http://10.10.253.59/api/v1" # URL base da API Zammad
|
|
||||||
zammad_token = "kT0IXO8aVhPoTLcMRNL290rqd9jbRhhM0zf8MgBo3n00NLChToSU6rOGnMgWA0M2" # Token da API Zammad
|
|
||||||
|
|
||||||
# Rota para listar tickets
|
|
||||||
@zammad.route('/tickets', methods=['GET'])
|
|
||||||
def listar_tickets():
|
|
||||||
try:
|
try:
|
||||||
# Cabeçalho de autenticação para a API Zammad
|
|
||||||
headers = {
|
headers = {
|
||||||
"Authorization": f"Token token={zammad_token}",
|
"Authorization": f"Token token={zammad_token}",
|
||||||
"Content-Type": "application/json"
|
"Content-Type": "application/json"
|
||||||
}
|
}
|
||||||
|
url = f"{base_url}/tickets?domain={domain}"
|
||||||
|
response = requests.get(url, headers=headers, timeout=10)
|
||||||
|
|
||||||
# Faz a requisição para a API Zammad
|
|
||||||
url = f"{base_url}/tickets"
|
|
||||||
response = requests.get(url, headers=headers, timeout=10) # Timeout adicionado para evitar requisições travadas
|
|
||||||
|
|
||||||
# Processa a resposta
|
|
||||||
if response.status_code == 200:
|
if response.status_code == 200:
|
||||||
tickets = response.json()
|
tickets = response.json()
|
||||||
return jsonify(tickets), 200
|
tickets_filtrados = [
|
||||||
|
{
|
||||||
|
"title": ticket.get("title"),
|
||||||
|
"type": ticket.get("type"),
|
||||||
|
"created_at": ticket.get("created_at"),
|
||||||
|
"close_at": ticket.get("close_at"),
|
||||||
|
"state_id": ticket.get("state_id"),
|
||||||
|
"pending_time": ticket.get("pending_time"),
|
||||||
|
"number": ticket.get("number"),
|
||||||
|
"organization_id": ticket.get("organization_id"),
|
||||||
|
"customer_id": ticket.get("customer_id"),
|
||||||
|
}
|
||||||
|
for ticket in tickets
|
||||||
|
]
|
||||||
|
return tickets_filtrados, 200
|
||||||
else:
|
else:
|
||||||
return jsonify({
|
return {"error": f"Erro ao buscar tickets: {response.status_code}", "details": response.text}, response.status_code
|
||||||
"error": f"Erro ao buscar tickets: {response.status_code}",
|
|
||||||
"details": response.text
|
|
||||||
}), response.status_code
|
|
||||||
|
|
||||||
except requests.exceptions.RequestException as e:
|
except requests.exceptions.RequestException as e:
|
||||||
# Captura problemas de conexão ou requisição
|
return {"error": "Erro na requisição à API", "details": str(e)}, 500
|
||||||
return jsonify({"error": "Erro na requisição à API", "details": str(e)}), 500
|
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
# Captura quaisquer outros erros inesperados
|
return {"error": "Erro interno ao processar a solicitação", "details": str(e)}, 500
|
||||||
return jsonify({"error": "Erro interno ao processar a solicitação", "details": str(e)}), 500
|
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue