-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
160 lines (133 loc) · 5.53 KB
/
api.py
File metadata and controls
160 lines (133 loc) · 5.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
from flask import Flask, request, jsonify
from flask_jwt_extended import JWTManager, create_access_token, jwt_required
from pymongo import MongoClient
from datetime import datetime
import os
from dotenv import load_dotenv
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
import base64
load_dotenv()
MONGO_URI = os.getenv("MONGO_URI")
app = Flask(__name__)
app.config["JWT_SECRET_KEY"]= os.getenv("JWT_SECRET_KEY")
jwt =JWTManager(app)
limiter = Limiter(
get_remote_address,
app=app,
default_limits=["10 per minute"],
storage_uri="memory://",
)
try:
client = MongoClient(MONGO_URI)
db = client["FaceSecureDB"]
client.admin.command('ping')
# print("MongoDB bağlantısı başarılı!")
except Exception as e:
print(f"MongoDB bağlantı hatası: {e}")
db = None
@app.route("/login", methods=["POST"])
def login():
data = request.json
username = data.get("username")
password = data.get("password")
if username == "admin" and password == "admin123":
token = create_access_token(identity=username)
return jsonify(access_token=token)
return jsonify(msg="Hatalı kimlik bilgisi"), 401
@app.route("/users", methods=["POST"]) # Yeni kullanıcı kaydının ve embedinglerinin kaydının olduğu kısım
@jwt_required()
def add_user():
if db is None:
return jsonify(msg="Veritabanı bağlantısı kurulamadı."), 500
data = request.json
user = data.get("user_id")
new_embeddings = data.get("embeddings")
if not user:
return jsonify(msg="Kullanıcı adı gerekli"), 400
if not new_embeddings:
return jsonify(msg="Embeddingler gerekli"), 400
try:
if db["users"].find_one({"user_id": user}):
return jsonify(msg="Kullanıcı zaten mevcut"), 409
db["users"].insert_one({"user_id": user, "embeddings_enc": new_embeddings})
return jsonify(msg=f"Kullanıcı eklendi ve {len(new_embeddings)} embedding kaydedildi"), 200
except Exception as e:
print(f"MongoDB'ye kullanıcı eklerken hata: {e}")
return jsonify(msg=f"Kullanıcı eklenirken veritabanı hatası oluştu: {str(e)}"), 500
@app.route("/users/<string:user_id>", methods=["DELETE"]) # Kullanıcı silme kısmı
@jwt_required()
def delete_user(user_id):
if db is None:
return jsonify(msg="Veritabanı bağlantısı kurulamadı."), 500
try:
result = db["users"].delete_one({"user_id": user_id})
if result.deleted_count > 0:
return jsonify(msg=f"{user_id} silindi"), 200
else:
return jsonify(msg=f"{user_id} bulunamadı"), 404
except Exception as e:
print(f"MongoDB'den kullanıcı silerken hata: {e}")
return jsonify(msg=f"Kullanıcı silinirken veritabanı hatası oluştu: {str(e)}"), 500
@app.route("/users", methods=["GET"]) # Tüm kayıtlı kullanıcıları getirme kısmı
def get_users():
if db is None:
return jsonify(msg="Veritabanı bağlantısı kurulamadı."), 500
try:
users = list(db["users"].find({}, {"_id": 0}))
return jsonify(users), 200
except Exception as e:
print(f"MongoDB'den kullanıcıları çekerken hata: {e}")
return jsonify(msg=f"Kullanıcılar alınırken veritabanı hatası oluştu: {str(e)}"), 500
@app.route("/logs", methods=["GET"]) # Yanlış girişlerin hepsini veritabanından alır.
@jwt_required()
def get_logs():
if db is None:
return jsonify(msg="Veritabanı bağlantısı kurulamadı."), 500
try:
logs_cursor = db["failed_logins"].find({}, {"_id": 0}) # _id hariç tüm alanları çek
logs_list = []
for log in logs_cursor:
if "image_data" in log and log["image_data"]:
# Binary image_data'yı base64 stringine dönüştür
log["image_base64"] = base64.b64encode(log["image_data"]).decode('utf-8')
del log["image_data"] # Binary veriyi JSON'dan kaldır
logs_list.append(log)
return jsonify(logs_list), 200
except Exception as e:
print(f"MongoDB'den logları çekerken hata: {e}")
return jsonify(msg=f"Loglar alınırken veritabanı hatası oluştu: {str(e)}"), 500
@app.route("/log_failed", methods=["POST"])
@limiter.limit("3 per minute", key_func=get_remote_address, override_defaults=True)
def log_failed():
if db is None:
return jsonify(msg="Veritabanı bağlantısı kurulamadı."), 500
ip = request.remote_addr
data = request.json
detected_score = data.get("score", None)
image_base64 = data.get("image_base64", None)
image_data = None
if image_base64:
try:
image_data = base64.b64decode(image_base64)
except Exception as e:
print(f"Base64 çözme hatası: {e}")
image_data = None
return jsonify(msg="Geçersiz resim verisi, log kaydedildi"), 400
reason = "Yüz tanınamadı"
if detected_score is not None:
reason = f"Yüz tanınamadı (Benzerlik Skoru: {detected_score:.2f})"
try:
db["failed_logins"].insert_one({
"timestamp": datetime.utcnow(),
"ip": ip,
"reason": reason,
"score": detected_score,
"image_data": image_data
})
return jsonify(msg="Log kaydedildi"), 201
except Exception as e:
print(f"MongoDB'ye log kaydederken hata: {e}")
return jsonify(msg=f"Log kaydedilirken veritabanı hatası oluştu: {str(e)}"), 500
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000)