54 lines
1.7 KiB
Python
54 lines
1.7 KiB
Python
from flask import Flask, request, jsonify
|
|
from pymongo import MongoClient
|
|
from dotenv import load_dotenv
|
|
import os
|
|
|
|
load_dotenv()
|
|
|
|
app = Flask(__name__)
|
|
|
|
EXPECTED_PASSWORD = "secret_password"
|
|
|
|
uri = os.getenv("MONGO_URI")
|
|
|
|
mongo_client = MongoClient(uri)
|
|
db = mongo_client["user_interactions"]
|
|
collection = db["user_events"]
|
|
|
|
def validate_event(event):
|
|
required_keys = ["@version", "type", "TimeStamp", "data", "@timestamp"]
|
|
return all(key in event for key in required_keys)
|
|
|
|
@app.route('/submit', methods=['POST', 'OPTIONS'])
|
|
def submit_event():
|
|
if request.method == 'OPTIONS':
|
|
resp = jsonify()
|
|
resp.headers['Access-Control-Allow-Origin'] = '*'
|
|
resp.headers['Access-Control-Allow-Methods'] = 'POST, OPTIONS'
|
|
resp.headers['Access-Control-Allow-Headers'] = 'Content-Type, X-Password'
|
|
return resp
|
|
try:
|
|
|
|
password = request.headers.get('X-Password')
|
|
if password != EXPECTED_PASSWORD:
|
|
return jsonify({"error": "Неверный пароль"}), 403
|
|
|
|
event = request.get_json()
|
|
|
|
if not event or not validate_event(event):
|
|
resp = jsonify({"error": "Неверный формат"})
|
|
resp.headers['Access-Control-Allow-Origin'] = '*'
|
|
return resp, 400
|
|
|
|
collection.insert_one(event)
|
|
|
|
resp = jsonify({"message": "Действие успешно сохранено"})
|
|
resp.headers['Access-Control-Allow-Origin'] = '*'
|
|
return resp, 200
|
|
except Exception as e:
|
|
resp = jsonify({"error": str(e)})
|
|
resp.headers['Access-Control-Allow-Origin'] = '*'
|
|
return resp, 500
|
|
|
|
if __name__ == '__main__':
|
|
app.run(debug=True, host='0.0.0.0', port=5000) |