from flask import Blueprint, render_template, redirect, url_for, flash, jsonify, current_app from flask_login import login_user, login_required, current_user from models import db, User from forms import SignupForm from altcha_utils import get_altcha main = Blueprint('main', __name__) @main.route('/altcha/challenge') def altcha_challenge(): """Generate a new Altcha challenge for the signup form.""" altcha = get_altcha(current_app.config['ALTCHA_HMAC_KEY']) challenge = altcha.create_challenge() return jsonify(challenge) @main.route('/') def index(): if current_user.is_authenticated: return redirect(url_for('main.dashboard')) return redirect(url_for('main.signup')) @main.route('/signup', methods=['GET', 'POST']) def signup(): if current_user.is_authenticated: return redirect(url_for('main.dashboard')) form = SignupForm() if form.validate_on_submit(): # Verify Altcha solution altcha = get_altcha(current_app.config['ALTCHA_HMAC_KEY']) if not altcha.verify_solution(form.altcha.data): flash('CAPTCHA verification failed. Please try again.', 'error') return render_template('signup.html', form=form) # Check if user already exists existing_user = User.query.filter_by(email=form.email.data.lower()).first() if existing_user: flash('An account with this email already exists.', 'error') return render_template('signup.html', form=form) # Create new user user = User(email=form.email.data.lower()) user.set_password(form.password.data) db.session.add(user) db.session.commit() # Auto-login after signup login_user(user) flash('Account created successfully!', 'success') return redirect(url_for('main.dashboard')) return render_template('signup.html', form=form) @main.route('/dashboard') @login_required def dashboard(): return render_template('dashboard.html')