-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp3.py
More file actions
2394 lines (1997 loc) · 94 KB
/
Copy pathapp3.py
File metadata and controls
2394 lines (1997 loc) · 94 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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import html
import os
import pyodbc
import traceback
import logging
from typing import Optional
import jwt
import bcrypt
from datetime import datetime, timedelta
from typing import Union
from fastapi import FastAPI, HTTPException, Depends, status
from fastapi import Form
from fastapi.security import OAuth2PasswordBearer
from pydantic import BaseModel
import requests
from apify_client import ApifyClient
from typing import List, Dict, Any
from apify_client._errors import ApifyApiError
import json
import cv2
from fastapi import FastAPI, Depends, HTTPException, UploadFile, File, Query, Header
from azure.storage.blob import BlobServiceClient, ContentSettings
from instagram import Instagram
from bs4 import BeautifulSoup
from fastapi.responses import JSONResponse
import instaloader
import mailtrap as mt
import secrets
import smtplib
logging.basicConfig(level=logging.INFO)
# Build domain -> university name lookup from bundled JSON (loaded once at startup)
_UNIVERSITY_DOMAIN_MAP: dict[str, str] = {}
try:
_data_path = os.path.join(os.path.dirname(__file__), "data", "universities.json")
with open(_data_path, "r", encoding="utf-8") as _f:
for _entry in json.load(_f):
for _domain in _entry.get("domains", []):
_UNIVERSITY_DOMAIN_MAP[_domain.lower()] = _entry["name"]
logging.info(f"Loaded {len(_UNIVERSITY_DOMAIN_MAP)} university domains.")
except Exception as _e:
logging.warning(f"Could not load universities.json: {_e}")
sending_email = "hawkeyehelp.noreply@gmail.com"
server = smtplib.SMTP("smtp.gmail.com",587)
server.starttls()
server.login(sending_email, "wnoq yzbk lqah pnqb")
# JWT Secret Key
SECRET_KEY = "43581f2ce3c30dac3191986e251dba7a8802ad7aa73641265d14744b24f18bdc"
REFRESH_SECRET_KEY = "0e5faaf7ff563aee3370140cd4c61b78097b700185bb655cda70ff47e83ff2bc88df468885df169dc96e8d84689a037942c5e72517d2ebb71239322789845da0"
ALGORITHM = "HS256"
#dsf
MAILTRAP_TOKEN = "1996707852d8b747152387db18b44f1f"
ADMIN_SECRET = "hawkeye-admin-2026"
connection_string_blob = os.getenv("AZURE_STORAGE_CONNECTION_STRING")
container_name = "reports-to-be-validated"
subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY")
ocr_endpoint = "https://hawkeye-cv-test2-hanavmodasiya.cognitiveservices.azure.com/vision/v3.2/ocr"
frame_output_dir = "frames"
CONTAINER_NAME_IG = "instagram-sessions"
BLOB_NAME_IG = "sessionfile"
blob_service_client = BlobServiceClient.from_connection_string(connection_string_blob)
client = ApifyClient(os.getenv("APIFY_API"))
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="login")
def download_cookies_from_blob():
"""Downloads the full Instagram cookies JSON file from Azure Blob Storage"""
try:
blob_service_client = BlobServiceClient.from_connection_string(connection_string_blob)
blob_client = blob_service_client.get_blob_client(container=CONTAINER_NAME_IG, blob="instagram_cookies.json")
# Download the entire file
with open("/tmp/instagram_cookies.json", "wb") as file:
stream = blob_client.download_blob()
file.write(stream.readall())
# Confirm file integrity
if os.path.getsize("/tmp/instagram_cookies.json") == 0:
raise HTTPException(status_code=500, detail="Downloaded cookies file is empty!")
print(f"✅ Cookies downloaded successfully. File Size: {os.path.getsize('/tmp/instagram_cookies.json')} bytes")
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error downloading cookies from Azure Blob: {str(e)}")
def load_cookies():
"""Loads and verifies essential Instagram cookies from the downloaded JSON file."""
try:
with open("/tmp/instagram_cookies.json", "r") as file:
cookies = json.load(file)
# Convert the list of cookies to a usable dictionary format
if isinstance(cookies, list):
cookies_dict = {cookie["name"]: cookie["value"] for cookie in cookies}
elif isinstance(cookies, dict):
cookies_dict = cookies
else:
raise ValueError("Invalid cookie format detected.")
# Check for the presence of essential cookies
required_cookies = ["sessionid", "csrftoken", "ds_user_id"]
for cookie in required_cookies:
if cookie not in cookies_dict:
raise ValueError(f"❌ Missing required cookie: {cookie}")
print("✅ All essential cookies are present.")
return cookies_dict
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error processing cookies: {str(e)}")
def download_session_from_blob():
"""Downloads the Instagram session file from Azure Blob Storage"""
try:
blob_service_client = BlobServiceClient.from_connection_string(connection_string_blob)
blob_client = blob_service_client.get_blob_client(container=CONTAINER_NAME_IG, blob=BLOB_NAME_IG)
# Download the session file
local_path = "/tmp/sessionfile"
with open(local_path, "wb") as download_file:
download_file.write(blob_client.download_blob().readall())
# Verify if the file exists
if not os.path.exists(local_path):
raise HTTPException(status_code=500, detail="Session file not downloaded successfully.")
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to download session file: {str(e)}")
def get_full_name_instagram_with_cookies(username, proxy):
"""Fetch full name using Instagram cookies with error handling and safer requests"""
L = instaloader.Instaloader()
L.context.proxy = proxy
try:
# ✅ Step 1: Download and Load Cookies
download_cookies_from_blob()
cookies = load_cookies()
# ✅ Step 2: Apply the cookies to the session
L.context._session.cookies.update(cookies)
# ✅ Step 3: Safer authentication check using a minimal endpoint
# Avoids infinite redirects by testing a simpler API endpoint
response = L.context.get_json("accounts/current_user/?__a=1", params={})
if "status" not in response or response["status"] != "ok":
raise HTTPException(status_code=401, detail="Invalid cookies provided. Please regenerate and re-upload them.")
# ✅ Step 4: Fetch the profile
profile = instaloader.Profile.from_username(L.context, username)
full_name = profile.full_name.strip()
name_parts = full_name.split(' ', 1)
first_name, last_name = (name_parts + [''])[:2]
print(f"✅ Successfully retrieved profile for {username}.")
return first_name, last_name, None
except instaloader.exceptions.ProfileNotExistsException:
return None, None, "Error: Username not found."
except instaloader.exceptions.ConnectionException:
return None, None, "Error: Unable to connect to Instagram. Please try again later."
except instaloader.exceptions.LoginRequiredException:
return None, None, "Error: Cookies expired or invalid."
except Exception as e:
import traceback
traceback.print_exc()
return None, None, f"Error: {str(e)}"
def get_display_name(username):
# Construct the Snapchat profile URL using the username
url = f"https://www.snapchat.com/add/{username}"
# Headers to mimic a browser request
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36",
"Accept-Language": "en-US,en;q=0.9",
}
# Sending the request
response = requests.get(url, headers=headers)
# Check if the request was successful
if response.status_code == 200:
# Parse the HTML content with BeautifulSoup
soup = BeautifulSoup(response.text, 'html.parser')
# Try to extract the display name using h1
display_name = soup.select_one("h1")
# Fallback to .Heading_h400Emphasis__SQXxl span if h1 is not found
if not display_name:
display_name = soup.select_one(".Heading_h400Emphasis__SQXxl span")
bitmoji_url = soup.select_one(".UserCard_verticalSnapcode__XWFrV")
if bitmoji_url != None:
bitmoji_url = bitmoji_url.find("img")
if bitmoji_url and bitmoji_url.has_attr("src"):
raw_url = bitmoji_url["src"]
clean_url = html.unescape(raw_url)
if display_name:
# Get the text and split into first and last name
full_name = display_name.get_text().strip()
name_parts = full_name.split(" ", 1) # Split into two parts: first name and last name
first_name = name_parts[0] # First part is the first name
last_name = name_parts[1] if len(name_parts) > 1 else "" # Second part if exists is the last name
return first_name, last_name, clean_url
else:
return None, None, None
else:
return None, None, None
def get_full_name_instagram(username):
L = instaloader.Instaloader()
# Set the proxy without authentication (IP only)
L.context.proxy = "http://161.97.136.251:3128"
try:
# Load the profile from the username using the proxy
profile = instaloader.Profile.from_username(L.context, username)
# Extract full name and split into first and last name
full_name = profile.full_name.strip()
name_parts = full_name.split(' ', 1)
if len(name_parts) > 1:
first_name, last_name = name_parts
else:
first_name, last_name = name_parts[0], ''
return first_name, last_name, None # No error
except instaloader.exceptions.ProfileNotExistsException:
return None, None, "Error: Username not found."
except instaloader.exceptions.ConnectionException:
return None, None, "Error: Unable to connect to Instagram. Please try again later."
except Exception as e:
return None, None, f"Error: An unexpected error occurred - {str(e)}"
def get_full_name_instagram_2(username, proxy):
"""Fetches the full name from Instagram using a proxy and session"""
L = instaloader.Instaloader()
# Set the proxy for the Instaloader instance
L.context.proxy = None
try:
# Download and load the session file
download_session_from_blob()
L.load_session_from_file('hawkeyeapp_official', '/tmp/sessionfile')
# Fetch the Instagram profile data
profile = instaloader.Profile.from_username(L.context, username)
# Extract and split the full name
full_name = profile.full_name.strip()
name_parts = full_name.split(' ', 1)
# Split first and last name or assign blank if missing
if len(name_parts) > 1:
first_name, last_name = name_parts
else:
first_name, last_name = name_parts[0], ''
return first_name, last_name, None # No error
except instaloader.exceptions.ProfileNotExistsException:
return None, None, "Error: Username not found."
except instaloader.exceptions.ConnectionException:
return None, None, "Error: Unable to connect to Instagram. Please try again later."
except Exception as e:
return None, None, f"Error: An unexpected error occurred - {str(e)}"
#pydantic input/output formats
class Person(BaseModel):
first_name: str
last_name: Union[str, None] = None
class User(BaseModel):
email: Union[str, None] = None
password: Union[str, None] = None
class Token(BaseModel):
access_token: str
refresh_token: str
token_type: str
class UserProfile(BaseModel):
username: Union[str, None] = None
age: Union[int, None] = None
state: Union[str, None] = None
snapchat_username: Union[str, None] = None
instagram_username: Union[str, None] = None
tinder_username: Union[str, None] = None
is_premium: Union[bool, None] = None
first_name: Union[str, None] = None
last_name: Union[str, None] = None
phone_number: Union[str, None] = None
class UserProfileRequest(BaseModel):
user: Union[User, None] = None
profile: Union[UserProfile, None] = None
class UserProfileResponse(BaseModel):
user_id: int
username: str = None
age: int = None
state: str = None
snapchat_username: str = None
instagram_username: str = None
tinder_username: str = None
email: str
previously_searched: str = None
is_premium: bool = False
searched_count: int = 0
first_name: str = ""
last_name: str = ""
phone_number: str = ""
is_premium_fixed: bool
is_verified: bool
university: str = ""
class RegisterResponse(BaseModel):
access_token: str
refresh_token: str
token_type: str
email: str
university: str = ""
class ReportRequest(BaseModel):
reported_username: str
report_cause: str
report_description: str
platform: str
class VerifyEmailRequest(BaseModel):
token: str
class DeleteAccountRequest(BaseModel):
token: str
class CommentRequest(BaseModel):
comment_text: str
class SetTipsOfDayRequest(BaseModel):
tip_id_1: int
tip_id_2: int
tip_id_3: int
class SponsoredTipResponse(BaseModel):
id: int
title: str
subtitle: str = ""
banner_color1: str = ""
banner_color2: str = ""
url: str = ""
class UniversityInfoResponse(BaseModel):
name: str
domain: str = ""
police_phone: str = ""
hotline_phone: str = ""
wellness_center_phone: str = ""
recent_posts: list = []
reported_accounts: list = []
connection_string = (
"Driver={ODBC Driver 18 for SQL Server};"
"Server=tcp:hawkeye-server-test.database.windows.net,1433;"
"Database=hawkeye-DB-test;"
"Uid=CloudSA1dee5af2;"
"Pwd=Hanav@1811;"
"Encrypt=yes;"
"TrustServerCertificate=no;"
"Connection Timeout=30;"
)
class UsernameRequest(BaseModel):
username: str
proxy: str
def extract_university_domain(email: str) -> Optional[str]:
"""
Returns the full university name for a recognized university email, or None if
the email doesn't belong to any known university.
Lookup order:
1. Exact domain match (e.g. "mit.edu")
2. Progressive subdomain stripping (e.g. "students.mit.edu" -> try "mit.edu")
3. Fallback: if domain ends in .edu but isn't in the JSON, return the
normalized <name>.edu so .edu-only schools still work.
"""
try:
domain = email.split('@')[1].lower()
# Exact match
if domain in _UNIVERSITY_DOMAIN_MAP:
return _UNIVERSITY_DOMAIN_MAP[domain]
# Strip subdomains one level at a time and retry
parts = domain.split('.')
for i in range(1, len(parts) - 1):
candidate = '.'.join(parts[i:])
if candidate in _UNIVERSITY_DOMAIN_MAP:
return _UNIVERSITY_DOMAIN_MAP[candidate]
# Not in JSON — fall back to requiring .edu so non-university emails are still rejected
if domain.endswith('.edu'):
return f"{parts[-2]}.edu"
return None
except Exception:
return None
app = FastAPI()
#basic routes
@app.get("/health-check")
def health_check():
return {"status": "success", "message": "Server is reachable"}
# @app.post("/get_instagram_name")
# def get_instagram_name(request: UsernameRequest):
# first_name, last_name, error = get_full_name_instagram_with_cookies(request.username, request.proxy)
# if error:
# raise HTTPException(status_code=400, detail=error)
# return {"first_name": first_name, "last_name": last_name}
def create_refresh_token(data: dict, expires_delta: timedelta = timedelta(days=7)):
to_encode = data.copy()
expire = datetime.utcnow() + expires_delta
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, REFRESH_SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
@app.post("/refresh-token")
def refresh_token(refresh_token: str):
try:
payload = jwt.decode(refresh_token, REFRESH_SECRET_KEY, algorithms=[ALGORITHM])
user_email = payload.get("sub")
if not user_email:
raise HTTPException(status_code=401, detail="Invalid token")
access_token = create_access_token(data={"sub": user_email})
return {"access_token": access_token}
except jwt.ExpiredSignatureError:
raise HTTPException(status_code=401, detail="Refresh token expired")
except jwt.InvalidTokenError:
raise HTTPException(status_code=401, detail="Invalid refresh token")
def create_access_token(data: dict, expires_delta:Optional[timedelta] = None):
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow()+expires_delta
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
def verify_token(token: str):
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
return payload
except jwt.ExpiredSignatureError:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED, detail="Token expired"
)
except jwt.InvalidTokenError:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token"
)
def get_current_user(token: str = Depends(oauth2_scheme)):
payload = verify_token(token)
user_email = payload.get("sub")
if user_email is None:
raise HTTPException(status_code=401, detail="Invalid token")
return user_email
# Routes
@app.get("/")
def root():
try:
conn = get_conn()
cursor = conn.cursor()
cursor.execute("""
IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='Persons' and xtype='U')
CREATE TABLE Persons (
ID int NOT NULL PRIMARY KEY IDENTITY,
FirstName varchar(255),
LastName varchar(255)
);
""")
conn.commit()
except Exception as e:
print(f"Error: {e}")
return {"message": "Person API root"}
# # instagram script
# def test_proxy(proxy):
# try:
# response = requests.get("https://httpbin.org/ip", proxies={"http": proxy, "https": proxy})
# return response.json()
# except Exception as e:
# raise HTTPException(status_code=500, detail=f"Proxy test failed: {str(e)}")
# @app.post("/test_proxy")
# def proxy_test(request: UsernameRequest):
# return test_proxy(request.proxy)
#User authentication routes
@app.post("/login", response_model=Token)
def login_user(user: User):
try:
conn = get_conn()
cursor = conn.cursor()
cursor.execute("SELECT HashedPassword FROM Users WHERE Email = ?", user.email)
db_user = cursor.fetchone()
if not db_user or not bcrypt.checkpw(user.password.encode('utf-8'), db_user.HashedPassword.encode('utf-8')):
raise HTTPException(status_code=401, detail="Invalid credentials")
except Exception as e:
raise HTTPException(status_code=400, detail=f"Error logging in: {str(e)}")
access_token = create_access_token(data={"sub": user.email})
refresh_token = create_refresh_token(data={"sub": user.email})
return {"access_token": access_token, "refresh_token": refresh_token,"token_type": "bearer"
}
@app.post("/set-profile")
def set_user_profile(user_profile: UserProfileRequest):
try:
if not user_profile.user or not user_profile.user.email:
raise HTTPException(status_code=422, detail="Email is required.")
email = user_profile.user.email
password = user_profile.user.password if user_profile.user else None
profile_data = user_profile.profile if user_profile.profile else None
conn = get_conn()
cursor = conn.cursor()
cursor.execute("SELECT * FROM Users WHERE Email = ?", email)
db_user = cursor.fetchone()
if not db_user:
raise HTTPException(status_code=404, detail="User not found")
if password and not bcrypt.checkpw(password.encode('utf-8'), db_user.HashedPassword.encode('utf-8')):
raise HTTPException(status_code=401, detail="Invalid credentials")
university = extract_university_domain(email)
cursor.execute("""
MERGE INTO UserProfiles AS target
USING (VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)) AS source
(Email, Username, Age, State, SnapchatUsername, InstagramUsername, TinderUsername, is_premium, searched_count, firstName, lastName, phoneNumber, University)
ON target.Email = source.Email
WHEN MATCHED THEN
UPDATE SET
Username = COALESCE(source.Username, target.Username),
Age = COALESCE(source.Age, target.Age),
State = COALESCE(source.State, target.State),
SnapchatUsername = COALESCE(source.SnapchatUsername, target.SnapchatUsername),
InstagramUsername = COALESCE(source.InstagramUsername, target.InstagramUsername),
TinderUsername = COALESCE(source.TinderUsername, target.TinderUsername),
is_premium = COALESCE(source.is_premium, target.is_premium),
firstName = COALESCE(source.firstName, target.firstName),
lastName = COALESCE(source.lastName, target.lastName),
phoneNumber = COALESCE(source.phoneNumber, target.phoneNumber),
University = COALESCE(source.University, target.University)
WHEN NOT MATCHED THEN
INSERT (Email, Username, Age, State, SnapchatUsername, InstagramUsername, TinderUsername, is_premium, searched_count, firstName, lastName, phoneNumber, University)
VALUES (source.Email, source.Username, source.Age, source.State, source.SnapchatUsername, source.InstagramUsername, source.TinderUsername, source.is_premium, 0, source.firstName, source.lastName, source.phoneNumber, source.University);
""", (
email,
profile_data.username if profile_data else None,
profile_data.age if profile_data else None,
profile_data.state if profile_data else None,
profile_data.snapchat_username if profile_data else None,
profile_data.instagram_username if profile_data else None,
profile_data.tinder_username if profile_data else None,
profile_data.is_premium if profile_data else None,
0,
profile_data.first_name if profile_data else None,
profile_data.last_name if profile_data else None,
profile_data.phone_number if profile_data else None,
university
))
conn.commit()
return {"message": "profile made or updated..."}
except Exception as e:
# import traceback
# traceback.print_exc()
raise HTTPException(status_code=400, detail=f"profile error: {e}")
@app.post("/register", response_model=RegisterResponse)
def register_user(user: User):
university = extract_university_domain(user.email)
if not university:
raise HTTPException(status_code=400, detail="Registration requires a .edu university email address.")
hashed_password = bcrypt.hashpw(user.password.encode('utf-8'), bcrypt.gensalt())
try:
conn = get_conn()
cursor = conn.cursor()
verification_token = secrets.token_urlsafe(32)
last_verification_code_date = datetime.now()
cursor.execute("""
INSERT INTO Users (Email, HashedPassword, last_verification_code, last_verification_code_date)
VALUES (?, ?, ?, ?)
""", (user.email, hashed_password, verification_token, last_verification_code_date))
# Create a minimal UserProfiles row so the university is immediately available
cursor.execute("""
INSERT INTO UserProfiles (Email, University, searched_count)
VALUES (?, ?, 0)
""", (user.email, university))
conn.commit()
except Exception as e:
raise HTTPException(status_code=400, detail=f"Error creating user: {str(e)}")
access_token = create_access_token(data={"sub": user.email})
refresh_token = create_refresh_token(data={"sub": user.email})
try:
verification_url = f"https://hawkeye-backend-python-test2-hwfugva4aacwhggz.westus-01.azurewebsites.net/verify-email?token={verification_token}"
mail = mt.Mail(
sender=mt.Address(email="noresponse@hawkeyeappus.com", name="Hawkeye Support"),
to=[mt.Address(email=user.email)],
subject="Verify your email",
text=f"Click the link below to verify your email:\n{verification_url}",
category="Email Verification Test",
)
client = mt.MailtrapClient(token=MAILTRAP_TOKEN)
response = client.send(mail)
print(response)
except Exception as e:
logging.warning(f"Verification email failed to send for {user.email}: {e}")
return {
"access_token": access_token,
"refresh_token": refresh_token,
"token_type": "bearer",
"email": user.email,
"university": university,
}
@app.post("/send-email-verification", dependencies=[Depends(get_current_user)])
def send_email_verification(user_email: str = Depends(get_current_user)):
try:
conn = get_conn()
cursor = conn.cursor()
verification_token = secrets.token_urlsafe(32)
last_verification_code_date = datetime.now()
cursor.execute("""
UPDATE Users
SET last_verification_code = ?, last_verification_code_date = ?
WHERE Email = ?
""", (verification_token, last_verification_code_date, user_email))
conn.commit()
verification_url = f"https://hawkeye-backend-python-test2-hwfugva4aacwhggz.westus-01.azurewebsites.net/verify-email?token={verification_token}"
mail = mt.Mail(
sender=mt.Address(email="noresponse@hawkeyeappus.com", name="Hawkeye Support"),
to=[mt.Address(email=user_email)],
subject="Verify your email",
text=f"Click the link below to verify your email:\n{verification_url}",
category="Email Verification",
)
client = mt.MailtrapClient(token=MAILTRAP_TOKEN)
client.send(mail)
return {"message": "Check inbox for verification email."}
except Exception as e:
logging.error(f"Error sending verification email to {user_email}: {e}")
raise HTTPException(status_code=500, detail=f"Failed to send verification email: {str(e)}")
@app.get("/verify-email")
def verify_email(token: str = Query(..., description="Verification token")):
if not token:
raise HTTPException(status_code=400, detail="Token is missing")
try:
# Connect to the database
conn = get_conn()
cursor = conn.cursor()
# Look up the user by verification token
cursor.execute("""
SELECT Email, last_verification_code, last_verification_code_date
FROM Users
WHERE last_verification_code = ?
""", (token,))
user = cursor.fetchone()
if not user:
raise HTTPException(status_code=400, detail="Invalid token")
# Check if the token has expired (using last_verification_code_date)
token_created_at = user[2] # last_verification_code_date is the 4th field in the query
token_age = datetime.now() - token_created_at
if token_age > timedelta(hours=24): # Set token expiration period to 24 hours
raise HTTPException(status_code=400, detail="Token has expired")
# Mark the email as verified
cursor.execute("""
UPDATE UserProfiles
SET is_verified = ?
WHERE Email = ?
""", (1, user[0]))
conn.commit()
return {"message": "Email verified successfully! Reload the Hawkeye App to see updates."}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error verifying email: {str(e)}")
@app.post("/request-account-deletion", dependencies=[Depends(get_current_user)])
def request_account_deletion(user_email: str = Depends(get_current_user)):
try:
conn = get_conn()
cursor = conn.cursor()
# Generate verification token and store it
deletion_token = secrets.token_urlsafe(32)
deletion_token_date = datetime.now()
cursor.execute("""
UPDATE Users
SET last_verification_code_delete = ?, last_verification_code_delete_date = ?
WHERE Email = ?
""", (deletion_token, deletion_token_date, user_email))
conn.commit()
# Generate verification link
deletion_url = f"https://hawkeye-backend-python-test2-hwfugva4aacwhggz.westus-01.azurewebsites.net/delete-account?token={deletion_token}"
# Send email
mail = mt.Mail(
sender=mt.Address(email="noresponse@hawkeyeappus.com", name="Hawkeye Support"),
to=[mt.Address(email=user_email)],
subject="Account Deletion Request",
text=f"Click the link below to confirm account deletion:\n{deletion_url}",
category="Account Deletion"
)
client = mt.MailtrapClient(token=MAILTRAP_TOKEN)
response = client.send(mail)
print(response)
return {"message": "Deletion email sent successfully. Please check your inbox."}
except Exception as e:
raise HTTPException(status_code=400, detail=f"Error requesting account deletion: {str(e)}")
@app.get("/delete-account")
def delete_account(token: str = Query(..., description="Verification token for account deletion")):
if not token:
raise HTTPException(status_code=400, detail="Token is missing")
try:
conn = get_conn()
cursor = conn.cursor()
# Verify token
cursor.execute("""
SELECT Email, last_verification_code_delete, last_verification_code_delete_date
FROM Users
WHERE last_verification_code_delete = ?
""", (token,))
user = cursor.fetchone()
if not user:
raise HTTPException(status_code=400, detail="Invalid or expired token")
# Check token expiration
token_created_at = user[2]
token_age = datetime.now() - token_created_at
if token_age > timedelta(hours=24):
raise HTTPException(status_code=400, detail="Token has expired")
# Delete the user account
cursor.execute("""
DELETE FROM Users
WHERE Email = ?
""", (user[0],))
conn.commit()
cursor.execute("""
DELETE FROM UserProfiles
WHERE Email = ?
""", (user[0],))
conn.commit()
return {"message": "Your account has been successfully deleted."}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error deleting account: {str(e)}")
@app.get("/fetch-user-profile/{email}", response_model=UserProfileResponse)
def fetch_user_profile(email: str):
conn = get_conn()
cursor = conn.cursor()
query = """
SELECT UserID, Username, Age, State, SnapchatUsername, InstagramUsername, TinderUsername, Email,
Previously_Searched, is_premium, searched_count, firstName, lastName, phoneNumber, isPremiumFixed, is_verified, University
FROM dbo.UserProfiles
WHERE Email = ?
"""
cursor.execute(query, email)
row = cursor.fetchone()
if row:
# Handle the case where fields might be None
if row.Username is None:
raise HTTPException(status_code=404, detail="User profile not found or missing username")
return UserProfileResponse(
user_id=-1,
username=row.Username if row.Username else "",
age=row.Age if row.Age else 0,
state=row.State if row.State else "",
snapchat_username=row.SnapchatUsername if row.SnapchatUsername else "",
instagram_username=row.InstagramUsername if row.InstagramUsername else "",
tinder_username=row.TinderUsername if row.TinderUsername else "",
email=row.Email,
previously_searched=row.Previously_Searched if row.Previously_Searched else "",
is_premium=row.is_premium if row.is_premium is not None else False,
searched_count=row.searched_count if row.searched_count is not None else 0,
first_name=row.firstName if row.firstName else "",
last_name=row.lastName if row.lastName else "",
phone_number=row.phoneNumber if row.phoneNumber else "",
is_premium_fixed=row.isPremiumFixed if row.isPremiumFixed is not None else False,
is_verified=row.is_verified if row.is_verified is not None else False,
university=row.University if row.University else ""
)
else:
raise HTTPException(status_code=404, detail="User profile not found")
INSTA_ACTOR_ID = "apify/instagram-profile-scraper"
def fetch_profiles_insta(usernames: List[str], include_about: bool = False, timeout_secs: int = 30 ) -> List[Dict[str, Any]]:
# print(os.getenv("APIFY_API"))
client = ApifyClient(os.getenv("APIFY_API"))
INSTA_ACTOR_ID = "apify/instagram-profile-scraper"
run_input = {
"includeAboutSection": include_about,
"usernames": usernames,
}
try:
run = client.actor(INSTA_ACTOR_ID).call(
run_input=run_input,
timeout_secs=timeout_secs
)
dataset_id = run["defaultDatasetId"]
results = list(client.dataset(dataset_id).iterate_items())
return results
except ApifyApiError as e:
return f"Apify API error: {e}"
except Exception as e:
return "Unexpected error while fetchinjg profiles"
# logger = logging.getLogger(__name__)
def get_profiles_insta(usernames: list[str]):
try:
results = fetch_profiles_insta(usernames)
return {"success": True, "data": results}
except Exception:
return (" failed")
#Searching routes
# @app.get("/searchInstagramTest/{username}")
# def search_instagram_test(username: str):
# return {"user_data": fetch_profiles_insta([username])}
#Reporting routes
@app.post("/reportUser")
async def report_user(
reported_username: str = Form(...),
report_cause: str = Form(...),
report_description: str = Form(...),
platform: str = Form(...),
video: Optional[UploadFile] = File(None),
token: str = Depends(oauth2_scheme)
):
try:
payload = verify_token(token)
reporter_email = payload.get("sub")
if not reporter_email:
raise HTTPException(status_code=401, detail="Invalid token")
conn = get_conn()
cursor = conn.cursor()
cursor.execute("SELECT ID, Username, University FROM UserProfiles WHERE Email = ?", (reporter_email,))
reporter_row = cursor.fetchone()
if not reporter_row:
raise HTTPException(status_code=404, detail="reporter username is not found")
reporter_id = reporter_row[0]
reporter_username = reporter_row[1]
reporter_university = reporter_row[2] or extract_university_domain(reporter_email)
platform = platform.lower()
valid_platforms = ["snapchat", "instagram", "tinder"]
if platform not in valid_platforms:
raise HTTPException(status_code=400, detail="use 'snapchat' or 'instagram'. Case is sensitive!!")
first_name = ""
last_name = ""
image_link = None
if platform == "snapchat":
first_name_temp, last_name_temp, image_link = get_display_name(reported_username)
if not first_name_temp:
return JSONResponse(status_code=404, content={"detail": "Username does not exist"})
first_name = first_name_temp
last_name = last_name_temp
if platform == "instagram":
try:
results_insta = get_profiles_insta([reported_username])
if (results_insta["success"] == False):
return JSONResponse(status_code=404, content={"detail": f"Username does not exist instagram"})
image_link = results_insta["data"][0]["profilePicUrlHD"]
full_name = results_insta["data"][0]["fullName"]
first_name_temp = ""
last_name_temp = ""
if full_name:
name_parts = full_name.split(" ")
first_name_temp = name_parts[0]
last_name_temp = name_parts[1] if len(name_parts) > 1 else ""
first_name = first_name_temp
last_name = last_name_temp
except Exception as e:
return JSONResponse(status_code=404, content={"detail": f"Username does not exist instagram, error: {e}"})
if image_link is None:
image_link = "na"
video_path = None
if video:
video_dir = "temp_videos"
if not os.path.exists(video_dir):
os.makedirs(video_dir)
video_path = f"{video_dir}/{reported_username}_{datetime.now().strftime('%Y%m%d-%H%M%S')}.mp4"
with open(video_path, "wb") as f:
f.write(await video.read())
extracted_text = process_video(video_path, frame_interval=120)
else:
extracted_text = ""
# --- DB insertion (unverified) ---
if platform == "snapchat":
table_name = "ReportedUsersSnapchat"
first_name_field = "Snapchat_Account_FirstName"
last_name_field = "Snapchat_Account_LastName"
foreign_key_column = "SnapchatUserID"
elif platform == "instagram":
table_name = "ReportedUsersInstagram"
first_name_field = "Instagram_Account_FirstName"
last_name_field = "Instagram_Account_LastName"
foreign_key_column = "InstagramUserID"
elif platform == "tinder":
table_name = "ReportedUsersTinder"
first_name_field = "Tinder_Account_FirstName"