53 lines
1.7 KiB
Python
53 lines
1.7 KiB
Python
from flask import Flask, request, jsonify
|
|
from pymongo import MongoClient
|
|
|
|
app = Flask(__name__)
|
|
|
|
try:
|
|
from local_settings import *
|
|
except ImportError:
|
|
print("Can't import from localsettings, terminating")
|
|
exit()
|
|
|
|
EXPECTED_PASSWORD = APPLICATION_PASSWORD
|
|
uri = 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
|