-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathappAddModel.py
More file actions
2012 lines (1894 loc) · 103 KB
/
Copy pathappAddModel.py
File metadata and controls
2012 lines (1894 loc) · 103 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
from logging.handlers import RotatingFileHandler
import urllib.parse
from flask import Flask, abort, jsonify, request, redirect, send_from_directory, stream_with_context, url_for, render_template, flash, session,Response
from forms import LoginForm # Import the form class
from authlib.integrations.flask_client import OAuth
from flask_wtf import CSRFProtect
import bleach
import time
from mdos.mdos_sanitizer import PromptAnalyzer,prompt
from markupsafe import escape
from dateutil.relativedelta import relativedelta
import datetime
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import VARCHAR, DateTime, Column, ForeignKey, BigInteger, NVARCHAR, Integer, Table, desc, UniqueConstraint,create_engine, MetaData, Column, String
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import relationship, sessionmaker, backref
from sqlalchemy.ext.declarative import declarative_base
from self_protection import protect, sanitize_input, getHash, encStandard, decStandard
import openai
import logging
import anthropic
import uuid
from sensitive_information.sensitive_data_sanitizer import SensitiveDataSanitizer
from aishieldsemail import send_secure_email
import secrets
from prompt_injection_sanitizer.prompt_injection_sanitizer import Prompt_Injection_Sanitizer,pre_proecess_prompt,prompt_injection_score
from insecure_output_handling.insecure_output_handling import InsecureOutputSanitizer
#from overreliance.overreliance_data_sanitizer import OverrelianceDataSanitizer as ODS
import json
import netifaces as nif
import os
import security_config as sc
import pathlib
import textwrap
import google.generativeai as googlegenai
import stripe
import urllib
from markupsafe import Markup
app = Flask(__name__)
#stripe_endpoint = str("success")
app.config['SECRET_KEY'] = str(decStandard(sc.SECRET_KEY))
app.config['SQLALCHEMY_DATABASE_URI'] = sc.SQLALCHEMY_DATABASE_URI
app.config['GOOGLE_CLIENT_ID'] = sc.GOOGLE_CLIENT_ID
app.config['GOOGLE_CLIENT_SECRET'] = sc.GOOGLE_CLIENT_SECRET
email_from = sc.EMAIL_FROM
smtpserver = sc.SMTP_SERVER
smtpport = sc.SMTP_PORT
smtpp = sc.SMTP_PASSWORD
smtpu = sc.SMTP_USER
smtp_server = str(decStandard(smtpserver))
smtp_port = str(decStandard(smtpport))
smtp_p = str(decStandard(smtpp))
smtp_u = str(decStandard(smtpu))
db = SQLAlchemy(app)
csrf = CSRFProtect(app)
oauth = OAuth(app)
handler = RotatingFileHandler(sc.LOG_PATH, maxBytes=10000000, backupCount=5)
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
app.logger.addHandler(handler)
app.logger.setLevel(logging.DEBUG)
stripe.api_key = str(decStandard(sc.STRIPE_K))
# Connection URL
DATABASE_URI = sc.SQLALCHEMY_DATABASE_URI
# Using declarative_base
Base = declarative_base()
apis = [{"APIowner":"OpenAI","TextGen": {"Name":"ChatGPT","Models":[
{"Name":"GPT 4o","details":{ "uri": "https://api.openai.com/v1/chat/completions","jsonv":"gpt-4o"}},
{"Name":"GPT 4","details":{ "uri": "https://api.openai.com/v1/chat/completions","jsonv":"gpt-4"}},
{"Name":"GPT 4 Turbo Preview","details":{ "uri": "https://api.openai.com/v1/chat/completions","jsonv":"gpt-4-turbo-preview" }},
{"Name":"GPT 3.5 Turbo","details":{"uri":"https://api.openai.com/v1/chat/completions","jsonv": "gpt-3.5-turbo"}}
]}},
{"APIowner":"Anthropic","TextGen": {"Name":"Claude","Models":[
{"Name":"Sonnet June 20, 2024","details":{"uri": "https://api.anthropic.com/v1/messages","jsonv":"claude-3-5-sonnet-20240620"}},
{"Name":"Opus February 29, 2024","details":{"uri": "https://api.anthropic.com/v1/messages","jsonv":"claude-3-opus-20240229"}},
]}},
{"APIowner":"Google","TextGen": {"Name":"Gemini","Models":[
{"Name":"Gemini 1.5 Pro","details":{"uri": "https://generativelanguage.googleapis.com/v1/{model=models/gemini-1.5-pro}:generateContent","jsonv":"gemini-1.5-pro"}},
{"Name":"Gemini 1.5 Flash","details":{"uri": "https://generativelanguage.googleapis.com/v1/{model=models/gemini-1.5-flash}:generateContent","jsonv":"gemini-1.5-flash"}},
{"Name":"Gemini 1.0 Pro","details":{"uri": "https://generativelanguage.googleapis.com/v1/{model=models/gemini-1.0-pro}:generateContent","jsonv":"gemini-1.0-pro"}}
]}},
{"APIowner":"Perplexity","TextGen": {"Name":"Perplexity.ai","Models":[
{"Name":"Perplexity llama-3-sonar-large-32k-chat","details":{"uri": "https://generativelanguage.googleapis.com/v1/{model=models/gemini-1.5-pro}:generateContent","jsonv":"llama-3-sonar-large-32k-chat"}},
{"Name":"Perplexity llama-3-sonar-small-32k-chat","details":{"uri": "https://generativelanguage.googleapis.com/v1/{model=models/gemini-1.5-flash}:generateContent","jsonv":"llama-3-sonar-small-32k-chat"}},
{"Name":"Perplexity llama-3-70b-instruct","details":{"uri": "https://generativelanguage.googleapis.com/v1/{model=models/gemini-1.0-pro}:generateContent","jsonv":"llama-3-70b-instruct"}},
{"Name":"Perplexity mixtral-8x7b-instruct","details":{"uri": "https://generativelanguage.googleapis.com/v1/{model=models/gemini-1.0-pro}:generateContent","jsonv":"mixtral-8x7b-instruct"}}
]}}]
google = oauth.register(
name='google',
client_id=app.config['GOOGLE_CLIENT_ID'],
client_secret=app.config['GOOGLE_CLIENT_SECRET'],
access_token_url='https://accounts.google.com/o/oauth2/token',
access_token_params=None,
authorize_url='https://accounts.google.com/o/oauth2/auth',
authorize_params=None,
api_base_url='https://www.googleapis.com/oauth2/v1/',
userinfo_endpoint='https://openidconnect.googleapis.com/v1/userinfo', # This API returns user details.
client_kwargs={'scope': 'openid email profile'},
)
def app_context():
app = Flask(__name__)
#setup engine and session
strAppKey = decStandard(sc.STR_APP_KEY)
app.secret_key = strAppKey.encode(str="utf-8")
csrf = CSRFProtect(app)
with app.app_context():
yield
#Base = declarative_base()
user_prompt_api_model = Table(
"user_prompt_api_model",
db.metadata,
db.Column("user_id", BigInteger,ForeignKey("users.id")),
db.Column("prompt_id", BigInteger, ForeignKey("inputPrompt.id")),
db.Column("preproc_prompt_id",BigInteger,ForeignKey("preprocInputPrompt.id")),
db.Column("apiresponse_id",BigInteger,ForeignKey("apiResponse.id")),
db.Column("aishields_report_id",BigInteger,ForeignKey("aiShieldsReport.id")),
db.Column("postproc_response_id",BigInteger,ForeignKey("postprocResponse.id")),
db.Column("GenApi_id",BigInteger,ForeignKey("GenApi.id"))
)
user_codes_users = Table(
"user_codes_users",
db.metadata,
db.Column("user_id", BigInteger,ForeignKey("users.id")),
db.Column("user_codes_id", BigInteger,ForeignKey("user_codes.id")),
)
user_api = Table(
"user_api",
db.metadata,
db.Column("user_id", BigInteger,ForeignKey("users.id")),
db.Column("genapi_id", BigInteger, ForeignKey("GenApi.id")),
)
user_api_cred = Table(
"user_api_cred",
db.metadata,
db.Column("user_id", BigInteger,ForeignKey("users.id")),
db.Column("api_id",BigInteger,ForeignKey("GenApi.id")),
db.Column("cred_id",BigInteger,ForeignKey("cred.id")),
db.Column("created_date",DateTime)
)
requests_client = Table(
"requests_client",
db.metadata,
db.Column("request_id", BigInteger,ForeignKey("requests.id")),
db.Column("client_id", BigInteger, ForeignKey("clients.id")),
)
class User_Optin(db.Model):
__tablename__ = "user_optin"
id = db.Column(BigInteger, primary_key=True)
user_id=db.Column(BigInteger,ForeignKey("users.id"))
user_optin=db.Column(Integer,default=0)
created_date = db.Column(DateTime,default=datetime.datetime.now(datetime.timezone.utc))
updated_date = db.Column(DateTime,default=datetime.datetime.now(datetime.timezone.utc))
class User_Subscriptions(db.Model):
__tablename__ = "user_subscriptions"
id = db.Column(BigInteger, primary_key=True)
user_id=db.Column(BigInteger,ForeignKey("users.id"))
subscription = db.Column(VARCHAR)
active = db.Column(Integer,default=1)
class Clients(db.Model):
__tablename__ = "clients"
id = db.Column(BigInteger, primary_key=True)
IPaddress = db.Column(NVARCHAR)
MacAddress = db.Column(NVARCHAR)
create_date = db.Column(DateTime,unique=False, default=datetime.datetime.now(datetime.timezone.utc))
requests = relationship("RequestLog", secondary=requests_client)
class RequestLog(db.Model):
__tablename__ = "requests"
id = db.Column(Integer, primary_key=True)
client_id = db.Column(Integer, nullable=False) # Assuming client ID is a string
client_ip = db.Column(NVARCHAR, nullable=False) # Assuming client ID is a string
url = db.Column(NVARCHAR)
request_type = db.Column(NVARCHAR)
Headers = db.Column(NVARCHAR) # Using Text instead of NVARCHAR for compatibility
Body = db.Column(NVARCHAR)
create_date = db.Column(DateTime, nullable=False, default=datetime.datetime.now)
# def __init__(self, client_id,client_ip request_type, headers, body, url):
# self.client_ip = client_ip
# self.client_id = client_id
# self.request_type = request_type
# self.Headers = headers
# self.Body = body
# self.url = url
@staticmethod
def get_request_count(client_ip):
# Calculate the datetime 10 minutes ago
ten_minutes_ago = datetime.datetime.now() - datetime.timedelta(minutes=10)
# Filter requests based on client_id and creation date
return RequestLog.query.filter_by(client_ip=client_ip).filter(RequestLog.create_date >= ten_minutes_ago).count()
class User(db.Model):
__tablename__ = "users"
id = db.Column(BigInteger, primary_key=True)
session_id = db.Column(NVARCHAR)
subscribed = db.Column(Integer, default=0)
provider = db.Column(NVARCHAR, default='AiShields')
username = db.Column(NVARCHAR)
first_name = db.Column(NVARCHAR)
last_name = db.Column(NVARCHAR)
passphrase = db.Column(NVARCHAR)
email = db.Column(NVARCHAR)
user_verified = db.Column(Integer,default=0)
created_date = db.Column(DateTime,default=datetime.datetime.now(datetime.timezone.utc))
updated_date = db.Column(DateTime,default=datetime.datetime.now(datetime.timezone.utc))
session_start = db.Column(DateTime,default=datetime.datetime.now(datetime.timezone.utc))
session_end = db.Column(DateTime,default=datetime.datetime.now(datetime.timezone.utc).__add__(datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=20, hours=0, weeks=0)))
inputPrompts = relationship("InputPrompt",secondary=user_prompt_api_model)
preprocPrompts = relationship("PreProcInputPrompt", secondary=user_prompt_api_model)
apiResponses = relationship("ApiResponse",secondary=user_prompt_api_model)
postProcResponses = relationship("PostProcResponse",secondary=user_prompt_api_model)
aiShieldsReports = relationship("AiShieldsReport",secondary=user_prompt_api_model)
genApis = relationship(
"GenApi", secondary=user_api, back_populates="users"
)
user_codes = relationship(
"UserCode", secondary=user_codes_users, back_populates="users",
)
class UserCode(db.Model):
__tablename__ = "user_codes"
id = db.Column(BigInteger, primary_key=True)
user_id = db.Column(BigInteger,ForeignKey("users.id"))
email = db.Column(NVARCHAR)
code = db.Column(NVARCHAR)
created_date = db.Column(DateTime,unique=False, default=datetime.datetime.now(datetime.timezone.utc))
users = relationship("User", back_populates="user_codes")
class Credential(db.Model):
__tablename__ = "cred"
id = db.Column(BigInteger, primary_key=True)
user_id = db.Column(BigInteger,ForeignKey("users.id"))
api_id = db.Column(BigInteger,ForeignKey("GenApi.id"))
username = db.Column(NVARCHAR)
email = db.Column(NVARCHAR)
token = db.Column(NVARCHAR, unique=False, nullable=True)
jwt = db.Column(NVARCHAR, unique=False, nullable=True)
header = db.Column(NVARCHAR, unique=False, nullable=True)
formfield = db.Column(NVARCHAR, unique=False, nullable=True)
created_date = db.Column(DateTime,unique=False, default=datetime.datetime.now(datetime.timezone.utc))
updated_date = db.Column(DateTime, unique=False, nullable=True)
class GenApi(db.Model):
__tablename__ = "GenApi"
id = db.Column(BigInteger, primary_key=True)
api_owner = db.Column(NVARCHAR, unique=False, nullable=False)
api_name = db.Column(NVARCHAR, unique=False, nullable=False)
uri = db.Column(NVARCHAR, unique=False, nullable=False)
headers = db.Column(NVARCHAR, unique=False, nullable=True)
formfields = db.Column(NVARCHAR, unique=False, nullable=True)
model = db.Column(NVARCHAR, unique=True, nullable=False)
created_date = db.Column(DateTime,default=datetime.datetime.now(datetime.timezone.utc))
updated_date = db.Column(DateTime,default=datetime.datetime.now(datetime.timezone.utc))
inputPrompts = relationship("InputPrompt", secondary=user_prompt_api_model)
preprocPrompts = relationship("PreProcInputPrompt", secondary=user_prompt_api_model)
apiResponses = relationship("ApiResponse",secondary=user_prompt_api_model)
postProcResponses = relationship("PostProcResponse",secondary=user_prompt_api_model)
aiShieldsReports = relationship("AiShieldsReport",secondary=user_prompt_api_model)
users = relationship(
"User", secondary=user_api, back_populates="genApis"
)
# class User(db.Model):
# id = db.db.Column(BigInteger, primary_key=True)
# username = db.db.Column(NVARCHAR, unique=True, nullable=False)
# email = db.db.Column(NVARCHAR, unique=True, nullable=False)
class InputPrompt(db.Model):
__tablename__ = "inputPrompt"
id = db.Column(BigInteger, primary_key=True)
user_id = db.Column(BigInteger,ForeignKey("users.id"))
cred_id = db.Column(BigInteger, ForeignKey("cred.id"))
username = db.Column(NVARCHAR)
email = db.Column(NVARCHAR)
api_id = db.Column(BigInteger,ForeignKey("GenApi.id"))
api = db.Column(NVARCHAR)
internalPromptID = db.Column(NVARCHAR,unique=True)
inputPrompt = db.Column(NVARCHAR)
created_date = db.Column(DateTime,default=datetime.datetime.now(datetime.timezone.utc))
updated_date = db.Column(DateTime,default=datetime.datetime.now(datetime.timezone.utc))
class PreProcInputPrompt(db.Model):
__tablename__ = "preprocInputPrompt"
id = db.Column(BigInteger, primary_key=True)
user_id = db.Column(BigInteger,ForeignKey("users.id"))
username = db.Column(NVARCHAR)
email = db.Column(NVARCHAR)
api_id = db.Column(BigInteger,ForeignKey("GenApi.id"))
api = db.Column(NVARCHAR,unique=False,nullable=False)
internalPromptID = db.Column(NVARCHAR,nullable=False)
rawInputPrompt_id = db.Column(BigInteger,ForeignKey("inputPrompt.id"),nullable=False)
inputPrompt = db.Column(NVARCHAR,unique=False,nullable=False)
preProcInputPrompt = db.Column(NVARCHAR,unique=False,nullable=False)
SensitiveDataSanitizerReport = db.Column(NVARCHAR,unique=False,nullable=True)
PromptInjectionReport = db.Column(NVARCHAR,unique=False,nullable=True)
OverrelianceReport = db.Column(NVARCHAR,unique=False,nullable=True)
OverrelianceKeyphraseData = db.Column(NVARCHAR,unique=False,nullable=True)
created_date = db.Column(DateTime,default=datetime.datetime.now(datetime.timezone.utc))
updated_date = db.Column(DateTime,default=datetime.datetime.now(datetime.timezone.utc))
class ApiResponse(db.Model):
__tablename__ = "apiResponse"
id = db.Column(BigInteger, primary_key=True)
user_id = db.Column(BigInteger,ForeignKey("users.id"))
username = db.Column(NVARCHAR)
email = db.Column(NVARCHAR)
internalPromptID = db.Column(NVARCHAR,unique=False,nullable=False)
preProcPrompt_id = db.Column(BigInteger,ForeignKey("preprocInputPrompt.id"))
rawInputPrompt_id = db.Column(BigInteger,ForeignKey("inputPrompt.id"))
externalPromptID = db.Column(NVARCHAR,unique=False,nullable=False)
api_id = db.Column(BigInteger,ForeignKey("GenApi.id"))
api = db.Column(NVARCHAR)
rawoutput = db.Column(NVARCHAR)
created_date = db.Column(DateTime,default=datetime.datetime.now(datetime.timezone.utc))
class PostProcResponse(db.Model):
__tablename__ = "postprocResponse"
id = db.Column(BigInteger, primary_key=True)
rawInputPrompt_id = db.Column(BigInteger, ForeignKey("inputPrompt.id"))
inputPromptID = db.Column(NVARCHAR,unique=False,nullable=False)
preProcPrompt_id = db.Column(BigInteger, ForeignKey("preprocInputPrompt.id"))
externalPromptID = db.Column(NVARCHAR,unique=False,nullable=False)
user_id = db.Column(BigInteger,ForeignKey("users.id"))
username = db.Column(NVARCHAR)
email = db.Column(NVARCHAR)
api_id = db.Column(BigInteger,ForeignKey("GenApi.id"))
api = db.Column(NVARCHAR,unique=False,nullable=False)
rawResponseID = db.Column(BigInteger,ForeignKey("apiResponse.id"))
rawOutputResponse = db.Column(NVARCHAR,unique=False,nullable=False)
InsecureOutputHandlingReport = db.Column(NVARCHAR,unique=False,nullable=False)
postProcOutputResponse = db.Column(NVARCHAR,unique=False,nullable=False)
created_date = db.Column(DateTime,default=datetime.datetime.now(datetime.timezone.utc))
class AiShieldsReport(db.Model):
__tablename__ = "aiShieldsReport"
id = db.Column(BigInteger, primary_key=True)
rawInputPrompt_id = db.Column(BigInteger, ForeignKey("inputPrompt.id"))
preProcPrompt_id = db.Column(BigInteger, ForeignKey("preprocInputPrompt.id"))
rawResponse_id = db.Column(BigInteger, ForeignKey("apiResponse.id"))
postProcResponse_id = db.Column(BigInteger, ForeignKey("postprocResponse.id"))
internalPromptID = db.Column(NVARCHAR,unique=False,nullable=False)
externalPromptID = db.Column(NVARCHAR,unique=False,nullable=True)
user_id = db.Column(BigInteger,ForeignKey("users.id"))
username = db.Column(NVARCHAR, unique=False, nullable=False)
email = db.Column(NVARCHAR, unique=False, nullable=False)
api_id = db.Column(BigInteger,ForeignKey("GenApi.id"))
api = db.Column(NVARCHAR,unique=False,nullable=False)
SensitiveDataSanitizerReport = db.Column(NVARCHAR,unique=False,nullable=True)
PromptInjectionReport = db.Column(NVARCHAR,unique=False,nullable=True)
OverrelianceReport = db.Column(NVARCHAR,unique=False,nullable=True)
InsecureOutputReportHandling = db.Column(NVARCHAR,unique=False,nullable=True)
MDOSreport = db.Column(NVARCHAR,unique=False,nullable=True)
created_date = db.Column(DateTime,default=datetime.datetime.now(datetime.timezone.utc))
updated_date = db.Column(DateTime)
class User_Info():
api:str
email:str
token:str
username:str
inputprompt:str
internalID = str(uuid.uuid4())
lstApi:str
strApi:str
strModel:str
userid:int
sensitiveData:bool
overrelianceData:bool
def mac_for_ip(ip):
'Returns a list of MACs for interfaces that have given IP, returns None if not found'
for i in nif.interfaces():
addrs = nif.ifaddresses(i)
try:
if_mac = addrs[nif.AF_LINK][0]['addr']
if_ip = addrs[nif.AF_INET][0]['addr']
except IndexError: #ignore ifaces that dont have MAC or IP
if_mac = if_ip = None
except KeyError:
if_mac = if_ip = None
if if_ip == ip:
return if_mac
return None
@app.template_filter('urlencode')
def urlencode_filter(s):
if type(s) == 'Markup':
s = s.unescape()
s = s.encode('utf8')
s = urllib.parse.urlencode({'prefilled_email': s})
return Markup(s)
@app.before_request
def before_request():
try:
public_routes = ['login','c','pay', 'create_checkout_session','subscribe','subscribed','cancel','newaccount', 'forgot', 'verifyemail', 'static','reset', 'success','webhook']
if 'logged_in' not in session and request.endpoint not in public_routes:
if request.url.startswith("https://checkout.stripe.com"):
#stripe_endpoint = request.endpoint
#public_routes += request.endpoint
return redirect(request.url)
if request.url.lower().startswith("https://chat.aishields.org/webhook"):
return redirect(request.url)
return redirect(url_for('login'))
if request.url.startswith("https://checkout.stripe.com"):
#stripe_endpoint = request.endpoint
#public_routes += request.endpoint
return redirect(request.url)
if request.url.lower().startswith("https://chat.aishields.org/webhook"):
#stripe_endpoint = request.endpoint
#public_routes += request.endpoint
return redirect(request.url)
# Save the request data for MDOS protection
macAddress = mac_for_ip(request.headers.get('X-Forwarded-For', request.remote_addr))
if macAddress is None:
macAddress = "?"
client_info = Clients(
IPaddress=request.headers.get('X-Forwarded-For', request.remote_addr),
MacAddress=macAddress
)
db.session.add(client_info)
db.session.commit()
db.session.flush()
request_data = RequestLog(
client_id=client_info.id,
client_ip=client_info.IPaddress,
request_type=request.method,
Headers=repr(dict(request.headers)),
Body=request.data.decode('utf-8'),
url=request.url
)
db.session.add(request_data)
db.session.commit()
# MDOS (Model Denial of Service entrypoint)
# James Yu can add code here to handle MDOS protection
client_id = request.remote_addr
request_count = RequestLog.get_request_count(client_id)
if request_count >= 500: # Adjust the limit as needed
flash('Too many requests, please try again later', 'danger')
print(request_count)
abort(429) # Too Many Requests status code
except Exception as err:
logging.error('An error occurred during login: %s', err)
flash("An error occurred. Please try again.")
return render_template('login.html', form=LoginForm())
@app.route('/subscribe',methods=['GET'])
def subscribe():
try:
if request.method == 'GET':
if request.form.get('email') is not None:
return render_template('subscribe.html',email=request.form.get('email'),noemail=False)
else:
return render_template('subscribe.html',noemail=True)
except Exception as err:
logging.error('An error occured during subscribe request: ' + str(err))
flash("An error occurred." + str(err) +" Please try again.")
return render_template('subscribe.html')
app.route('/subscribed',methods=['GET'])
def success():
try:
if request.method == 'GET':
session = stripe.checkout.Session.retrieve(request.args.get('session_id'))
if session:
customer = stripe.Customer.retrieve(session.customer)
return render_template('newaccount.html', email=customer.email)
return render_template('login.html')
except Exception as err:
logging.error('An error occured during request: ' + str(err))
flash("An error occurred." + str(err) +" Please try again.")
return render_template('subscribe.html')
@app.route('/cancel',methods=['GET'])
def cancel():
try:
if request.method == 'GET':
return render_template('cancel.html',email=request.form.get('email'))
except Exception as err:
logging.error('An error occured during cancel page load request: ' + str(err))
flash("An error occurred." + str(err) +" Please try again.")
return render_template('subscribe.html')
@app.route('/create_checkout_session', methods=['POST'])
def create_checkout_session():
try:
#prices = stripe.Price.list(
# lookup_keys=[request.form['lookup_key']],
# expand=['data.product']
# )
strEmail = ""
if request.form.get('email2') is not None:
strEmail = str(request.form.get("email2")).lower()
#elif request.form.get("email") is not None:
# strEmail = str(request.form.get("email")).lower()
logging.error('\n\n\n' + strEmail + '\n\n\n')
usercode = UserCode()
usercode.user_id = 0
usercode.email = strEmail
usercode.code = str(uuid.uuid4())
db.session.add(usercode)
db.session.commit()
db.session.flush(objects=[usercode])
# user = (
# db.session.query(User)
# .filter(User.email == strEmail.lower(),User.user_verified == 1)
# .first()
# )
if strEmail is not None :
checkout_session = stripe.checkout.Session.create(
line_items=[
{
'price': 'price_1PPjO8DLTE0Q14oGUFYIbzNb',
'quantity': 1
},
],
metadata={"email":str(strEmail),'code':str(usercode.code)},
customer_email=str(strEmail),
mode="subscription",
subscription_data={
"trial_period_days": 14,
"trial_settings": {"end_behavior": {"missing_payment_method": "cancel"}},},
payment_method_collection="always",
success_url='https://chat.aishields.org/subscribed?session_id={CHECKOUT_SESSION_ID}',
cancel_url='https://chat.aishields.org/cancel.html',
)
logging.error('\n\n\n' + checkout_session.url + '\n\n\n')
return redirect(checkout_session.url, code=303)
flash("Please subscribe to our free trial")
return render_template('subscribe.html')
except Exception as e:
logging.error(e)
flash(e)
return "Server error", 500
@app.route('/create_portal_session', methods=['POST'])
def create_portal_session():
# For demonstration purposes, we're using the Checkout session to retrieve the customer ID.
# Typically this is stored alongside the authenticated user in your database.
checkout_session_id = request.form.get('session_id')
customer_email = request.form.get('email')
checkout_session = stripe.checkout.Session.retrieve(checkout_session_id)
current_user = (
db.session.query(User)
.filter(User.email == customer_email,User.user_verified == 1, User.subscribed==1)
.first()
)
current_user.session_id = checkout_session_id
current_user.session_start = datetime.datetime.now(datetime.timezone.utc)
current_user.session_end = datetime.datetime.now(datetime.timezone.utc).__add__(datetime.timedelta(datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=5, hours=0, weeks=0)))
db.commit(current_user)
db.flush(objects=[current_user])
# This is the URL to which the customer will be redirected after they are
# done managing their billing with the portal.
return_url = "https://chat.aishields.org/profile"
portalSession = stripe.billing_portal.Session.create(
customer=checkout_session.customer,
return_url=return_url,
)
return redirect(portalSession.url, code=303)
@csrf.exempt
@app.route('/webhook', methods=['POST'])
def webhook():
# Replace this endpoint secret with your endpoint's unique secret
# If you are testing with the CLI, find the secret by running 'stripe listen'
# If you are using an endpoint defined with the API or dashboard, look in your webhook settings
# at https://dashboard.stripe.com/webhooks
webhook_secret = str(decStandard(sc.STRIPE_SignK))
request_data = json.loads(request.data)
if webhook_secret:
# Retrieve the event by verifying the signature using the raw body and secret if webhook signing is configured.
signature = request.headers.get('stripe-signature')
try:
event = stripe.Webhook.construct_event(
payload=request.data, sig_header=signature, secret=webhook_secret)
data = event['data']
except Exception as e:
return e
# Get the type of webhook event sent - used to check the status of PaymentIntents.
event_type = event['type']
else:
data = request_data['data']
event_type = request_data['type']
data_object = data['object']
logging.error('event ' + event_type)
if event_type == 'checkout.session.completed':
logging.error('🔔 Payment succeeded!')
if data_object is not None:
email = data_object["customer_email"]
subscription_id = data_object['subscription']
user = (db.session.query(User)
.filter(User.email==email,User.user_verified==1)
.first())
user.subscribed = 1
db.session.add(user)
db.session.commit()
db.session.flush(objects=[user])
user_subscription = User_Subscriptions()
user_subscription.active = 1
user_subscription.subscription = subscription_id
user_subscription.user_id = user.id
db.session.add(user_subscription)
db.session.commit()
db.session.flush(objects=[user_subscription])
elif event_type == 'customer.subscription.trial_will_end':
logging.error('Subscription trial will end')
elif event_type == 'customer.subscription.created':
logging.error('Subscription created %s', event.id)
elif event_type == 'customer.subscription.updated':
logging.error('Subscription created %s', event.id)
elif event_type == 'customer.subscription.deleted':
# handle subscription canceled automatically based
# upon your subscription settings. Or if the user cancels it.
stripe_customer_id = data_object["customer"]
customer = stripe.Customer.retrieve(id=stripe_customer_id)
email = customer.email
user = (db.session.query(User)
.filter(User.email==email,User.user_verified==1)
.first())
user_subscription = (db.session.query(User_Subscriptions)
.filter(User_Subscriptions.user_id ==user.id)
.first())
if user_subscription is None:
user_subscription = User_Subscriptions()
user_subscription.active = 0
user_subscription.user_id = user.id
user_subscription.subscription = "NA"
user_subscription.active = 0
user.subscribed = 0
db.session.add(user)
db.session.add(user_subscription)
db.session.commit()
db.session.flush(object[user,user_subscription])
logging.error('Subscription canceled: %s', event.id)
elif event['type'] == 'account.updated':
account = event['data']['object']
elif event['type'] == 'account.external_account.created':
external_account = event['data']['object']
elif event['type'] == 'account.external_account.deleted':
external_account = event['data']['object']
elif event['type'] == 'account.external_account.updated':
external_account = event['data']['object']
elif event['type'] == 'balance.available':
balance = event['data']['object']
elif event['type'] == 'billing_portal.configuration.created':
configuration = event['data']['object']
elif event['type'] == 'billing_portal.configuration.updated':
configuration = event['data']['object']
elif event['type'] == 'billing_portal.session.created':
session = event['data']['object']
elif event['type'] == 'capability.updated':
capability = event['data']['object']
elif event['type'] == 'cash_balance.funds_available':
cash_balance = event['data']['object']
elif event['type'] == 'charge.captured':
charge = event['data']['object']
elif event['type'] == 'charge.expired':
charge = event['data']['object']
elif event['type'] == 'charge.failed':
charge = event['data']['object']
elif event['type'] == 'charge.pending':
charge = event['data']['object']
elif event['type'] == 'charge.refunded':
charge = event['data']['object']
elif event['type'] == 'charge.succeeded':
charge = event['data']['object']
elif event['type'] == 'charge.updated':
charge = event['data']['object']
elif event['type'] == 'charge.dispute.closed':
dispute = event['data']['object']
elif event['type'] == 'charge.dispute.created':
dispute = event['data']['object']
elif event['type'] == 'charge.dispute.funds_reinstated':
dispute = event['data']['object']
elif event['type'] == 'charge.dispute.funds_withdrawn':
dispute = event['data']['object']
elif event['type'] == 'charge.dispute.updated':
dispute = event['data']['object']
elif event['type'] == 'charge.refund.updated':
refund = event['data']['object']
elif event['type'] == 'checkout.session.async_payment_failed':
session = event['data']['object']
elif event['type'] == 'checkout.session.async_payment_succeeded':
session = event['data']['object']
elif event['type'] == 'checkout.session.completed':
session = event['data']['object']
elif event['type'] == 'checkout.session.expired':
session = event['data']['object']
elif event['type'] == 'climate.order.canceled':
order = event['data']['object']
elif event['type'] == 'climate.order.created':
order = event['data']['object']
elif event['type'] == 'climate.order.delayed':
order = event['data']['object']
elif event['type'] == 'climate.order.delivered':
order = event['data']['object']
elif event['type'] == 'climate.order.product_substituted':
order = event['data']['object']
elif event['type'] == 'climate.product.created':
product = event['data']['object']
elif event['type'] == 'climate.product.pricing_updated':
product = event['data']['object']
elif event['type'] == 'coupon.created':
coupon = event['data']['object']
elif event['type'] == 'coupon.deleted':
coupon = event['data']['object']
elif event['type'] == 'coupon.updated':
coupon = event['data']['object']
elif event['type'] == 'credit_note.created':
credit_note = event['data']['object']
elif event['type'] == 'credit_note.updated':
credit_note = event['data']['object']
elif event['type'] == 'credit_note.voided':
credit_note = event['data']['object']
elif event['type'] == 'customer.created':
customer = event['data']['object']
elif event['type'] == 'customer.deleted':
customer = event['data']['object']
elif event['type'] == 'customer.updated':
customer = event['data']['object']
elif event['type'] == 'customer.discount.created':
discount = event['data']['object']
elif event['type'] == 'customer.discount.deleted':
discount = event['data']['object']
elif event['type'] == 'customer.discount.updated':
discount = event['data']['object']
elif event['type'] == 'customer.source.created':
source = event['data']['object']
elif event['type'] == 'customer.source.deleted':
source = event['data']['object']
elif event['type'] == 'customer.source.expiring':
source = event['data']['object']
elif event['type'] == 'customer.source.updated':
source = event['data']['object']
elif event['type'] == 'customer.subscription.created':
subscription = event['data']['object']
elif event['type'] == 'customer.subscription.deleted':
subscription = event['data']['object']
elif event['type'] == 'customer.subscription.paused':
subscription = event['data']['object']
elif event['type'] == 'customer.subscription.pending_update_applied':
subscription = event['data']['object']
elif event['type'] == 'customer.subscription.pending_update_expired':
subscription = event['data']['object']
elif event['type'] == 'customer.subscription.resumed':
subscription = event['data']['object']
elif event['type'] == 'customer.subscription.trial_will_end':
subscription = event['data']['object']
elif event['type'] == 'customer.subscription.updated':
subscription = event['data']['object']
elif event['type'] == 'customer.tax_id.created':
tax_id = event['data']['object']
elif event['type'] == 'customer.tax_id.deleted':
tax_id = event['data']['object']
elif event['type'] == 'customer.tax_id.updated':
tax_id = event['data']['object']
elif event['type'] == 'customer_cash_balance_transaction.created':
customer_cash_balance_transaction = event['data']['object']
elif event['type'] == 'entitlements.active_entitlement_summary.updated':
active_entitlement_summary = event['data']['object']
elif event['type'] == 'file.created':
file = event['data']['object']
elif event['type'] == 'financial_connections.account.created':
account = event['data']['object']
elif event['type'] == 'financial_connections.account.deactivated':
account = event['data']['object']
elif event['type'] == 'financial_connections.account.disconnected':
account = event['data']['object']
elif event['type'] == 'financial_connections.account.reactivated':
account = event['data']['object']
elif event['type'] == 'financial_connections.account.refreshed_balance':
account = event['data']['object']
elif event['type'] == 'financial_connections.account.refreshed_ownership':
account = event['data']['object']
elif event['type'] == 'financial_connections.account.refreshed_transactions':
account = event['data']['object']
elif event['type'] == 'identity.verification_session.canceled':
verification_session = event['data']['object']
elif event['type'] == 'identity.verification_session.created':
verification_session = event['data']['object']
elif event['type'] == 'identity.verification_session.processing':
verification_session = event['data']['object']
elif event['type'] == 'identity.verification_session.requires_input':
verification_session = event['data']['object']
elif event['type'] == 'identity.verification_session.verified':
verification_session = event['data']['object']
elif event['type'] == 'invoice.created':
invoice = event['data']['object']
elif event['type'] == 'invoice.deleted':
invoice = event['data']['object']
elif event['type'] == 'invoice.finalization_failed':
invoice = event['data']['object']
elif event['type'] == 'invoice.finalized':
invoice = event['data']['object']
elif event['type'] == 'invoice.marked_uncollectible':
invoice = event['data']['object']
elif event['type'] == 'invoice.overdue':
invoice = event['data']['object']
elif event['type'] == 'invoice.paid':
invoice = event['data']['object']
elif event['type'] == 'invoice.payment_action_required':
invoice = event['data']['object']
elif event['type'] == 'invoice.payment_failed':
#email customer with link to payment portal: <a href="https://billing.stripe.com/p/login/8wM8yA8Mp6Rt7qo7ss">Manage Subscription</a>
#change subscription status to 2
email = data_object["customer_email"]
user = (db.session.query(User)
.filter(User.email == email,User.subscribed == 1,User.user_verified)
.first())
to_email = user.email
from_email = smtp_u
s_server = smtp_server
s_port = smtp_port
s_p = smtp_p
m_subj = "Payment failed for subscription to AiShields"
m_message = "Dear " + user.first_name + ", \n\n Please update your payment method to keep your AiShields subscription active using this link: https://billing.stripe.com/p/login/8wM8yA8Mp6Rt7qo7ss?prefilled_email=" + str(email).replace(old='@',new='%40') + " \n\n Thank you, \n\n Support@AiShields.org"
send_secure_email(to_email,from_email,s_server,s_port,from_email,s_p,m_subj,m_message)
user.subscribed = 0
user_subscription = (db.session.query(User_Subscriptions)
.filter(User_Subscriptions.user_id == user.id).first())
user_subscription.active = 2
db.session.add(user)
db.session.add(user_subscription)
db.session.commit()
db.session.flush(objects=[user,user_subscription])
invoice = event['data']['object']
elif event['type'] == 'invoice.payment_succeeded':
invoice = event['data']['object']
elif event['type'] == 'invoice.sent':
invoice = event['data']['object']
elif event['type'] == 'invoice.upcoming':
invoice = event['data']['object']
elif event['type'] == 'invoice.updated':
invoice = event['data']['object']
elif event['type'] == 'invoice.voided':
invoice = event['data']['object']
elif event['type'] == 'invoice.will_be_due':
invoice = event['data']['object']
elif event['type'] == 'invoiceitem.created':
invoiceitem = event['data']['object']
elif event['type'] == 'invoiceitem.deleted':
invoiceitem = event['data']['object']
elif event['type'] == 'issuing_authorization.created':
issuing_authorization = event['data']['object']
elif event['type'] == 'issuing_authorization.updated':
issuing_authorization = event['data']['object']
elif event['type'] == 'issuing_card.created':
issuing_card = event['data']['object']
elif event['type'] == 'issuing_card.updated':
issuing_card = event['data']['object']
elif event['type'] == 'issuing_cardholder.created':
issuing_cardholder = event['data']['object']
elif event['type'] == 'issuing_cardholder.updated':
issuing_cardholder = event['data']['object']
elif event['type'] == 'issuing_dispute.closed':
issuing_dispute = event['data']['object']
elif event['type'] == 'issuing_dispute.created':
issuing_dispute = event['data']['object']
elif event['type'] == 'issuing_dispute.funds_reinstated':
issuing_dispute = event['data']['object']
elif event['type'] == 'issuing_dispute.submitted':
issuing_dispute = event['data']['object']
elif event['type'] == 'issuing_dispute.updated':
issuing_dispute = event['data']['object']
elif event['type'] == 'issuing_personalization_design.activated':
issuing_personalization_design = event['data']['object']
elif event['type'] == 'issuing_personalization_design.deactivated':
issuing_personalization_design = event['data']['object']
elif event['type'] == 'issuing_personalization_design.rejected':
issuing_personalization_design = event['data']['object']
elif event['type'] == 'issuing_personalization_design.updated':
issuing_personalization_design = event['data']['object']
elif event['type'] == 'issuing_token.created':
issuing_token = event['data']['object']
elif event['type'] == 'issuing_token.updated':
issuing_token = event['data']['object']
elif event['type'] == 'issuing_transaction.created':
issuing_transaction = event['data']['object']
elif event['type'] == 'issuing_transaction.updated':
issuing_transaction = event['data']['object']
elif event['type'] == 'mandate.updated':
mandate = event['data']['object']
elif event['type'] == 'payment_intent.amount_capturable_updated':
payment_intent = event['data']['object']
elif event['type'] == 'payment_intent.canceled':
payment_intent = event['data']['object']
elif event['type'] == 'payment_intent.created':
payment_intent = event['data']['object']
elif event['type'] == 'payment_intent.partially_funded':
payment_intent = event['data']['object']
elif event['type'] == 'payment_intent.payment_failed':
payment_intent = event['data']['object']
elif event['type'] == 'payment_intent.processing':
payment_intent = event['data']['object']
elif event['type'] == 'payment_intent.requires_action':
payment_intent = event['data']['object']
elif event['type'] == 'payment_intent.succeeded':
payment_intent = event['data']['object']
elif event['type'] == 'payment_link.created':
payment_link = event['data']['object']
elif event['type'] == 'payment_link.updated':
payment_link = event['data']['object']
elif event['type'] == 'payment_method.attached':
payment_method = event['data']['object']
elif event['type'] == 'payment_method.automatically_updated':
payment_method = event['data']['object']
elif event['type'] == 'payment_method.detached':
payment_method = event['data']['object']
elif event['type'] == 'payment_method.updated':
payment_method = event['data']['object']
elif event['type'] == 'payout.canceled':
payout = event['data']['object']
elif event['type'] == 'payout.created':
payout = event['data']['object']
elif event['type'] == 'payout.failed':
payout = event['data']['object']
elif event['type'] == 'payout.paid':
payout = event['data']['object']
elif event['type'] == 'payout.reconciliation_completed':
payout = event['data']['object']
elif event['type'] == 'payout.updated':
payout = event['data']['object']
elif event['type'] == 'person.created':
person = event['data']['object']
elif event['type'] == 'person.deleted':
person = event['data']['object']
elif event['type'] == 'person.updated':
person = event['data']['object']
elif event['type'] == 'plan.created':
plan = event['data']['object']
elif event['type'] == 'plan.deleted':
plan = event['data']['object']
elif event['type'] == 'plan.updated':
plan = event['data']['object']
elif event['type'] == 'price.created':
price = event['data']['object']
elif event['type'] == 'price.deleted':
price = event['data']['object']
elif event['type'] == 'price.updated':
price = event['data']['object']
elif event['type'] == 'product.created':
product = event['data']['object']
elif event['type'] == 'product.deleted':
product = event['data']['object']
elif event['type'] == 'product.updated':
product = event['data']['object']
elif event['type'] == 'promotion_code.created':
promotion_code = event['data']['object']
elif event['type'] == 'promotion_code.updated':
promotion_code = event['data']['object']
elif event['type'] == 'quote.accepted':
quote = event['data']['object']
elif event['type'] == 'quote.canceled':
quote = event['data']['object']
elif event['type'] == 'quote.created':
quote = event['data']['object']
elif event['type'] == 'quote.finalized':
quote = event['data']['object']
elif event['type'] == 'quote.will_expire':
quote = event['data']['object']
elif event['type'] == 'radar.early_fraud_warning.created':
early_fraud_warning = event['data']['object']
elif event['type'] == 'radar.early_fraud_warning.updated':
early_fraud_warning = event['data']['object']
elif event['type'] == 'refund.created':
refund = event['data']['object']
elif event['type'] == 'refund.updated':
refund = event['data']['object']
elif event['type'] == 'reporting.report_run.failed':
report_run = event['data']['object']