Boobs00 commited on
Commit
3546e19
·
verified ·
1 Parent(s): 9d6574c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +105 -0
app.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, jwt, datetime, json
2
+ from flask import Flask, request, jsonify
3
+ from werkzeug.security import generate_password_hash, check_password_hash
4
+ from models import db, User, SearchHistory
5
+ from flask_cors import CORS
6
+ from functools import wraps
7
+ from datetime import datetime as dt
8
+
9
+ SECRET_KEY = os.getenv("SECRET_KEY", "ultra_secret_dev_key")
10
+ app = Flask(__name__)
11
+ app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///users.db"
12
+ app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
13
+ db.init_app(app)
14
+ CORS(app)
15
+
16
+ with app.app_context():
17
+ db.create_all()
18
+
19
+ def token_required(f):
20
+ @wraps(f)
21
+ def decorated(*args, **kwargs):
22
+ token = None
23
+ if "Authorization" in request.headers:
24
+ token = request.headers["Authorization"].split(" ")[-1]
25
+ if not token:
26
+ return jsonify({"message": "Token is missing!"}), 401
27
+ try:
28
+ data = jwt.decode(token, SECRET_KEY, algorithms=["HS256"])
29
+ current_user = User.query.get(data["user_id"])
30
+ except Exception:
31
+ return jsonify({"message": "Token is invalid!"}), 401
32
+ return f(current_user, *args, **kwargs)
33
+ return decorated
34
+
35
+ @app.route("/signup", methods=["POST"])
36
+ def signup():
37
+ data = request.json
38
+ if User.query.filter_by(username=data["username"]).first():
39
+ return jsonify({"message": "User already exists"}), 400
40
+ hashed_pw = generate_password_hash(data["password"])
41
+ new_user = User(username=data["username"], password_hash=hashed_pw)
42
+ db.session.add(new_user)
43
+ db.session.commit()
44
+ return jsonify({"message": "User created"}), 201
45
+
46
+ @app.route("/login", methods=["POST"])
47
+ def login():
48
+ data = request.json
49
+ user = User.query.filter_by(username=data["username"]).first()
50
+ if not user or not check_password_hash(user.password_hash, data["password"]):
51
+ return jsonify({"message": "Invalid credentials"}), 401
52
+ token = jwt.encode({
53
+ "user_id": user.id,
54
+ "exp": datetime.datetime.utcnow() + datetime.timedelta(hours=2)
55
+ }, SECRET_KEY, algorithm="HS256")
56
+ return jsonify({"token": token})
57
+
58
+ @app.route("/search", methods=["POST"])
59
+ @token_required
60
+ def secure_search(current_user):
61
+ data = request.get_json()
62
+ query = data.get("query", "")
63
+ filters = data.get("filters", {})
64
+ # Save search to history
65
+ entry = SearchHistory(
66
+ query=query,
67
+ filters=json.dumps(filters),
68
+ user_id=current_user.id,
69
+ timestamp=dt.utcnow()
70
+ )
71
+ db.session.add(entry)
72
+ db.session.commit()
73
+ # Simulate filtered results
74
+ results = [
75
+ {"title": f"{query} ({', '.join(k for k, v in filters.items() if v)})", "url": "#"}
76
+ ]
77
+ return jsonify({
78
+ "user": current_user.username,
79
+ "results": results,
80
+ "ai_preview": "https://fake-preview.com/image.png"
81
+ })
82
+
83
+ @app.route("/history", methods=["GET"])
84
+ @token_required
85
+ def get_history(current_user):
86
+ history = SearchHistory.query.filter_by(user_id=current_user.id)\
87
+ .order_by(SearchHistory.timestamp.desc()).limit(20).all()
88
+ return jsonify([
89
+ {
90
+ "query": h.query,
91
+ "filters": json.loads(h.filters or '{}'),
92
+ "timestamp": h.timestamp.isoformat()
93
+ }
94
+ for h in history
95
+ ])
96
+
97
+ @app.route("/history", methods=["DELETE"])
98
+ @token_required
99
+ def clear_history(current_user):
100
+ deleted = SearchHistory.query.filter_by(user_id=current_user.id).delete()
101
+ db.session.commit()
102
+ return jsonify({"message": f"{deleted} entries deleted."}), 200
103
+
104
+ if __name__ == "__main__":
105
+ app.run(host="0.0.0.0", port=7860)