Просмотр исходного кода

feat: implement password reset functionality with CSRF protection

Manuel 11 месяцев назад
Родитель
Сommit
e2ddf926db
3 измененных файлов с 86 добавлено и 3 удалено
  1. 3 3
      app.py
  2. 51 0
      routes/auth_routes.py
  3. 32 0
      services/auth_service.py

+ 3 - 3
app.py

@@ -9,12 +9,12 @@ from dotenv import load_dotenv
 from flask import Flask
 from flask_apscheduler import APScheduler
 from flask_socketio import SocketIO
-from flask_wtf.csrf import CSRFProtect
 
 from config import Config, logger
 from database.database import migrate_database
 from parsers.log import process_logs
 from routes import register_routes
+from routes.auth_routes import csrf
 from routes.stats_routes import realtime_data_thread
 from services.metrics_service import MetricsService
 from services.notifications import (
@@ -46,8 +46,8 @@ def create_app():
     app = Flask(__name__, static_folder="./static")
     app.config.from_object(Config())
 
-    # Initialize CSRF protection
-    CSRFProtect(app)
+    # Initialize CSRF protection (shared instance with routes)
+    csrf.init_app(app)
 
     # Initialize extensions
     scheduler = APScheduler()

+ 51 - 0
routes/auth_routes.py

@@ -15,11 +15,13 @@ from flask import (
     session,
     url_for,
 )
+from flask_wtf.csrf import CSRFProtect
 
 from config import logger
 from services.auth_service import AuthConfig, AuthService
 
 auth_bp = Blueprint("auth", __name__, url_prefix="/auth")
+csrf = CSRFProtect()
 
 
 @auth_bp.route("/login", methods=["GET", "POST"])
@@ -147,3 +149,52 @@ def check_auth():
         }
 
     return {"authenticated": False}, 401
+
+
+@auth_bp.route("/reset-password", methods=["POST"])
+@csrf.exempt
+def reset_password():
+    """
+    Reset user password. Only accessible from localhost for security.
+    Requires username and new_password in request body.
+
+    Usage examples:
+    curl -X POST http://localhost:5000/auth/reset-password \
+      -H "Content-Type: application/json" \
+      -d '{"username": "admin", "new_password": "newpassword123"}'
+    """
+    # Check if request is from localhost
+    client_ip = request.headers.get("X-Forwarded-For", request.remote_addr)
+    if client_ip:
+        client_ip = client_ip.split(",")[0].strip()
+
+    # Allow only localhost connections
+    if client_ip not in ["127.0.0.1", "::1", "localhost"]:
+        logger.warning("Password reset attempt from unauthorized IP")
+        return {
+            "error": "Access denied. This endpoint is only accessible from localhost."
+        }, 403
+
+    # Get data from request
+    data = request.get_json() if request.is_json else request.form
+    username = data.get("username", "").strip()
+    new_password = data.get("new_password", "")
+
+    # Validate input
+    if not username or not new_password:
+        return {"error": "Username and new_password are required."}, 400
+
+    if len(new_password) < 8:
+        return {"error": "Password must be at least 8 characters long."}, 400
+
+    # Update password
+    success = AuthService.update_user_password(username, new_password)
+
+    if success:
+        logger.info(f"Password reset successful for user: {username} from localhost")
+        return {
+            "success": True,
+            "message": f"Password updated successfully for user: {username}",
+        }, 200
+    else:
+        return {"error": "Failed to update password. User may not exist."}, 400

+ 32 - 0
services/auth_service.py

@@ -246,6 +246,38 @@ class AuthService:
         """Check if current request is from an authenticated user."""
         return cls.get_current_user() is not None
 
+    @classmethod
+    def update_user_password(cls, username: str, new_password: str) -> bool:
+        """
+        Update user password in the database.
+        Returns True if successful, False otherwise.
+        """
+        session = get_session()
+        try:
+            user = session.query(AdminUser).filter_by(username=username).first()
+
+            if not user:
+                logger.error(f"User not found: {username}")
+                return False
+
+            # Hash the new password
+            password_hash, salt = cls.hash_password_bcrypt(new_password)
+
+            # Update user password
+            user.password_hash = password_hash
+            user.salt = salt
+            session.commit()
+
+            logger.info(f"Password updated successfully for user: {username}")
+            return True
+
+        except Exception as e:
+            logger.error(f"Error updating password for {username}: {e}")
+            session.rollback()
+            return False
+        finally:
+            session.close()
+
 
 def login_required(f):
     """