-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathverifikator.py
More file actions
533 lines (435 loc) · 17.9 KB
/
verifikator.py
File metadata and controls
533 lines (435 loc) · 17.9 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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
import os
import json
import logging
import time
from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException, Request, Depends
from fastapi.staticfiles import StaticFiles
from contextlib import asynccontextmanager
from pydantic import BaseModel
from google.oauth2.service_account import Credentials
import gspread
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from threading import Lock
from datetime import datetime, time as dt_time, timezone
import uuid
from fastapi.responses import RedirectResponse, HTMLResponse,PlainTextResponse
import requests
import psycopg2
from psycopg2 import pool, sql
import html
from starlette.middleware.base import BaseHTTPMiddleware
from ipaddress import ip_address, IPv4Address
from fastapi_utils.tasks import repeat_every
import asyncio
#load_dotenv(dotenv_path='./.env')
#load_dotenv(dotenv_path='./.env.db')
logging.basicConfig(level=logging.INFO)
#env stvari
google_key_path = os.environ["GOOGLE_KEY_PATH"]
spreadsheet_id = os.environ["SPREADSHEET_ID"]
sheet_id = int(os.environ["SPREADSHEET_SHEET_ID"])
impersonation_user = os.environ.get("SPREADSHEET_USER")
google_client_id = os.environ["GOOGLE_CLIENT_ID"]
google_client_secret = os.environ["GOOGLE_CLIENT_SECRET"]
google_redirect_uri = os.environ["GOOGLE_REDIRECT_URI"]
db_host = os.environ["POSTGRES_HOST"]
db_user = os.environ["POSTGRES_USER"]
db_password = os.environ["POSTGRES_PASSWORD"]
db_database = os.environ["POSTGRES_DB"]
# provjera sheetsa
credentials = Credentials.from_service_account_file(
google_key_path,
scopes=["https://www.googleapis.com/auth/spreadsheets"],
subject=impersonation_user
)
client = gspread.authorize(credentials)
cached_rows = None
cache_timestamp = 0
last_loaded_day = None
cache_lock = Lock()
# Inicijalizacija PostgreSQL connection pool-a
db_pool = None
def init_db(): #koristio sam psycopg2, no postoje drugi library na istu foru
global db_pool
db_pool = psycopg2.pool.SimpleConnectionPool(1, 10, #10 mozemo povecati ako ce trebati vise konekcija, iako neznam zasto bi trebalo?
host=db_host,
user=db_user,
password=db_password,
dbname=db_database
)
logging.info("POSGRESRADI.")
with db_pool.getconn() as conn:
with conn.cursor() as cursor:
cursor.execute("""
CREATE TABLE IF NOT EXISTS verification_attempts (
state TEXT PRIMARY KEY,
izvor TEXT NOT NULL,
email TEXT,
status TEXT NOT NULL,
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
used_at TIMESTAMP WITH TIME ZONE
);
""")
conn.commit()
db_pool.putconn(conn)
@asynccontextmanager
async def lifespan(app: FastAPI):
try:
init_db()
refresh_cache(force=True)
async def scheduled_refresh_cache():
while True:
now = datetime.now()
logging.info(f"Trenutno vrijeme pokretanja je: {now}")
if now.hour == 5:
logging.info("Refreshanje oko 5 ujutro")
refresh_cache(force=True)
await asyncio.sleep(3600)
task = asyncio.create_task(scheduled_refresh_cache())
except Exception as e:
logging.error(f"[ERROR] Startup error: {e}")
yield
if task:
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
app = FastAPI(lifespan=lifespan)
app.mount("/static", StaticFiles(directory="static"), name="static")
class OAuthRedirectMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
client_host = request.client.host if request.client else None
if client_host:
try:
ip = ip_address(client_host)
if ip.is_private:
response = await call_next(request)
return response
except ValueError:
pass
if request.url.path == "/oauth/callback" or request.url.path == "/":
response = await call_next(request)
return response
return PlainTextResponse("Not Found", status_code=404)
app.add_middleware(OAuthRedirectMiddleware)
class EmailRequest(BaseModel):
email: str
class EmailsRequest(BaseModel):
emails: list[str]
class VerificationRequest(BaseModel):
state: str
izvor: str
def normalize(email: str) -> str:
return email.strip().lower()
def load_rows():
if cached_rows is None:
raise RuntimeError("STUPCI IZ SHEETA NE RADE")
return cached_rows
def refresh_cache(force=False):
global cached_rows, cache_timestamp, last_loaded_day
now = datetime.now()
refresh_time = dt_time(5, 0)
if force or cached_rows is None or (now.date() != last_loaded_day and now.time() >= refresh_time):
with cache_lock:
try:
spreadsheet = client.open_by_key(spreadsheet_id)
worksheet = spreadsheet.get_worksheet_by_id(sheet_id)
rows = worksheet.get_all_records()
cached_rows = rows
cache_timestamp = time.time()
last_loaded_day = now.date()
logging.info(f"Spreadsheet ucitan {len(rows)} redaka")
except Exception as e:
logging.exception("error u ucitavanju redaka: ", e)
raise
@app.post("/verify-email")
def verify_email(req: EmailRequest):
try:
rows = load_rows()
except RuntimeError as e:
raise HTTPException(status_code=503, detail=str(e))
search_email = normalize(req.email)
for row in rows:
kset_email = normalize(row.get("KSET e-pošta", "") or "")
private_email = normalize(row.get("Privatna e-pošta", "") or "")
if search_email in [kset_email, private_email]:
return {
"full_name": row.get("Ime i prezime", "N/A"),
"section": row.get("Matična sekcija", "N/A"),
"status_clanstva": row.get("Trenutna vrsta članstva", "N/A"),
"kset_email": kset_email,
"private_email": private_email,
}
raise HTTPException(status_code=404, detail="Email nije pronađen.")
@app.post("/verify-emails")
def verify_emails_batch(req: EmailsRequest):
try:
rows = load_rows()
except RuntimeError as e:
raise HTTPException(status_code=503, detail=str(e))
lookup_data = {}
for row in rows:
kset_email = normalize(row.get("KSET e-pošta", "") or "")
private_email = normalize(row.get("Privatna e-pošta", "") or "")
data = {
"full_name": row.get("Ime i prezime", "N/A"),
"section": row.get("Matična sekcija", "N/A"),
"status_clanstva": row.get("Trenutna vrsta članstva", "N/A"),
"kset_email": kset_email,
"private_email": private_email,
}
if kset_email:
lookup_data[kset_email] = data
if private_email:
lookup_data[private_email] = data
response_data = {}
for email in req.emails:
normalized_email = normalize(email)
if normalized_email in lookup_data:
response_data[email] = lookup_data[normalized_email]
return response_data
@app.post("/generate-oauth-link")
def generate_oauth_link_simplified(req: VerificationRequest):
conn = None
try:
conn = db_pool.getconn()
cursor = conn.cursor()
insert_query = """
INSERT INTO verification_attempts (state, izvor, status, created_at)
VALUES (%s, %s, %s, %s)
ON CONFLICT (state) DO UPDATE SET izvor = EXCLUDED.izvor, status = EXCLUDED.status, created_at = EXCLUDED.created_at, used_at = NULL;
"""
cursor.execute(insert_query, (
req.state,
req.izvor,
"pending",
datetime.now(timezone.utc)
))
conn.commit()
logging.info(f"Novi pokusaj verifikacije zabiljezen za state: {req.state}")
except psycopg2.Error as e:
logging.error(f"Greška prilikom zapisivanja u PostgreSQL bazu: {e}")
if conn: conn.rollback()
raise HTTPException(status_code=500, detail="Greška baze podataka")
finally:
if conn: db_pool.putconn(conn)
oauth_url = (
"https://accounts.google.com/o/oauth2/v2/auth"
"?response_type=code"
f"&client_id={google_client_id}"
f"&redirect_uri={google_redirect_uri}"
"&scope=openid%20email"
f"&state={req.state}"
"&prompt=select_account"
)
return {"oauth_url": oauth_url, "state": req.state}
@app.get("/oauth/status")
def oauth_status(state: str):
conn = None
logging.info(f"Received /oauth/status request for state={state}")
try:
conn = db_pool.getconn()
cursor = conn.cursor()
cursor.execute(
"SELECT email, status FROM verification_attempts WHERE state = %s",
(state,)
)
row = cursor.fetchone()
if not row:
raise HTTPException(status_code=404, detail="Vec iskoristen link")
email, status = row
if status == "success":
return {
"status": "success",
"private_email": email
}
elif status == "pending":
return {"status": "pending"}
else:
return {"status": "fail", "reason": "Verifikacija nije uspjela"}
except psycopg2.Error as e:
logging.error(f"Greška prilikom provjere statusa u PostgreSQL: {e}")
raise HTTPException(status_code=500, detail="Greška baze podataka")
finally:
if conn: db_pool.putconn(conn)
@app.get("/oauth/callback", response_class=HTMLResponse)
def oauth_callback(code: str, state: str):
conn = None
try:
conn = db_pool.getconn()
cursor = conn.cursor()
cursor.execute(
"SELECT created_at, status FROM verification_attempts WHERE state = %s FOR UPDATE",
(state,)
)
row = cursor.fetchone()
if not row:
return HTMLResponse(content="<h1>Neispravan state</h1>", status_code=400)
created_at, status = row
if status != "pending":
return HTMLResponse(content="<h1>OAuth link je već iskorišten</h1>", status_code=400)
if (datetime.now(timezone.utc) - created_at).total_seconds() > 5 * 60:
cursor.execute("UPDATE verification_attempts SET status = %s, used_at = %s WHERE state = %s",
("expired", datetime.now(timezone.utc), state))
conn.commit()
return HTMLResponse(content="<h1>OAuth link je istekao</h1>", status_code=400)
google_email = verify_email_with_google(code)
req = EmailRequest(email=google_email)
sheet_data = verify_email(req) # Ovo će baciti HTTPException ako email nije u bazi
# Ažuriranje statusa i ostalih podataka u bazi
update_query = """
UPDATE verification_attempts
SET email = %s, status = %s, used_at = %s
WHERE state = %s
"""
cursor.execute(update_query, (
google_email,
"success",
datetime.now(timezone.utc),
state
))
conn.commit()
html_content = f"""
<html>
<head>
<title>Verifikacija uspješna</title>
<style>
body {{
font-family: Arial, sans-serif;
text-align: center;
margin: 50px;
}}
img {{
max-width: 200px;
margin-bottom: 20px;
}}
h1 {{
color: #333;
}}
</style>
</head>
<body>
<img src="Logo.svg" alt="Logo">
<h1>Verifikacija uspješna {html.escape(sheet_data.get('full_name', 'N/A'))}, možete zatvoriti ovu karticu</h1>
</body>
</html>
"""
return HTMLResponse(content=html_content, status_code=200)
except HTTPException as e:
# Ažuriranje statusa na "fail" ako verifikacija nije uspjela
if conn:
cursor.execute("UPDATE verification_attempts SET status = %s, used_at = %s WHERE state = %s",
("fail", datetime.now(timezone.utc), state))
conn.commit()
return HTMLResponse(content=f"""
<h1>Verifikacija nije uspjela</h1>
<p>Email se ne nalazi u bazi. Pokušajte se registrirati s drugim emailom.</p>
""", status_code=403)
except Exception as e:
logging.error(f"Neočekivana greška u callbacku: {e}")
if conn:
cursor.execute("UPDATE verification_attempts SET status = %s, used_at = %s WHERE state = %s",
("fail", datetime.now(timezone.utc), state))
conn.commit()
return HTMLResponse(content="<h1>Došlo je do neočekivane greške</h1>", status_code=500)
finally:
if conn:
db_pool.putconn(conn)
'''
@app.get("/oauth/callback")
def oauth_callback(code: str, state: str):
conn = None
try:
conn = db_pool.getconn()
cursor = conn.cursor()
cursor.execute(
"SELECT created_at, status, izvor FROM verification_attempts WHERE state = %s FOR UPDATE",
(state,)
)
row = cursor.fetchone()
if not row:
return RedirectResponse(url=f"/?status=error&message=Neispravan state", status_code=302)
created_at, status, izvor = row
if status != "pending":
return RedirectResponse(url=f"/?status=error&message=Link je već iskorišten", status_code=302)
if (datetime.now(timezone.utc) - created_at).total_seconds() > 5 * 60:
cursor.execute("UPDATE verification_attempts SET status = %s, used_at = %s WHERE state = %s",
("expired", datetime.now(timezone.utc), state))
conn.commit()
return RedirectResponse(url=f"/?status=error&message=Link je istekao", status_code=302)
google_email = verify_email_with_google(code)
req = EmailRequest(email=google_email)
sheet_data = verify_email(req)
update_query = """
UPDATE verification_attempts
SET email = %s, status = %s, used_at = %s
WHERE state = %s
"""
cursor.execute(update_query, (
google_email,
"success",
datetime.now(timezone.utc),
state
))
conn.commit()
# Preusmjeri korisnika natrag na klijentsku aplikaciju s podacima
# koje ce klijent pročitati i upotrijebiti za provjeru statusa
return RedirectResponse(url=f"/?status=success&state={state}", status_code=302)
except HTTPException as e:
if conn:
cursor.execute("UPDATE verification_attempts SET status = %s, used_at = %s WHERE state = %s",
("fail", datetime.now(timezone.utc), state))
conn.commit()
return RedirectResponse(url=f"/?status=error&message={e.detail}", status_code=302)
except Exception as e:
logging.error(f"Neočekivana greška u callbacku: {e}")
if conn:
cursor.execute("UPDATE verification_attempts SET status = %s, used_at = %s WHERE state = %s",
("fail", datetime.now(timezone.utc), state))
conn.commit()
return RedirectResponse(url=f"/?status=error&message=Došlo je do neočekivane greške", status_code=302)
finally:
if conn:
db_pool.putconn(conn)
'''
def verify_email_with_google(code: str) -> str:
client_id = os.getenv("GOOGLE_CLIENT_ID")
client_secret = os.getenv("GOOGLE_CLIENT_SECRET")
redirect_uri = os.getenv("GOOGLE_REDIRECT_URI")
token_resp = requests.post("https://oauth2.googleapis.com/token", data={
"code": code,
"client_id": client_id,
"client_secret": client_secret,
"redirect_uri": redirect_uri,
"grant_type": "authorization_code",
})
if token_resp.status_code != 200:
logging.error("Request failed pri pristupu oauth: %s", token_resp.text)
raise HTTPException(status_code=400, detail="Greška kod verifikacije (token)")
access_token = token_resp.json().get("access_token")
userinfo_resp = requests.get(
"https://www.googleapis.com/oauth2/v3/userinfo",
headers={"Authorization": f"Bearer {access_token}"}
)
if userinfo_resp.status_code != 200:
logging.error("Userinfo request failed: %s", userinfo_resp.text)
raise HTTPException(status_code=400, detail="Greška kod dohvaćanja korisnika")
return userinfo_resp.json().get("email")
@app.post("/refresh-cache")
def api_refresh_cache():
try:
refresh_cache(force=True)
return {"status": "Spreadsheet refreshed"}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Greška: {e}")
@app.post("/clear-cache")
def clear_cache():
global cached_rows, cache_timestamp, last_loaded_day
cached_rows = None
cache_timestamp = 0
last_loaded_day = None
return {"status": "Cache cleared"}