Files
2026-01-17 11:40:17 +01:00

123 lines
5.2 KiB
Python

from flask import Blueprint, render_template, request, jsonify, session, redirect, url_for
from werkzeug.security import generate_password_hash, check_password_hash
import sqlite3
import json
import secrets
import random
import os
from config import MAIN_DB, THEMES_DIR
from utils.theme_engine import get_themes_by_rubro, get_theme_config
auth_bp = Blueprint('auth', __name__)
@auth_bp.route('/register', methods=['GET', 'POST'])
def register():
"""Registro - Sistema Simple y Profesional"""
if request.method == 'POST':
try:
data = request.get_json() if request.is_json else (request.form.to_dict() if request.form else {})
if not data:
return jsonify({'success': False, 'error': 'Sin datos'}), 400
email = str(data.get('email', '')).strip()
password = str(data.get('password', '')).strip()
plan = str(data.get('plan', 'base'))
rubro = str(data.get('rubro', 'gimnasio'))
if not email or '@' not in email:
return jsonify({'success': False, 'error': 'Email inválido'}), 400
if not password:
return jsonify({'success': False, 'error': 'Contraseña requerida'}), 400
conn = sqlite3.connect(MAIN_DB)
c = conn.cursor()
try:
c.execute('INSERT INTO users (email, password, plan, rubro) VALUES (?, ?, ?, ?)',
(email, generate_password_hash(password), plan, rubro))
user_id = c.lastrowid
except sqlite3.IntegrityError:
conn.close()
return jsonify({'success': False, 'error': 'Email ya existe'}), 400
theme = 'default'
themes_by_rubro = get_themes_by_rubro(rubro)
if themes_by_rubro:
theme = random.choice(list(themes_by_rubro.keys()))
theme_config = get_theme_config(theme)
default_colors = {'primary': '#c94d4d', 'secondary': '#d97757', 'accent': '#f4a261', 'text': '#2c2c2c'}
default_typography = {'font_family': 'Roboto'}
if theme_config:
default_colors = theme_config.get('colors', default_colors)
default_typography = theme_config.get('typography', default_typography)
content = json.dumps({
'site_name': email.split('@')[0].title() + ' Site',
'hero_title': 'Bienvenido',
'colors': default_colors,
'typography': default_typography
})
slug = f'site-{secrets.token_hex(4)}'
c.execute('INSERT INTO sites (user_id, slug, theme, content_json) VALUES (?, ?, ?, ?)',
(user_id, slug, theme, content))
site_id = c.lastrowid
# Menús por defecto
for loc, title, url, order in [('header', 'Inicio', '#inicio', 0), ('footer', 'Contacto', '#contacto', 1)]:
c.execute('INSERT INTO menus (user_id, site_id, location, title, url, order_index) VALUES (?, ?, ?, ?, ?, ?)',
(user_id, site_id, loc, title, url, order))
conn.commit()
conn.close()
return jsonify({'success': True, 'message': 'Registro exitoso. Inicia sesión.', 'redirect': url_for('auth.login')})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
return render_template('register.html', plan=request.args.get('plan', 'base'), rubro=request.args.get('rubro', 'gimnasio'))
@auth_bp.route('/login', methods=['GET', 'POST'])
def login():
"""Login"""
if request.method == 'POST':
try:
data = request.get_json()
email = data.get('email')
password = data.get('password')
conn = sqlite3.connect(MAIN_DB)
c = conn.cursor()
c.execute('SELECT id, password FROM users WHERE email = ?', (email,))
user = c.fetchone()
conn.close()
if user and check_password_hash(user[1], password):
session['user_id'] = user[0]
# Buscar sitio para redirigir
conn = sqlite3.connect(MAIN_DB)
c = conn.cursor()
c.execute('SELECT id FROM sites WHERE user_id = ? LIMIT 1', (user[0],))
site = c.fetchone()
conn.close()
redirect_url = url_for('customizer.customizer_view', site_id=site[0]) if site else url_for('dashboard.dashboard_view')
return jsonify({'success': True, 'redirect': redirect_url})
return jsonify({'success': False, 'error': 'Credenciales inválidas'}), 401
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
return render_template('login.html')
@auth_bp.route('/logout')
def logout():
session.pop('user_id', None)
return redirect(url_for('public.landing'))