-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.py
More file actions
91 lines (70 loc) · 2.93 KB
/
auth.py
File metadata and controls
91 lines (70 loc) · 2.93 KB
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
from flask import Blueprint, request, jsonify, session
from src.models.saas_models import db, Admin, Business, BusinessType, BusinessStatus
from werkzeug.security import check_password_hash
from datetime import datetime
auth_bp = Blueprint('auth', __name__)
@auth_bp.route('/login', methods=['POST'])
def login():
"""Endpoint para login de administradores"""
try:
data = request.get_json()
email = data.get('email')
password = data.get('password')
if not email or not password:
return jsonify({'error': 'Email e senha são obrigatórios'}), 400
# Buscar administrador no banco
admin = Admin.query.filter_by(email=email).first()
if not admin or not admin.check_password(password):
return jsonify({'error': 'Credenciais inválidas'}), 401
# Salvar sessão (em produção, usar JWT)
session['admin_id'] = admin.id
session['admin_email'] = admin.email
return jsonify({
'message': 'Login realizado com sucesso',
'admin': admin.to_dict()
}), 200
except Exception as e:
return jsonify({'error': str(e)}), 500
@auth_bp.route('/logout', methods=['POST'])
def logout():
"""Endpoint para logout"""
session.clear()
return jsonify({'message': 'Logout realizado com sucesso'}), 200
@auth_bp.route('/register', methods=['POST'])
def register():
"""Endpoint para registro de novos administradores"""
try:
data = request.get_json()
name = data.get('name')
email = data.get('email')
password = data.get('password')
if not all([name, email, password]):
return jsonify({'error': 'Nome, email e senha são obrigatórios'}), 400
# Verificar se email já existe
if Admin.query.filter_by(email=email).first():
return jsonify({'error': 'Email já cadastrado'}), 409
# Criar novo administrador
admin = Admin(name=name, email=email)
admin.set_password(password)
db.session.add(admin)
db.session.commit()
return jsonify({
'message': 'Administrador criado com sucesso',
'admin': admin.to_dict()
}), 201
except Exception as e:
db.session.rollback()
return jsonify({'error': str(e)}), 500
@auth_bp.route('/me', methods=['GET'])
def get_current_admin():
"""Endpoint para obter dados do administrador logado"""
try:
admin_id = session.get('admin_id')
if not admin_id:
return jsonify({'error': 'Não autenticado'}), 401
admin = Admin.query.get(admin_id)
if not admin:
return jsonify({'error': 'Administrador não encontrado'}), 404
return jsonify({'admin': admin.to_dict()}), 200
except Exception as e:
return jsonify({'error': str(e)}), 500