-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
3053 lines (2491 loc) · 136 KB
/
main.py
File metadata and controls
3053 lines (2491 loc) · 136 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 yaml
from fastapi import FastAPI, Request, HTTPException, Depends, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, Response, JSONResponse
from fastapi.security import OAuth2PasswordRequestForm
from linkml.generators.pydanticgen import PydanticGenerator
from linkml.linter.linter import Linter
from linkml.linter.formatters import JsonFormatter
from linkml_runtime.linkml_model.meta import SchemaDefinition
from openai import OpenAI, OpenAIError, APIError, RateLimitError
from pydantic import BaseModel, Field
from typing import List, Annotated
from database import SessionLocal, engine
from sqlalchemy.orm import Session
from sqlalchemy import text
from dotenv import load_dotenv
from datetime import date, datetime, timedelta, time
from security import hash_password, verify_password, create_access_token, get_current_user, Token
from gmail_service import send_email
from typing import List
import models
import os
import tempfile
import logging
import asyncio
from email_listener import listen_notifications
from typing import Optional
import pytz
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
from ontologies.ontologies import router as ontologies_router, refresh_all as refresh_ontologies, refresh_state, background_refresh
from ontologies.cache import is_empty
from expire_subscriptions_job import expire_subscriptions_job
import chromadb
import re
import openai
import json
import Levenshtein
local_tz = pytz.timezone("Europe/Rome")
load_dotenv(override=True)
admin_email = os.getenv("ADMIN_EMAIL")
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
app = FastAPI(
docs_url="/api/docs/", redoc_url="/api/redoc/", openapi_url="/api/openapi.json"
)
# models.Base.metadata.create_all(bind=engine) # Create tables in the database
# Defining Pydantic Models for Data Validation
class UserBase(BaseModel):
username: str
email: str
password: str
firstName: str
lastName: str
birthDate: date
status: str
class UsernameRequest(BaseModel):
username: str
class UpdateUserStatusRequest(BaseModel):
username: str
newStatus: str
class OperationRequest(BaseModel):
username: str
operation: str
class UserResponse(BaseModel):
username: str
email: str
firstName: str
lastName: str
birthDate: date
status: str
class Config:
orm_mode = True
class UserLogin(BaseModel):
username: str
password: str
class UserSubscribesPolicyBase(BaseModel):
username: str
startDate: Optional[datetime] = None
endDate: Optional[datetime] = None
requestDate: datetime
status: str
policyName: str
class Config:
orm_mode = True
class UserSubscribesPolicyRequest(BaseModel):
username: str
policyName: str
class UserMadeOperationInput(BaseModel):
username: str
operationName: str
class UserUpdateRequest(BaseModel):
username: str
email: Optional[str] = Field(default=None)
firstName: Optional[str] = Field(default=None)
lastName: Optional[str] = Field(default=None)
birthDate: Optional[str] = Field(default=None)
password: Optional[str] = Field(default=None)
class ContributeRequest(BaseModel):
username: str
diagramName: str
graphJson: str
# Database Connection Function
def get_db ():
db = SessionLocal()
try:
yield db
finally:
db.close()
db_dependency = Annotated[Session, Depends(get_db)]
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"], # Allows all methods
allow_headers=["*"], # Allows all headers
)
# Mount ontologies router under /api
app.include_router(ontologies_router, prefix="/api")
# Register a User
@app.post("/api/auth/register/")
async def register_user(user: UserBase, db: db_dependency):
existing_user = db.query(models.User).filter(models.User.username == user.username).first()
if existing_user:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="username already exists."
)
existing_email = db.query(models.User).filter(models.User.email == user.email).first()
if existing_email:
if existing_email.status == "pending":
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="email already exists and is pending approval."
)
elif existing_email.status == "active":
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="email already exists."
)
elif existing_email.status == "blocked":
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="email already exists and is blocked."
)
hashed_pw = hash_password(user.password)
db_user = models.User(
username=user.username,
email=user.email,
password=hashed_pw,
firstName=user.firstName,
lastName=user.lastName,
birthDate=user.birthDate,
status="pending"
)
db.add(db_user)
db.commit()
db.refresh(db_user)
subject = "New user awaiting approval"
body = (
f"A new user has just registered on SchemaLink and is awaiting approval:\n\n"
f"Username: {user.username}\n"
f"Email: {user.email}"
f"\n\nSchemaLink Notification System"
)
logging.info(f"Sending email to notify admin of new registration: {user.email}")
send_email(to_email=admin_email, subject=subject, message=body)
return {
"username": db_user.username,
"email": db_user.email,
"firstName": db_user.firstName,
"lastName": db_user.lastName,
"status": db_user.status
}
# Login a User and return JWT Token
@app.post("/api/auth/login/")
async def login_user(user: UserLogin, db: db_dependency):
db_user = db.query(models.User).filter(models.User.username == user.username).first()
if not db_user:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="user account not found."
)
if not verify_password(user.password, db_user.password):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="incorrect password."
)
if db_user.status=='pending':
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="user account not yet approved."
)
if db_user.status == "blocked":
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="user account is blocked."
)
if db_user.status == "disabled":
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="user account is disabled."
)
access_token_expires = timedelta(minutes=30)
access_token = create_access_token(data={"sub": db_user.username}, expires_delta=access_token_expires)
response_data = {
"message": "Login successful",
"access_token": access_token,
"user": {
"username": db_user.username,
"email": db_user.email,
"firstName": db_user.firstName,
"lastName": db_user.lastName,
"birthDate": db_user.birthDate.isoformat() if db_user.birthDate else None,
"status": db_user.status
}
}
response = JSONResponse(content=response_data)
response.set_cookie(
key="access_token",
value=access_token,
httponly=True, # Not accessible by JavaScript (prevents XSS)
secure=False, # ONLY in development, set to True in production
samesite="Lax", # Prevents CSRF, but allows use across subdomains
max_age=1800, # Expiration time (30 min)
)
return response
# Logout a User
@app.post("/api/auth/logout/")
async def logout_user():
response = JSONResponse(content={"message": "Logged out"})
response.delete_cookie("access_token")
return response
# Delete user account
@app.post("/api/auth/delete-account/")
async def delete_account(db: db_dependency, current_user: str = Depends(get_current_user)):
db_user = db.query(models.User).filter(models.User.username == current_user).first()
db_user.status = "disabled"
db.commit()
db.refresh(db_user)
subscriptions = db.query(models.UserSubscribesPolicy).filter(
models.UserSubscribesPolicy.username == db_user.username,
models.UserSubscribesPolicy.status.in_(["active", "pending"])
).all()
for sub in subscriptions:
if sub.status == "active":
sub.status = "expired"
sub.endDate = datetime.now(local_tz)
elif sub.status == "pending":
sub.status = "expired"
db.commit()
admin_subject = f"Account deletion notice: {db_user.username}"
admin_body = (
f"The following user has deleted his account from SchemaLink:\n\n"
f"Username: {db_user.username}\n"
f"Email: {db_user.email}\n\n"
f"SchemaLink Notification System"
)
send_email(to_email=admin_email, subject=admin_subject, message=admin_body)
return JSONResponse(content={"message": "Account successfully deleted."})
# Get all users
@app.post("/api/get-users/", response_model=List[UserResponse])
async def get_users(db: db_dependency):
db_users = db.query(models.User).all()
return db_users
# Update user status
@app.post("/api/update-status/")
async def update_user_status( status_update: UpdateUserStatusRequest, db: db_dependency):
user = db.query(models.User).filter(models.User.username == status_update.username).first()
if not user:
raise HTTPException(
status_code=404,
detail="User not found"
)
# Business rule validation on the backend side
valid_transitions = {
"pending": ["active", "disabled"],
"active": ["disabled", "blocked"],
"blocked": ["active"]
}
current_status = user.status
new_status = status_update.newStatus
if current_status not in valid_transitions or new_status not in valid_transitions[current_status]:
raise HTTPException(
status_code=400,
detail=f"Invalid status change from {current_status} to {new_status}"
)
user.status = new_status
db.commit()
db.refresh(user)
return {
"message": f"Status of {user.username} updated from {current_status} to {new_status}",
"user": {
"username": user.username,
"status": user.status
}
}
# Get all user subscriptions to policies
@app.post("/api/get-user-subscriptions/", response_model=List[UserSubscribesPolicyBase])
async def get_user_subscriptions(db: db_dependency):
db_subscriptions = db.query(models.UserSubscribesPolicy).all()
return db_subscriptions
# Update user policy status
@app.post("/api/update-subscription-status/")
async def update_subscription_status( status_subscription_update: UpdateUserStatusRequest, db: db_dependency):
policySubscription = db.query(models.UserSubscribesPolicy).filter(
models.UserSubscribesPolicy.username == status_subscription_update.username,
models.UserSubscribesPolicy.status == "pending"
).first()
if not policySubscription:
raise HTTPException(
status_code=404,
detail="Policy subscription not found"
)
# Business rule validation on the backend side
valid_transitions = {
"pending": ["active", "rejected"],
}
current_status = policySubscription.status
new_status = status_subscription_update.newStatus
if current_status not in valid_transitions or new_status not in valid_transitions[current_status]:
raise HTTPException(
status_code=400,
detail=f"Invalid status change from {current_status} to {new_status}"
)
policySubscription.status = new_status
if new_status == "active":
now = datetime.now(local_tz)
existing_active = db.query(models.UserSubscribesPolicy).filter(
models.UserSubscribesPolicy.username == policySubscription.username,
models.UserSubscribesPolicy.status == "active",
models.UserSubscribesPolicy.startDate <= now,
models.UserSubscribesPolicy.endDate >= now
).first()
residual_operations = 0
if existing_active and policySubscription.policyName != "platinum":
used_operations = db.query(models.UserMadeOperation).filter(
models.UserMadeOperation.username == existing_active.username,
models.UserMadeOperation.date >= existing_active.startDate,
models.UserMadeOperation.date <= existing_active.endDate
).count()
total_allowed = existing_active.numOperations or 0
residual_operations = max(total_allowed - used_operations, 0)
if existing_active:
existing_active.status = "expired"
existing_active.endDate = now
policySubscription.startDate = now
if policySubscription.policyName == "silver":
duration_days = 3
maxAccess = 50
elif policySubscription.policyName == "gold":
duration_days = 7
maxAccess = 100
elif policySubscription.policyName == "platinum":
duration_days = 7
maxAccess = None
else:
raise HTTPException(status_code=400, detail="Invalid policy name")
if policySubscription.policyName != "platinum":
policySubscription.numOperations = maxAccess + residual_operations
else:
policySubscription.numOperations = None
policySubscription.endDate = now + timedelta(days=duration_days)
db.commit()
db.refresh(policySubscription)
return {
"message": f"Status of policy of {policySubscription.username} to {policySubscription.policyName} updated from {current_status} to {new_status}",
"subscription": {
"username": policySubscription.username,
"policyName": policySubscription.policyName,
"status": policySubscription.status,
"startDate": policySubscription.startDate,
"endDate": policySubscription.endDate
}
}
# User is authorized to perform operation
@app.post("/api/canPerformOperation/")
async def check_user_operation(request_data: OperationRequest, db: db_dependency):
username = request_data.username
operation = request_data.operation
#print("Username received:", username)
#print("Operation received:", operation)
# Username null
if not username:
return JSONResponse(content={"allowed": False, "reason": "You must register to request intelligent operations."})
# Admin user
if username == "schemalink":
return JSONResponse(content={"allowed": True})
now = datetime.now(local_tz)
# Active policy
policy_subscription = db.execute(
text ("""
SELECT startDate, policyName
FROM UserSubscribesPolicy
WHERE username = :username
AND startDate <= :now
AND endDate >= :now
AND status = 'active'
ORDER BY startDate DESC
LIMIT 1
"""),
{"username": username, "now": now}
).fetchone()
if not policy_subscription:
return JSONResponse(content={"allowed": False, "reason": "No active subscription policy."})
start_date = policy_subscription[0]
policy_name = policy_subscription[1]
if policy_name == "platinum":
return JSONResponse(content={"allowed": True, "policy": policy_name})
max_access = db.execute(
text("""
SELECT numOperations
FROM UserSubscribesPolicy
WHERE username = :username
AND startDate <= :now
AND endDate >= :now
AND status = 'active'
"""),
{"username": username, "now": now}
).scalar()
# Operations performed by the user
user_ops_count = db.execute(
text("""SELECT COUNT(*)
FROM UserMadeOperation
WHERE username = :username
AND date >= :start_date
"""),
{"username": username, "start_date": start_date}
).scalar()
if user_ops_count >= max_access:
return JSONResponse(content={"allowed": False, "reason": "You reached the maximum number of intelligent requests for your policy."})
return JSONResponse(content={"allowed": True, "policy": policy_name})
# User made operation
@app.post("/api/user-operation/")
async def log_user_operation(operation: UserMadeOperationInput, db: db_dependency):
try:
now = datetime.now(local_tz)
db_operation = models.UserMadeOperation(
username=operation.username,
operationName=operation.operationName,
date=now
)
db.add(db_operation)
db.commit()
db.refresh(db_operation)
threshold_reached = False
policy = None
subscription = None
if (operation.username != "schemalink"):
subscription = db.query(models.UserSubscribesPolicy).filter(
models.UserSubscribesPolicy.username == operation.username,
models.UserSubscribesPolicy.status == 'active'
).order_by(models.UserSubscribesPolicy.startDate.desc()).first()
if subscription:
policy = db.query(models.Policy).filter_by(name=subscription.policyName).first()
if policy:
op_count = db.query(models.UserMadeOperation).filter(
models.UserMadeOperation.username == operation.username,
models.UserMadeOperation.date >= subscription.startDate,
models.UserMadeOperation.date <= now
).count()
threshold_reached = False
if (policy.name != "platinum"):
threshold = policy.threshold if policy.threshold is not None else 0
if op_count == (subscription.numOperations - threshold):
threshold_reached = True
user = db.query(models.User).filter_by(username=operation.username).first()
if user:
subject = f"You have {policy.threshold} operations remaining on your '{policy.name}' plan"
body = (
f"Hi {user.username},\n\n"
f"You have {policy.threshold} intelligent requests remaining"
f"under your current '{policy.name}' subscription plan.\n\n"
f"Once you reach the limit of {subscription.numOperations} intelligent requests, your subscription will expire "
f"and you will no longer be able to use intelligent requests.\n\n"
f"To continue uninterrupted, consider upgrading or renewing your plan.\n\n"
f"Thank you for using SchemaLink!\n"
f"\nBest regards,\n"
f"The SchemaLink Team"
)
send_email(to_email=user.email, subject=subject, message=body)
if op_count >= subscription.numOperations:
subscription.status = 'expired'
subscription.endDate = now
db.commit()
return {
"message": "Operation logged successfully.",
"thresholdReached": threshold_reached,
"data": {
"username": db_operation.username,
"operationName": db_operation.operationName,
"date": db_operation.date,
"policyName": policy.name if policy else None,
"policyThreshold": policy.threshold if policy else None,
"policyMaxAccess": subscription.numOperations if subscription else None
}
}
except Exception as e:
print(f"Error: {e}")
return JSONResponse(status_code=500, content={"message": "Internal server error"})
# User subscribes to a policy
@app.post("/api/subscribe-policy/")
async def subscribe_policy( data: UserSubscribesPolicyRequest, db: db_dependency):
user = db.query(models.User).filter(models.User.username == data.username).first()
if not user:
raise HTTPException(status_code=404, detail="User not found")
now = datetime.now(local_tz)
pending_policy = db.execute(
text("""
SELECT policyName FROM UserSubscribesPolicy
WHERE username = :username
AND status = 'pending'
"""),
{"username": data.username}
).fetchone()
if pending_policy:
raise HTTPException(
status_code=400,
detail="User already has a pending policy request."
)
active_policy = db.execute(
text ("""
SELECT policyName AS "policyName", requestDate AS "requestDate"
FROM UserSubscribesPolicy
WHERE username = :username
AND startDate <= :now
AND endDate >= :now
AND status = 'active'
"""),
{"username": data.username, "now": now}
).mappings().fetchone()
current_policy = active_policy["policyName"].lower() if active_policy else None
request_date = active_policy["requestDate"] if active_policy else None
requested = data.policyName.lower()
allowed_transitions = {
None: ["trial", "silver", "gold", "platinum"], # No policy
"trial": ["silver", "gold", "platinum"],
"silver": ["gold", "platinum"],
"gold": ["platinum"],
"platinum": []
}
if requested not in allowed_transitions[current_policy]:
raise HTTPException(
status_code=400,
detail=f"Cannot subscribe to '{requested}' while having '{current_policy or 'no'}' policy active."
)
new_subscription = models.UserSubscribesPolicy(
username=data.username,
policyName=data.policyName,
requestDate = now,
startDate=None,
endDate=None,
status='pending'
)
db.add(new_subscription)
db.commit()
db.refresh(new_subscription)
subject = " Policy Subscription Request Pending Approva"
body = (
f"The user **{data.username}** has requested to subscribe to the **{data.policyName}** policy."
f"\n\nSchemaLink Notification System"
)
logging.info(f"Sending email to notify policy request")
send_email(to_email=admin_email, subject=subject, message=body)
return {
"message": "Policy subscription request created successfully.",
"data": {
"username": new_subscription.username,
"policyName": new_subscription.policyName,
"requestDate": new_subscription.requestDate
}
}
# Get user subscription details
@app.post("/api/get-user-subscription-details/")
async def get_user_subscription_details(request: UsernameRequest, db: db_dependency):
username = request.username
user = db.query(models.User).filter(models.User.username == username).first()
if not user:
raise HTTPException(
status_code=404,
detail="User not found"
)
subscription = db.query(models.UserSubscribesPolicy).filter(
models.UserSubscribesPolicy.username == username,
models.UserSubscribesPolicy.status == 'active'
).order_by(models.UserSubscribesPolicy.requestDate.desc()).first()
if not subscription:
return {
"hasSubscription": False
}
policy = db.query(models.Policy).filter(models.Policy.name == subscription.policyName).first()
operations_done = db.query(models.UserMadeOperation).filter(
models.UserMadeOperation.username == username,
models.UserMadeOperation.date >= subscription.startDate,
models.UserMadeOperation.date <= subscription.endDate
).count()
now = datetime.now(local_tz)
subscription_end = subscription.endDate.astimezone(local_tz)
delta = subscription_end - now
hours_remaining = delta.seconds // 3600 + delta.days * 24
minutes_remaining = (delta.seconds % 3600) // 60
remaining_time_str = f"{int(hours_remaining)}:{int(minutes_remaining):02d}"
return {
"hasSubscription": True,
"policyName": policy.name,
"operationsDone": operations_done,
"maxAccess": subscription.numOperations,
"hoursRemaining": remaining_time_str,
}
# Get user subscription active or pending
@app.post("/api/get-user-subscription/")
async def get_user_subscription(request: UsernameRequest, db: db_dependency):
username = request.username
user = db.query(models.User).filter(models.User.username == username).first()
if not user:
raise HTTPException(
status_code=404,
detail="User not found"
)
active_sub = db.query(models.UserSubscribesPolicy).filter(
models.UserSubscribesPolicy.username == username,
models.UserSubscribesPolicy.status == "active"
).order_by(models.UserSubscribesPolicy.requestDate.desc()).first()
pending_sub = db.query(models.UserSubscribesPolicy).filter(
models.UserSubscribesPolicy.username == username,
models.UserSubscribesPolicy.status == "pending"
).order_by(models.UserSubscribesPolicy.requestDate.desc()).first()
return {
"activePolicyName": active_sub.policyName if active_sub else None,
"pendingPolicyName": pending_sub.policyName if pending_sub else None
}
# Update a user
@app.patch("/api/update-user/")
async def update_user(user_update: UserUpdateRequest, db: Session = Depends(get_db)):
user = db.query(models.User).filter(models.User.username == user_update.username).first()
if not user:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="User not found"
)
if user_update.firstName:
user.firstName = user_update.firstName
if user_update.lastName:
user.lastName = user_update.lastName
if user_update.email:
existing_email = db.query(models.User).filter(models.User.email == user_update.email).first()
if existing_email:
if existing_email.status == "pending":
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="email already exists and is pending approval."
)
elif existing_email.status == "active":
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="email already exists."
)
elif existing_email.status == "blocked":
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="email already exists and is blocked."
)
user.email = user_update.email
if user_update.birthDate:
try:
user.birthDate = datetime.strptime(user_update.birthDate, "%Y-%m-%d").date()
except ValueError:
raise HTTPException(
status_code=400,
detail="Invalid birthDate format. Use YYYY-MM-DD."
)
if user_update.password:
user.password = hash_password(user_update.password)
db.commit()
db.refresh(user)
return {
"username": user.username,
"email": user.email,
"firstName": user.firstName,
"lastName": user.lastName,
"birthDate": user.birthDate.isoformat() if user.birthDate else None,
"status": user.status
}
# Contribute on AI store
@app.post("/api/contribute/")
async def contribute_on_ai_store(request: ContributeRequest, db: db_dependency):
username = request.username
user = db.query(models.User).filter(models.User.username == username).first()
if not user:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="User not found"
)
with tempfile.NamedTemporaryFile(delete=False, suffix=".json", mode='w', encoding='utf-8') as temp_file:
temp_file.write(request.graphJson)
temp_file_path = temp_file.name
subject = "New contribution received"
body = (
f"The gold/platinum user {user.username} ({user.email}) "
f"proposes the schema '{request.diagramName}' to be included into the AI store. "
f"See attached file for the SchemaLink JSON internal representation."
f"\n\nSchemaLink Notification System"
)
send_email(to_email=admin_email, subject=subject, message=body, attachment=temp_file_path)
subject = "Thanks for contributing to the AI store"
body = (
f"Hi {user.username},\n\n"
f"Thank you for contributing to the AI store! "
f"Your schema '{request.diagramName}' has been received and is under review.\n"
f"\nBest regards,\n"
f"The SchemaLink Team"
)
to_email = user.email
send_email(to_email=to_email, subject=subject, message=body)
os.remove(temp_file_path)
return JSONResponse(content={"message": "Contribution received successfully"}, status_code=200)
# All subscription
@app.post("/api/dashboard-subscriptions/")
async def dashboard_subscriptions(db: db_dependency):
try:
result = db.execute (
text ("""
SELECT policyName, COUNT(*) as count
FROM UserSubscribesPolicy
WHERE status = 'active'
GROUP BY policyName
""")
)
data = result.fetchall()
response = {policy: count for policy, count in data}
return response
except Exception as e:
print(f"Error: {e}")
return JSONResponse(status_code=500, content={"message": "Internal server error"})
# Most active users
@app.get("/api/most-active-users/")
async def most_active_users(db: db_dependency):
try:
query = text("""
SELECT username, COUNT(*) AS operations_count
FROM UserMadeOperation
GROUP BY username
ORDER BY operations_count DESC
LIMIT 10
""")
result = db.execute(query)
data = result.fetchall()
response = [{"username": row.username, "operations_count": row.operations_count} for row in data]
return response
except Exception as e:
print(f"Error: {e}")
return JSONResponse(status_code=500, content={"message": "Internal server error"})
# Operations by policy category
@app.get("/api/operations-by-policy-category")
async def operations_by_policy_category(db=Depends(get_db)):
try:
query = text("""
SELECT
usp.policyName AS policy,
c.name AS category,
COUNT(*) AS count
FROM UserSubscribesPolicy usp
JOIN UserMadeOperation umo ON umo.username = usp.username
JOIN OperationIsCategory oic ON oic.operationName = umo.operationName
JOIN Category c ON c.name = oic.categoryName
GROUP BY usp.policyName, c.name
ORDER BY usp.policyName, c.name
""")
result = db.execute(query)
rows = result.fetchall()
data = {}
for row in rows:
policy = row.policy
category = row.category
count = row.count
if policy not in data:
data[policy] = {}
data[policy][category] = count
return data
except Exception as e:
print(f"Error: {e}")
return JSONResponse(status_code=500, content={"message": "Internal server error"})
# User growth by policy
@app.get("/api/user-growth-by-policy")
async def user_growth_by_policy(db=Depends(get_db)):
try:
query = text("""
SELECT
DATE_TRUNC('month', startDate) AS month,
policyName,
COUNT(DISTINCT username) AS active_users
FROM UserSubscribesPolicy
WHERE status = 'active'
GROUP BY month, policyName
ORDER BY month, policyName
""")
result = db.execute(query)
rows = result.fetchall()
data = {}
for row in rows:
month_str = row.month.strftime('%Y-%m')
policy = row.policyname
active_users = row.active_users
if month_str not in data:
data[month_str] = {"month": month_str, "trial": 0, "silver": 0, "gold": 0, "platinum": 0}
data[month_str][policy] = active_users
sorted_data = [data[month] for month in sorted(data.keys())]
return sorted_data
except Exception as e:
print(f"Error: {e}")
return JSONResponse(status_code=500, content={"message": "Internal server error"})
# Average latency by policy
@app.get("/api/average-latency-by-policy")
async def average_latency_by_policy(db=Depends(get_db)):
try: