-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
516 lines (422 loc) · 16.5 KB
/
main.py
File metadata and controls
516 lines (422 loc) · 16.5 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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
from fastapi import FastAPI, Depends, HTTPException, UploadFile, File, Form, status
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse, FileResponse
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from sqlalchemy.orm import Session
from sqlalchemy import and_
from datetime import datetime, date, timedelta
from jose import JWTError, jwt
import os
import shutil
from typing import List, Optional
from database import get_db, init_db, User, Badge, AccessLog, ResultEnum
from models import (
UserCreate, UserResponse, BadgeCreate, BadgeResponse,
VerificationRequest, VerificationResponse, AccessLogResponse
)
from face_recognition_service import FaceRecognitionService
from qr_service import QRService
from report_service import ReportService
app = FastAPI(title="System Weryfikacji Tożsamości")
SECRET_KEY = "admin-secret-key-change-in-production"
ALGORITHM = "HS256"
ADMIN_PASSWORD = "admin"
face_service = FaceRecognitionService()
qr_service = QRService()
report_service = ReportService()
security = HTTPBearer(auto_error=False)
UPLOAD_DIR = "uploads"
os.makedirs(UPLOAD_DIR, exist_ok=True)
os.makedirs("static", exist_ok=True)
os.makedirs("reports", exist_ok=True)
app.mount("/static", StaticFiles(directory="static"), name="static")
@app.on_event("startup")
def startup_event():
init_db()
@app.get("/", response_class=HTMLResponse)
async def read_root():
with open("static/index.html", "r", encoding="utf-8") as f:
return f.read()
@app.get("/admin", response_class=HTMLResponse)
async def admin_panel():
with open("static/admin.html", "r", encoding="utf-8") as f:
return f.read()
def create_access_token():
expire = datetime.utcnow() + timedelta(hours=24)
to_encode = {"sub": "admin", "exp": expire}
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
async def verify_admin_token(credentials: Optional[HTTPAuthorizationCredentials] = Depends(security)):
if not credentials:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Brak autoryzacji"
)
try:
token = credentials.credentials
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
if payload.get("sub") != "admin":
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Nieprawidłowy token"
)
return payload
except JWTError:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Nieprawidłowy token"
)
@app.post("/api/admin/login")
async def admin_login(password: str = Form(...)):
if password == "admin":
token = create_access_token()
return {"success": True, "token": token, "message": "Zalogowano pomyślnie"}
else:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Nieprawidłowe hasło"
)
@app.get("/api/admin/check-auth")
async def check_auth(credentials: Optional[HTTPAuthorizationCredentials] = Depends(security)):
if not credentials:
return {"authenticated": False}
try:
token = credentials.credentials
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
if payload.get("sub") == "admin":
return {"authenticated": True}
except JWTError:
pass
return {"authenticated": False}
@app.get("/api/check-qr")
async def check_qr_code(qr_code: str, db: Session = Depends(get_db)):
"""
Proste sprawdzenie kodu QR, używane przed przejściem do weryfikacji twarzy.
Tutaj sprawdzamy tylko, czy podany ciąg znaków istnieje jako qr_code w tabeli Badge
i czy przepustka / użytkownik są nadal ważni.
"""
if not qr_code or not QRService.validate_qr_code(qr_code):
return {"valid": False, "message": "Kod QR niezgodny z bazą"}
badge = db.query(Badge).filter(Badge.qr_code == qr_code).first()
if not badge:
return {"valid": False, "message": "Kod QR niezgodny z bazą"}
if badge.valid_until and badge.valid_until < date.today():
return {"valid": False, "message": "Kod QR niezgodny z bazą"}
user = db.query(User).filter(User.id == badge.user_id).first()
if not user or not user.is_active:
return {"valid": False, "message": "Kod QR niezgodny z bazą"}
return {"valid": True, "message": "Kod QR jest prawidłowy"}
@app.post("/api/verify", response_model=VerificationResponse)
async def verify_access(
qr_code: str = Form(...),
image: Optional[UploadFile] = File(None),
images: List[UploadFile] = File(default=[]),
db: Session = Depends(get_db)
):
try:
timestamp = datetime.now()
timestamp_str = timestamp.strftime("%Y%m%d_%H%M%S")
image_paths: List[str] = []
if images:
for idx, up in enumerate(images[:3]):
fn = f"{timestamp_str}_{qr_code}_{idx}.jpg"
p = os.path.join(UPLOAD_DIR, fn)
with open(p, "wb") as buffer:
shutil.copyfileobj(up.file, buffer)
image_paths.append(p)
elif image is not None:
image_filename = f"{timestamp_str}_{qr_code}.jpg"
image_path = os.path.join(UPLOAD_DIR, image_filename)
with open(image_path, "wb") as buffer:
shutil.copyfileobj(image.file, buffer)
image_paths.append(image_path)
else:
raise HTTPException(status_code=400, detail="Brak zdjęcia do weryfikacji")
primary_image_path = image_paths[0]
liveness_ok = False
if len(image_paths) >= 3:
# Detekcja mrugnięcia – traktujemy ją teraz jako dodatkową informację,
# ale NIE blokujemy całej weryfikacji, gdy mrugnięcie nie zostanie wykryte.
liveness_ok = face_service.detect_blink_liveness(image_paths[:6])
if (not liveness_ok) and face_service.detect_screen_spoof(primary_image_path):
log = AccessLog(
timestamp=timestamp,
result="SUSPICIOUS",
match_score=None,
badge_id=None,
user_id=None,
image_path=primary_image_path,
)
db.add(log)
db.commit()
return VerificationResponse(
success=False,
message="Podejrzenie uzycia zdjecia lub ekranu (telefon, monitor)",
result="SUSPICIOUS",
log_id=log.id,
)
# W tym miejscu upewniamy się, że kod QR istnieje w naszej bazie (tabela Badge)
badge = db.query(Badge).filter(Badge.qr_code == qr_code).first()
if not badge:
log = AccessLog(
timestamp=timestamp,
result="REJECT",
match_score=None,
badge_id=None,
user_id=None,
image_path=primary_image_path,
)
db.add(log)
db.commit()
return VerificationResponse(
success=False,
message="Nieprawidłowy kod QR",
result="REJECT",
log_id=log.id,
)
if badge.valid_until and badge.valid_until < date.today():
log = AccessLog(
timestamp=timestamp,
result="REJECT",
match_score=None,
badge_id=badge.id,
user_id=badge.user_id,
image_path=primary_image_path,
)
db.add(log)
db.commit()
return VerificationResponse(
success=False,
message="Przepustka wygasła",
result="REJECT",
log_id=log.id,
)
user = db.query(User).filter(User.id == badge.user_id).first()
if not user or not user.is_active:
log = AccessLog(
timestamp=timestamp,
result="REJECT",
match_score=None,
badge_id=badge.id,
user_id=user.id if user else None,
image_path=primary_image_path,
)
db.add(log)
db.commit()
return VerificationResponse(
success=False,
message="Użytkownik nieaktywny",
result="REJECT",
log_id=log.id,
)
face_result = face_service.recognize_face(primary_image_path, threshold=0.5)
if not face_result:
log = AccessLog(
timestamp=timestamp,
result="REJECT",
match_score=None,
badge_id=badge.id,
user_id=user.id,
image_path=primary_image_path
)
db.add(log)
db.commit()
return VerificationResponse(
success=False,
message="Nie rozpoznano twarzy",
result="REJECT",
log_id=log.id
)
recognized_face_id, match_score = face_result
if recognized_face_id != user.face_id:
log = AccessLog(
timestamp=timestamp,
result="SUSPICIOUS",
match_score=match_score,
badge_id=badge.id,
user_id=user.id,
image_path=primary_image_path
)
db.add(log)
db.commit()
return VerificationResponse(
success=False,
message="Niezgodność twarzy z kartą - podejrzana sytuacja",
result="SUSPICIOUS",
match_score=match_score,
user_id=user.id,
log_id=log.id
)
if match_score >= 0.5:
log = AccessLog(
timestamp=timestamp,
result="ACCEPT",
match_score=match_score,
badge_id=badge.id,
user_id=user.id,
image_path=primary_image_path
)
db.add(log)
db.commit()
return VerificationResponse(
success=True,
message="Dostęp przyznany",
result="ACCEPT",
match_score=match_score,
user_id=user.id,
log_id=log.id,
first_name=user.first_name,
last_name=user.last_name
)
else:
log = AccessLog(
timestamp=timestamp,
result="REJECT",
match_score=match_score,
badge_id=badge.id,
user_id=user.id,
image_path=primary_image_path
)
db.add(log)
db.commit()
return VerificationResponse(
success=False,
message="Niskie dopasowanie twarzy",
result="REJECT",
match_score=match_score,
log_id=log.id
)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Błąd weryfikacji: {str(e)}")
@app.post("/api/users", response_model=UserResponse)
async def create_user(user: UserCreate, db: Session = Depends(get_db)):
if not user.face_id or user.face_id.strip() == "":
import time
base_id = f"{user.first_name.upper()}_{user.last_name.upper()}"
face_id = f"{base_id}_{int(time.time())}"
else:
face_id = user.face_id
db_user = User(
first_name=user.first_name,
last_name=user.last_name,
face_id=face_id,
is_active=user.is_active
)
db.add(db_user)
db.commit()
db.refresh(db_user)
return db_user
@app.get("/api/users", response_model=List[UserResponse])
async def get_users(db: Session = Depends(get_db)):
users = db.query(User).all()
return users
@app.get("/api/users/{user_id}", response_model=UserResponse)
async def get_user(user_id: int, db: Session = Depends(get_db)):
user = db.query(User).filter(User.id == user_id).first()
if not user:
raise HTTPException(status_code=404, detail="Użytkownik nie znaleziony")
return user
@app.post("/api/users/{user_id}/register-face")
async def register_user_face(
user_id: int,
image: UploadFile = File(...),
db: Session = Depends(get_db)
):
user = db.query(User).filter(User.id == user_id).first()
if not user:
raise HTTPException(status_code=404, detail="Użytkownik nie znaleziony")
image_filename = f"register_{user_id}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
image_path = os.path.join(UPLOAD_DIR, image_filename)
with open(image_path, "wb") as buffer:
shutil.copyfileobj(image.file, buffer)
success = face_service.register_face(image_path, user.face_id)
if success:
return {"message": "Twarz zarejestrowana pomyślnie", "success": True}
else:
return {"message": "Nie wykryto twarzy na zdjęciu", "success": False}
@app.post("/api/badges", response_model=BadgeResponse)
async def create_badge(badge: BadgeCreate, db: Session = Depends(get_db)):
db_badge = Badge(
qr_code=badge.qr_code,
valid_until=badge.valid_until,
user_id=badge.user_id
)
db.add(db_badge)
db.commit()
db.refresh(db_badge)
return db_badge
@app.get("/api/badges", response_model=List[BadgeResponse])
async def get_badges(db: Session = Depends(get_db)):
badges = db.query(Badge).all()
return badges
@app.get("/api/badges/{badge_id}/qr")
async def get_badge_qr(badge_id: int, db: Session = Depends(get_db)):
badge = db.query(Badge).filter(Badge.id == badge_id).first()
if not badge:
raise HTTPException(status_code=404, detail="Przepustka nie znaleziona")
# Generujemy obraz QR na podstawie qr_code zapisanego w bazie
qr_image = qr_service.generate_qr_code(badge.qr_code)
return {"qr_code": badge.qr_code, "qr_image": qr_image}
@app.get("/api/users/{user_id}/check-qr")
async def check_user_qr(user_id: int, qr_code: str, db: Session = Depends(get_db)):
user = db.query(User).filter(User.id == user_id).first()
if not user:
raise HTTPException(status_code=404, detail="Użytkownik nie znaleziony")
badge = db.query(Badge).filter(Badge.qr_code == qr_code).first()
if not badge:
return {"valid": False, "message": "Kod QR nie istnieje"}
if badge.user_id != user_id:
return {"valid": False, "message": "Kod QR nie należy do tego użytkownika"}
if badge.valid_until and badge.valid_until < date.today():
return {"valid": False, "message": "Przepustka wygasła"}
return {"valid": True, "message": "Kod QR jest prawidłowy"}
@app.get("/api/logs", response_model=List[AccessLogResponse])
async def get_logs(
start_date: Optional[str] = None,
end_date: Optional[str] = None,
limit: int = 100,
db: Session = Depends(get_db)
):
query = db.query(AccessLog)
if start_date:
start = datetime.fromisoformat(start_date)
query = query.filter(AccessLog.timestamp >= start)
if end_date:
end = datetime.fromisoformat(end_date)
query = query.filter(AccessLog.timestamp <= end)
logs = query.order_by(AccessLog.timestamp.desc()).limit(limit).all()
return logs
@app.get("/api/reports/generate")
async def generate_report(
start_date: Optional[str] = None,
end_date: Optional[str] = None,
db: Session = Depends(get_db)
):
start = datetime.now() - timedelta(days=30)
end = datetime.now()
if start_date:
start = datetime.fromisoformat(start_date)
if end_date:
end = datetime.fromisoformat(end_date)
logs = db.query(AccessLog).filter(
and_(AccessLog.timestamp >= start, AccessLog.timestamp <= end)
).all()
logs_data = []
for log in logs:
logs_data.append({
"timestamp": log.timestamp,
"result": log.result,
"match_score": log.match_score,
"badge_id": log.badge_id,
"user_id": log.user_id,
"image_path": log.image_path
})
report_path = report_service.generate_access_report(logs_data, start, end)
return FileResponse(
report_path,
media_type="application/pdf",
filename=os.path.basename(report_path)
)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)