31494c9dab
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
55 lines
1.7 KiB
Python
55 lines
1.7 KiB
Python
from flask import request, jsonify
|
|
from werkzeug.security import check_password_hash
|
|
from datetime import datetime, timedelta, timezone
|
|
import jwt
|
|
|
|
from util.logger import logger
|
|
from util.db_pool import get_connection
|
|
from util.limiter import limiter
|
|
from auth.token import SECRET_KEY
|
|
|
|
|
|
@limiter.limit("10 per minute")
|
|
def login_route():
|
|
data = request.get_json(silent=True) or {}
|
|
username = data.get('username', '').strip()
|
|
password = data.get('password', '')
|
|
|
|
if not username or not password:
|
|
return jsonify({"message": "Username und Passwort erforderlich"}), 400
|
|
|
|
if not SECRET_KEY:
|
|
logger.error("Login blocked: SECRET_KEY is not configured.")
|
|
return jsonify({"message": "Server misconfigured"}), 500
|
|
|
|
try:
|
|
conn = get_connection()
|
|
cursor = conn.cursor(dictionary=True)
|
|
cursor.execute("SELECT * FROM users WHERE username = %s", (username,))
|
|
user = cursor.fetchone()
|
|
cursor.close()
|
|
conn.close()
|
|
|
|
if user and check_password_hash(user['password'], password):
|
|
logger.info(f"Login successful: {username}")
|
|
|
|
payload = {
|
|
"id": user['id'],
|
|
"username": user['username'],
|
|
"role": user['role'],
|
|
"exp": datetime.now(timezone.utc) + timedelta(minutes=60)
|
|
}
|
|
token = jwt.encode(payload, SECRET_KEY, algorithm="HS256")
|
|
|
|
return jsonify({
|
|
"token": token,
|
|
"role": user['role']
|
|
})
|
|
|
|
logger.warning(f"⛔ Login failed: {username}")
|
|
return jsonify({"message": "Login failed"}), 401
|
|
|
|
except Exception as e:
|
|
logger.error(f"[Login Error] {e}")
|
|
return jsonify({"message": "Server error"}), 500
|