""" Authentifizierungs-Views """ from flask import Blueprint, render_template, request, redirect, url_for, session, flash, g, current_app from cmbnet.db import get_db from cmbnet.auth import verify_password auth_bp = Blueprint('auth', __name__) @auth_bp.before_request def load_tenant(): """Lädt Tenant aus URL""" tenant_code = request.view_args.get('tenant') if tenant_code: db = get_db() tenant = db.execute('SELECT * FROM tenants WHERE code = ?', (tenant_code,)).fetchone() if not tenant: flash('Ungültiger Mandant', 'error') return redirect(url_for('auth.login_select', tenant=current_app.config['DEFAULT_TENANT'])) g.tenant_id = tenant['id'] g.tenant_code = tenant['code'] @auth_bp.route('/login', methods=['GET', 'POST']) def login(**kwargs): """Login-View""" tenant_code = g.tenant_code next_url = request.args.get('next') if request.method == 'POST': username = request.form.get('username', '').strip() password = request.form.get('password', '') tenant_selected = request.form.get('tenant', tenant_code) db = get_db() # Überprüfe Account für den Tenant account = db.execute( 'SELECT a.*, t.code as tenant_code FROM accounts a JOIN tenants t ON a.tenant_id = t.id WHERE a.name = ? AND t.code = ?', (username, tenant_selected) ).fetchone() if account and verify_password(account['password_hash'], password): # Login erfolgreich session['account_id'] = account['id'] session['tenant_id'] = account['tenant_id'] session['tenant_code'] = account['tenant_code'] session['role'] = account['role'] session['username'] = account['name'] # Weiterleitung if next_url: return redirect(next_url) # Rollenbasierte Weiterleitung role = account['role'] if role == 'Administrator': return redirect(url_for('admin.dashboard', tenant=tenant_selected)) elif role == 'Dispatcher': return redirect(url_for('views.dispatcher', tenant=tenant_selected)) elif role == 'Beobachter': return redirect(url_for('views.beobachter', tenant=tenant_selected)) elif role == 'Gruppe': return redirect(url_for('views.gruppen', tenant=tenant_selected)) else: return redirect(url_for('views.oeffentlich', tenant=tenant_selected)) else: flash('Ungültiger Benutzername oder Passwort', 'error') return render_template('login.html', tenant_code=tenant_code) @auth_bp.route('/login/select') def login_select(**kwargs): """Mandantenauswahl für Login""" return render_template('login_select.html') @auth_bp.route('/logout') def logout(**kwargs): """Logout""" session.clear() tenant_code = g.get('tenant_code') or request.args.get('tenant') or 'RV' return redirect(url_for('auth.login', tenant=tenant_code))