-
Notifications
You must be signed in to change notification settings - Fork 68
/
app.py
2287 lines (2018 loc) · 86.7 KB
/
app.py
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 multiprocessing.pool import ThreadPool
import os
import threading
from flask.globals import current_app
from oauthlib.oauth2 import WebApplicationClient
from flask import Flask, render_template, redirect, request, flash, url_for, jsonify, abort, send_from_directory, make_response
from flask_login import LoginManager, current_user, login_user, logout_user, login_required
from flask_sqlalchemy import SQLAlchemy
from passlib.hash import sha256_crypt
from password_generator import PasswordGenerator
from flask_mail import Mail, Message
from datetime import datetime
import json as json_lib
import requests
import random
import string
import pytz
import re
import razorpay
import hmac
import hashlib
from itsdangerous import SignatureExpired, URLSafeTimedSerializer
import qrcode
from flask_login import UserMixin
from functools import wraps
from decouple import config
import csv
import cloudinary
import cloudinary.uploader
import cloudinary.api
from flask_migrate import Migrate
import io
from flask_cors import CORS
# AWS S3 Bucket
import boto3
# Facebook Login
# import requests_oauthlib
# from requests_oauthlib.compliance_fixes import facebook_compliance_fix
# Pdf Conversion
# import pdfkit
regex = '^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$'
# SES Conf
CHARSET = "UTF-8"
def check(email):
return re.search(regex, email)
# end
app = Flask(__name__)
CORS(app, resources={r"v1/api/*": {"origins": "*"}})
app.config['CORS_HEADERS'] = 'Content-Type'
app.config.from_object(config("app_settings"))
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = config('email_username')
app.config['MAIL_PASSWORD'] = config('email_password')
app.config['MAIL_DEBUG'] = False
app.config.from_object(config("app_settings"))
db = SQLAlchemy(app)
mail = Mail(app)
if db.engine.url.drivername == 'sqlite':
migrate = Migrate(app, db, render_as_batch=True)
else:
migrate = Migrate(app, db)
os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"
# serializer for registration
s = URLSafeTimedSerializer(app.secret_key)
login_manager = LoginManager(app)
login_manager.login_view = 'loginPage'
login_manager.login_message_category = 'info'
RAZORPAY_KEY_ID = config("razorpay_key_id")
RAZORPAY_KEY_SECRET = config("razorpay_key_secret")
# S3 Client
# s3_client = boto3.client('s3', aws_access_key_id=config(
# "S3_KEY"), aws_secret_access_key=config("S3_SECRET_ACCESS_KEY"))
cloudinary.config(
cloud_name=config("CLOUDINARY_CLOUD_NAME"),
api_key=config("CLOUDINARY_API_KEY"),
api_secret=config("CLOUDINARY_API_SECRET")
)
def upload(file, **options):
res = cloudinary.uploader.upload(file)
return res['secure_url']
# Facebook Login Credentials
# FB_AUTHORIZATION_BASE_URL = "https://www.facebook.com/dialog/oauth"
# FB_TOKEN_URL = config('facebook_token_url')
# FB_CLIENT_ID = config("facebook_app_id")
# FB_CLIENT_SECRET = config("facebook_secret")
# Google Login Credentials
GOOGLE_CLIENT_ID = config("google_client_id")
GOOGLE_CLIENT_SECRET = config("google_client_secret")
GOOGLE_DISCOVERY_URL = (
"https://accounts.google.com/.well-known/openid-configuration"
)
IST = pytz.timezone('Asia/Kolkata')
x = datetime.now(IST)
time = x.strftime("%c")
host = config('host_status', default=False, cast=bool)
ipc = config("demo_ip")
favTitle = config("favTitle")
site_url = config("site_url")
@login_manager.user_loader
def load_user(user_id):
return Users.query.get(user_id)
class Users(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), nullable=False)
email = db.Column(db.String(50), nullable=False)
password = db.Column(db.String(500), nullable=False)
profile_image = db.Column(db.String(500), nullable=True)
status = db.Column(db.Integer, nullable=False)
is_staff = db.Column(db.Boolean, default=False, nullable=False)
last_login = db.Column(db.String(50), nullable=False)
group = db.relationship('Group', cascade="all,delete", backref='group')
class Token(db.Model):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(100), nullable=False)
token_id = db.Column(db.String(200), nullable=False)
# U->Used, E->Expired, A->Available
status = db.Column(db.String(50), nullable=False, default='A')
class Fonts(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
font_cdn = db.Column(db.String(500), nullable=True)
class Group(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), nullable=False)
date = db.Column(db.String(50), nullable=False)
textColor = db.Column(db.String(50), nullable=True)
bg_image = db.Column(db.String(500), nullable=True)
font_size = db.Column(db.Integer, nullable=False)
font_name = db.Column(db.String(250), nullable=False)
certx = db.Column(db.Integer, nullable=False)
certy = db.Column(db.Integer, nullable=False)
qrx = db.Column(db.Integer, nullable=False)
qry = db.Column(db.Integer, nullable=False)
certnox = db.Column(db.Integer, nullable=False)
certnoy = db.Column(db.Integer, nullable=False)
prefix = db.Column(db.String(20), default='CGV')
user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
certificates = db.relationship(
'Certificate', cascade="all,delete", backref='certificates')
class Certificate(db.Model):
id = db.Column(db.Integer, primary_key=True)
number = db.Column(db.String(50), nullable=False)
name = db.Column(db.String(50), nullable=False)
email = db.Column(db.String(50), nullable=False)
is_email_sent = db.Column(db.Boolean, default=False)
coursename = db.Column(db.String(500), nullable=False)
last_update = db.Column(db.String(50), nullable=False, default=x)
group_id = db.Column(db.Integer, db.ForeignKey('group.id'))
user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
qrcode = db.relationship('QRCode', cascade="all,delete", backref='qrcode')
class QRCode(db.Model):
id = db.Column(db.Integer, primary_key=True)
certificate_num = db.Column(db.String(50), nullable=False)
link = db.Column(db.String(200), nullable=False)
qr_code = db.Column(db.String(100), nullable=True)
certificate_id = db.Column(db.Integer, db.ForeignKey('certificate.id'))
class Newsletter(db.Model):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(50), nullable=False)
ip = db.Column(db.String(200), nullable=False)
date = db.Column(db.String(50), nullable=False)
class Contact(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), nullable=False)
email = db.Column(db.String(50), nullable=False)
phone = db.Column(db.String(50), nullable=False)
message = db.Column(db.String(500), nullable=False)
ip = db.Column(db.String(200), nullable=False)
date = db.Column(db.String(50), nullable=False)
class Feedback(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), nullable=False)
email = db.Column(db.String(50), nullable=False)
phone = db.Column(db.String(50), nullable=False)
rating = db.Column(db.String(10), nullable=False)
message = db.Column(db.String(500), nullable=False)
ip = db.Column(db.String(200), nullable=False)
date = db.Column(db.String(50), nullable=False)
class Transactions(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(127), nullable=False)
email = db.Column(db.String(127), nullable=False)
phone = db.Column(db.String(15), nullable=False)
order_id = db.Column(db.String(50), nullable=False)
amount = db.Column(db.String(50), nullable=False)
currency = db.Column(db.String(50), nullable=False)
payment_id = db.Column(db.String(127), nullable=False)
response_msg = db.Column(db.Text(), nullable=False)
status = db.Column(db.String(25), nullable=False)
error_code = db.Column(db.String(127), nullable=True)
error_source = db.Column(db.String(127), nullable=True)
txn_timestamp = db.Column(
db.DateTime(), default=datetime.now(IST), nullable=False)
class APIKey(db.Model):
id = db.Column(db.Integer, primary_key=True)
key = db.Column(db.String(50), nullable=False)
user_id = db.Column(db.Integer, nullable=False)
group_name = db.Column(db.String(50), nullable=True)
group_id = db.Column(db.Integer, db.ForeignKey('group.id'))
usage_limit = db.Column(db.Integer, nullable=True)
is_valid = db.Column(db.Boolean, nullable=False, default=False)
is_approved = db.Column(db.Boolean, nullable=False, default=False)
date_generated = db.Column(db.String(50), nullable=False)
class PublicAPIKey(db.Model):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(100), nullable=False)
key = db.Column(db.String(50), nullable=False)
is_valid = db.Column(db.Boolean, nullable=False, default=False)
is_approved = db.Column(db.Boolean, nullable=False, default=False)
date_generated = db.Column(db.String(50), nullable=False)
# Admin Required Decorator
def admin_required(func):
@wraps(func)
def decorated_view(*args, **kwargs):
if not current_user.is_staff:
flash('You are not authorized to access this page.', 'danger')
return render_template('block.html', favTitle=favTitle, user=current_user)
return func(*args, **kwargs)
return decorated_view
# Use if Sendgrid is configured
# def send_async_email(app, msg):
# with app.app_context():
# mail.send(msg)
# return True
# def send_email_now(email, subject, from_email, from_email_name, template_name, **kwargs):
# app = current_app._get_current_object()
# msg = Message(
# sender=(from_email_name, from_email),
# recipients=[email],
# subject=subject
# )
# msg.html = render_template(template_name, **kwargs)
# try:
# thr = threading.Thread(target=send_async_email, args=[app, msg]).start()
# return thr
# except Exception as e:
# print(e)
# return False
def send_async_email(app, client, data):
with app.app_context():
response = client.send_email(
Destination={
'ToAddresses': [
data["email"],
],
},
Message={
'Body': {
'Html': {
'Charset': CHARSET,
'Data': data["msg_html"],
},
},
'Subject': {
'Charset': CHARSET,
'Data': data["subject"],
},
},
Source=data["sender"],
)
return response["ResponseMetadata"]["HTTPStatusCode"]
def send_email_now(email, subject, from_email, from_email_name, template_name, **kwargs):
aws_email = config("AWS_SES_VERIFIED_EMAIL")
sender = f"{from_email_name} <{aws_email}>"
client = boto3.client('ses',
region_name=config("AWS_REGION"),
aws_access_key_id=config("AWS_ACCESS_KEY_ID"),
aws_secret_access_key=config("AWS_ACCESS_KEY_SECRET")
)
msg_html = render_template(template_name, **kwargs)
data = {
"email": email,
"subject": subject,
"sender": sender,
"msg_html": msg_html
}
try:
pool = ThreadPool(processes=1)
# Provide the contents of the email.
async_res = pool.apply_async(send_async_email, [app, client, data])
return async_res.get() == 200
# Display an error if something goes wrong.
except Exception as e:
print(e)
return False
# def upload_image(file, bucket="cgv", **kwargs):
# """
# Function to upload an image to an S3 bucket
# """
# if kwargs["folder"] == "qr_codes":
# response = s3_client.put_object(
# Bucket=bucket,
# Key=f'{kwargs["folder"]}/{kwargs["number"]}.png',
# Body=file,
# ContentType='image/png',
# )
# else:
# response = s3_client.put_object(
# Bucket=bucket,
# Key=f'{kwargs["folder"]}/{kwargs["name"]}',
# Body=file,
# ContentType='image/png',
# )
# return response
# def upload_doc(file, bucket="cgv", **kwargs):
# """
# Function to upload a raw file to an S3 bucket
# """
# if kwargs["localhost"]:
# with open(file, "rb") as f:
# response = s3_client.upload_fileobj(
# f, bucket, f'certificates/{kwargs["number"]}.pdf')
# else:
# response = s3_client.put_object(
# Bucket=bucket,
# Key=f'certificates/{kwargs["number"]}.pdf',
# Body=file,
# )
# return response
# def delete_from_s3(file, bucket='cgv'):
# """
# Function to delete objects from S3 bucket
# """
# s3_client.delete_object(Bucket=bucket, Key=file)
# For Gravatar
def avatar(email, size):
digest = hashlib.md5(email.lower().encode('utf-8')).hexdigest()
return f'https://www.gravatar.com/avatar/{digest}?d=identicon&s={size}'
def send_password_reset_email(name, email):
token = s.dumps(email, salt='cgv-password-reset')
new_token = Token(email=email, token_id=token, status='A')
db.session.add(new_token)
db.session.commit()
if app.debug:
link = f"http://127.0.0.1:5000/reset-password/{token}"
else:
link = f"{config('site_url')}/reset-password/{token}"
print(link)
subject = "Password Reset Link | CGV"
return send_email_now(email, subject, '[email protected]', 'Password Bot CGV', 'emails/reset-password.html', name=name, link=link)
@app.route('/forgot', methods=['GET', 'POST'])
def forgot_password_page():
if (request.method == 'POST'):
email = request.form.get('email')
post = Users.query.filter_by(email=email).first()
name = post.name
if (post != None):
if (post.email == config("admin_email")):
flash("You can't reset password of administrator!", "danger")
else:
if send_password_reset_email(name, email):
flash(
f"We've sent a password reset link on {email}", "success")
else:
flash("Error while sending password reset email!", "danger")
elif (post == None):
flash("We didn't find your account!", "danger")
return render_template('forgot-password.html', favTitle=favTitle, verified=False)
return render_template('forgot-password.html', favTitle=favTitle, verified=False)
@app.route('/reset-password/<token>', methods=['GET', 'POST'])
def reset_password(token):
if current_user.is_authenticated:
return redirect(url_for('dashboard_page'))
if request.method == 'POST':
password = request.form.get('password')
password = sha256_crypt.hash(password)
email = s.loads(token, salt="cgv-password-reset")
user = Users.query.filter_by(email=email).first()
user.password = password
db_token = Token.query.filter_by(token_id=token).first()
db_token.status = 'U'
db.session.commit()
flash('Password changed successfully.', 'success')
return redirect(url_for('loginPage'))
try:
email = s.loads(token, salt="cgv-password-reset", max_age=1800)
except SignatureExpired:
db_token = Token.query.filter_by(token_id=token).first()
db_token.status = 'E'
db.session.commit()
flash("Sorry, link has been expired.", "danger")
return render_template('forgot-password.html', favTitle=favTitle, verified=False)
except Exception:
flash("Sorry, Invalid token.", "danger")
return render_template('forgot-password.html', favTitle=favTitle, verified=False)
user = Users.query.filter_by(email=email).first()
first_name = user.name.split(" ")[0]
db_token = Token.query.filter_by(token_id=token).first()
if db_token.status == 'U':
flash("Sorry, link has been already used.", "danger")
return render_template("forgot-password.html", favTitle=favTitle, name=first_name, token=token, verified=False)
elif db_token.status == 'E':
flash("Sorry, link has been expired.", "danger")
return render_template("forgot-password.html", favTitle=favTitle, name=first_name, token=token, verified=False)
return render_template("forgot-password.html", favTitle=favTitle, name=first_name, token=token, verified=True)
@app.route('/')
def home_page():
try:
response = requests.get(config("contributors_api"))
team = response.json()
except Exception:
team = {}
return render_template('index.html', favTitle=favTitle, team=team, user=current_user)
@app.route('/contact', methods=['GET', 'POST'])
def contact_page():
if (request.method == 'POST'):
name = request.form.get('name')
email = request.form.get('email')
phone = request.form.get('phone')
message = request.form.get('editordata')
if (host == True):
try:
ip_address = request.environ['HTTP_X_FORWARDED_FOR']
except KeyError:
ip_address = request.remote_addr
except Exception:
ip_address = ipc
else:
ip_address = ipc
# name validation it must be greater than than 2 letters and less than 40 letters
if len(name) >= 2 and len(name) <= 40:
pass
else:
flash("Please Enter Your Name Correctly!! ", "danger")
return redirect("/#footer")
# email validation
if check(email):
pass
else:
flash(
"Email is not Correct Please Check it and Try It once again!!", "danger")
return redirect('/#footer')
# number validation
if len(phone) >= 8 and len(phone) <= 13:
pass
else:
flash(
"Phone Number is not Correct Please Check it and Try It once again!!", "danger")
return redirect('/#footer')
entry = Contact(name=name, phone=phone, message=message, ip=ip_address, date=time,
email=email)
db.session.add(entry)
db.session.commit()
flash("Thank you for contacting us – we will get back to you soon!", "success")
return redirect('/#footer')
@app.route('/feedback', methods=['GET', 'POST'])
def feedback_page():
if (request.method == 'POST'):
data = json_lib.loads(request.data)
name = data["name"]
email = data["email"]
phone = data["phone"]
rating = data["rating"]
message = data["message"]
if (host == True):
try:
ip_address = request.environ['HTTP_X_FORWARDED_FOR']
except KeyError:
ip_address = request.remote_addr
except Exception:
ip_address = ipc
else:
ip_address = ipc
try:
entry = Feedback(name=name, phone=phone, rating=rating,
message=message, ip=ip_address, date=time, email=email)
db.session.add(entry)
db.session.commit()
return jsonify(feedback_success="Thank you for feedback – we will get back to you soon!", status=200)
except Exception:
return jsonify(feedback_error="Sorry, we could not record your feedback.", status=400)
return redirect('/#footer')
@app.route('/newsletter', methods=['GET', 'POST'])
def newsletter_page():
if (request.method == 'POST'):
email = request.form.get('email')
if (host == True):
try:
ip_address = request.environ['HTTP_X_FORWARDED_FOR']
except KeyError:
ip_address = request.remote_addr
except Exception:
ip_address = ipc
else:
ip_address = ipc
post = Newsletter.query.filter_by(email=email).first()
if (post == None):
entry = Newsletter(ip=ip_address, date=time, email=email)
db.session.add(entry)
db.session.commit()
flash("Thank you for subscribing!", "success")
else:
flash("You have already subscribed!", "danger")
return redirect('/#footer')
@app.route("/certificate/verify", methods=['GET', 'POST'])
def certificate_verify():
if (host == True):
try:
ip_address = request.environ['HTTP_X_FORWARDED_FOR']
except KeyError:
ip_address = request.remote_addr
except Exception:
ip_address = ipc
else:
ip_address = ipc
if (request.method == 'POST'):
certificate_no = request.form.get('certificateno')
postc = Certificate.query.filter_by(number=certificate_no).first()
if (postc != None):
posto = Group.query.filter_by(id=postc.group_id).first()
flash("Certificate Number Valid!", "success")
return render_template('Redesign-verify2.html', postc=postc, posto=posto, favTitle=favTitle, ip=ip_address)
elif (postc == None):
flash("No details found. Contact your organization!", "danger")
return render_template('Redesign-verify2.html', favTitle=favTitle, ip=ip_address, user=current_user)
# @app.route("/certificate/generate", methods=['GET', 'POST'])
# def certificate_generate():
# if (host == True):
# try:
# ip_address = request.environ['HTTP_X_FORWARDED_FOR']
# except KeyError:
# ip_address = request.remote_addr
# except Exception:
# ip_address = ipc
# else:
# ip_address = ipc
# if (request.method == 'POST'):
# certificateno = request.form.get('certificateno')
# postc = Certificate.query.filter_by(number=certificateno).first()
# if (postc != None):
# posto = Group.query.filter_by(id=postc.group_id).first()
# qr_code = QRCode.query.filter_by(
# certificate_num=certificateno).first()
# img_url = qr_code.qr_code
# rendered_temp = render_template('certificate.html', postc=postc, posto=posto,
# qr_code=img_url, favTitle=favTitle, site_url=site_url, number=certificateno, pdf=True)
# if not app.debug:
# configr = pdfkit.configuration(
# wkhtmltopdf='/app/bin/wkhtmltopdf')
# file = pdfkit.from_string(
# rendered_temp, False, css='static/css/certificate.css', configuration=configr)
# upload_doc(file, number=certificateno, localhost=False)
# download_url = f"https://cgv.s3.us-east-2.amazonaws.com/certificates/{certificateno}.pdf"
# else:
# try:
# pdfkit.from_string(
# rendered_temp, f"{certificateno}.pdf", css='static/css/certificate.css')
# except OSError:
# download_url = f"http://127.0.0.1:5000/download/{certificateno}.pdf"
# return render_template('certificate.html', postc=postc, qr_code=img_url, posto=posto, favTitle=favTitle, site_url=site_url, ip=ip_address, download_url=download_url)
# elif (postc == None):
# flash("No details found. Contact your organization!", "danger")
# return render_template('Redesign-generate.html', favTitle=favTitle, ip=ip_address, user=current_user)
@app.route("/certificate/generate", methods=['GET', 'POST'])
def certificate_generate():
if (host == True):
try:
ip_address = request.environ['HTTP_X_FORWARDED_FOR']
except KeyError:
ip_address = request.remote_addr
except Exception:
ip_address = ipc
else:
ip_address = ipc
if (request.method == 'POST'):
certificateno = request.form.get('certificateno')
postc = Certificate.query.filter_by(number=certificateno).first()
if (postc != None):
posto = Group.query.filter_by(id=postc.group_id).first()
postf = Fonts.query.filter_by(name=posto.font_name).first()
qr_code = QRCode.query.filter_by(
certificate_num=certificateno).first()
img_url = qr_code.qr_code
return render_template('certificate.html', postf=postf, postc=postc, qr_code=img_url, posto=posto, favTitle=favTitle, site_url=site_url, number=certificateno)
elif (postc == None):
flash("No details found. Contact your organization!", "danger")
return render_template('Redesign-generate.html', favTitle=favTitle, ip=ip_address, user=current_user)
# @app.route("/certify/<string:number>", methods=['GET'])
# def certificate_generate_string(number):
# postc = Certificate.query.filter_by(number=number).first()
# if (postc != None):
# style = "display: none;"
# posto = Group.query.filter_by(id=postc.group_id).first()
# qr_code = QRCode.query.filter_by(certificate_num=number).first()
# img_url = qr_code.qr_code
# rendered_temp = render_template('certificate.html', postc=postc, posto=posto,
# qr_code=img_url, favTitle=favTitle, site_url=site_url, number=number, style=style, pdf=True)
# if not app.debug:
# configr = pdfkit.configuration(wkhtmltopdf='/app/bin/wkhtmltopdf')
# file = pdfkit.from_string(
# rendered_temp, False, css='static/css/certificate.css', configuration=configr)
# upload_doc(file, number=number, localhost=False)
# download_url = f"https://cgv.s3.us-east-2.amazonaws.com/certificates/{number}.pdf"
# else:
# try:
# pdfkit.from_string(
# rendered_temp, f"{number}.pdf", css='static/css/certificate.css')
# except OSError:
# download_url = f"http://127.0.0.1:5000/download/{number}.pdf"
# return render_template('certificate.html', postc=postc, posto=posto, qr_code=img_url, favTitle=favTitle, site_url=site_url, number=number, download_url=download_url, pdf=False)
# else:
# return redirect('/')
@app.route("/certify/<string:number>", methods=['GET'])
def certificate_generate_string(number):
postc = Certificate.query.filter_by(number=number).first()
if (postc != None):
style = "display: none;"
posto = Group.query.filter_by(id=postc.group_id).first()
postf = Fonts.query.filter_by(name=posto.font_name).first()
qr_code = QRCode.query.filter_by(certificate_num=number).first()
img_url = qr_code.qr_code
return render_template('certificate.html', postf=postf, postc=postc, posto=posto, qr_code=img_url, favTitle=favTitle, site_url=site_url, number=number, style=style)
else:
return redirect('/')
@app.route('/download/<path:filename>', methods=['GET', 'POST'])
def download(filename):
docs = os.path.join(current_app.root_path)
return send_from_directory(directory=docs, filename=filename)
# Payment Views
@app.route("/pay", methods=["GET", "POST"])
def pay_now():
name = request.form.get("name")
email = request.form.get("email")
phone = request.form.get("phone")
plan = request.form.get("plan")
plan_info = {
"Basic Plan": 100,
"Regular Plan": 200,
"Premium Plan": 300
}
order_amount = plan_info[plan] * 100
order_currency = 'INR'
client = razorpay.Client(auth=(RAZORPAY_KEY_ID, RAZORPAY_KEY_SECRET))
order = client.order.create(
{'amount': order_amount, 'currency': order_currency, 'payment_capture': '1'})
context = {
"payment": order,
"name": name,
"phone": phone,
"email": email,
"rzp_id": RAZORPAY_KEY_ID,
"currency": order_currency
}
return render_template("razorpay.html", context=context)
@app.route("/razorpay-handler/", methods=["GET", "POST"])
def razorpay_handler():
# from front end
payment_id = request.form.get('payment_id')
order_id = request.form.get('order_id')
sign = request.form.get('sign')
server_order = request.form.get('server_order')
name = request.form.get('name')
email = request.form.get('email')
phone = request.form.get('phone')
amount = int(request.form.get('amount')) // 100
currency = request.form.get('currency')
# genrate signature
secret_key = bytes(RAZORPAY_KEY_SECRET, 'utf-8')
generated_signature = hmac.new(secret_key, bytes(server_order + "|" + payment_id, 'utf-8'),
hashlib.sha256).hexdigest()
# checking authentic source
if generated_signature == sign:
new_txn = Transactions(name=name, email=email, phone=phone, order_id=order_id, amount=amount, currency=currency,
payment_id=payment_id, response_msg=sign, status="SUCCESS")
db.session.add(new_txn)
db.session.commit()
return jsonify(success=True)
return jsonify(success=False)
@app.route("/payment-failure/", methods=["GET", "POST"])
def failed_payment():
# from front end
payment_id = request.form.get('payment_id')
order_id = request.form.get('order_id')
server_order = request.form.get('server_order')
reason = request.form.get('reason')
step = request.form.get('step')
source = request.form.get('source')
description = request.form.get('description')
code = request.form.get('code')
name = request.form.get('name')
email = request.form.get('email')
phone = request.form.get('phone')
amount = int(request.form.get('amount')) // 100
currency = request.form.get('currency')
new_txn = Transactions(name=name, email=email, phone=phone, order_id=order_id, amount=amount, currency=currency,
payment_id=payment_id, error_source=source, error_code=code,
response_msg="Step : " + step + ", Reason : " + reason + ", Desc: " + description,
status="FAILURE")
db.session.add(new_txn)
db.session.commit()
return jsonify(success=True)
@app.route('/login', methods=['GET', 'POST'])
def loginPage():
# TODO: Check for active session
if current_user.is_authenticated:
return redirect(url_for('dashboard_page'))
if (request.method == 'POST'):
email = request.form.get('email')
password = request.form.get('password')
remember = request.form.get('remember')
response = Users.query.filter_by(email=email).first()
if ((response != None) and (response.status == 1) and (response.email == email) and (
sha256_crypt.verify(password, response.password) == 1) and (response.status == 1)):
updateloginTime = Users.query.filter_by(email=email).first()
updateloginTime.last_login = time
db.session.commit()
login_user(response, remember=remember)
next_page = request.args.get('next')
return redirect(next_page) if next_page else redirect(url_for('dashboard_page'))
else:
flash("Invalid credentials or account not activated!", "danger")
return render_template('login.html', favTitle=favTitle)
else:
return render_template('login.html', favTitle=favTitle)
@app.route('/validate/email', methods=['POST'])
def email_validation():
data = json_lib.loads(request.data)
email = data['email']
pattern = '^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
user = Users.query.filter_by(email=email).first()
if user and user.status == 0:
return jsonify(account_inactive=True)
if user:
return jsonify(email_error='You are already registered. Please login to continue.', status=409)
if not bool(re.match(pattern, email)):
return jsonify(email_pattern_error='Please enter a valid email address.')
return jsonify(email_valid=True)
@app.route('/validate/password', methods=['POST'])
def validate_password():
data = json_lib.loads(request.data)
password = data["password"]
pattern = '^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[$#@!%^&*()])(?=\S+$).{8,30}$'
if bool(re.match(pattern, password)):
return jsonify(password_valid=True)
return jsonify(
password_error='Password must be 8-30 characters long and must contain atleast one uppercase letter, one lowercase letter, one number(0-9) and one special character(@,#,$,%,&,_)')
@app.route('/match/passwords', methods=["POST"])
def match_passwords():
data = json_lib.loads(request.data)
password1 = data['password']
password2 = data['password2']
if str(password1) == str(password2):
return jsonify(password_match=True)
return jsonify(password_mismatch='Password and Confirm Password do not match.')
def send_activation_email(name, email):
token = s.dumps(email, salt='cgv-email-confirm')
new_token = Token(email=email, token_id=token, status='A')
db.session.add(new_token)
db.session.commit()
if app.debug:
link = f"http://127.0.0.1:5000/confirm-email/{token}"
else:
link = f"{config('site_url')}/confirm-email/{token}"
print(link)
subject = "Welcome aboard " + name + "!"
return send_email_now(email, subject, '[email protected]', 'Register Bot CGV', 'emails/account-activation.html', name=name, link=link)
@app.route('/register', methods=['GET', 'POST'])
def register_page():
if current_user.is_authenticated:
return redirect(url_for('dashboard_page'))
if (request.method == 'POST'):
name = request.form.get('name')
email = request.form.get('email')
password = request.form.get('password')
password = sha256_crypt.hash(password)
profile_image = avatar(email, 128)
entry = Users(name=name, email=email, password=password, profile_image=profile_image,
status=0, is_staff=0, last_login=time,)
db.session.add(entry)
db.session.commit()
if send_activation_email(name, email):
flash(
f"We've sent an account activation link on {email}", "success")
else:
flash("Error while sending account activation email!", "danger")
return render_template('resend.html', favTitle=favTitle)
return render_template('register.html', favTitle=favTitle)
@app.route('/resend-link/', methods=['GET', 'POST'])
def resend_email():
if current_user.is_authenticated:
return redirect(url_for('dashboard_page'))
if request.method == 'POST':
email = request.form.get('email')
user = Users.query.filter_by(email=email).first()
if user:
if user.status == 1:
flash('Your account is already activated. Please login', 'danger')
return redirect(url_for('resend_email'))
name = user.name
if send_activation_email(name, email):
flash(
f"We've sent an account activation link on {email}", "success")
else:
flash("Error while sending account activation email!", "danger")
else:
flash('You are not registered yet.', 'danger')
return redirect(url_for('resend_email'))
return render_template("resend.html", favTitle=favTitle)
@app.route('/confirm-email/<token>', methods=['GET'])
def confirm_email(token):
if current_user.is_authenticated:
return redirect(url_for('dashboard_page'))
try:
email = s.loads(token, salt="cgv-email-confirm", max_age=1800)
except SignatureExpired:
db_token = Token.query.filter_by(token_id=token).first()
db_token.status = 'E'
flash("Sorry, link has been expired.")
return render_template('login.html', favTitle=favTitle)
db_token = Token.query.filter_by(token_id=token).first()
if db_token.status == 'U':
flash("Sorry, link has been already used.", "danger")
return render_template("resend.html", favTitle=favTitle)
elif db_token.status == 'E':
flash("Sorry, link has been expired.", "danger")
return render_template("resend.html", favTitle=favTitle)
user = Users.query.filter_by(email=email).first()
user.status = 1
db_token = Token.query.filter_by(token_id=token).first()
db_token.status = 'U'
user.last_login = time
db.session.commit()
# Some error here
if (host == True):
try:
ip_address = request.environ['HTTP_X_FORWARDED_FOR']
except KeyError:
ip_address = request.remote_addr
except Exception:
ip_address = ipc
else:
ip_address = ipc
try:
url = requests.get("http://ip-api.com/json/{}".format(ip_address))
j = url.json()
city = j["city"]
country = j["country"]
subject = " New device login from " + \
str(city) + ", " + str(country) + " detected."
email_sent = send_email_now(email, subject, '[email protected]',
'Security Bot CGV', 'emails/login-alert.html', city=city, country=country, time=str(time), ip_address=str(ip_address))
except Exception:
pass
login_user(user)
next_page = request.args.get('next')
return redirect(next_page) if next_page else redirect(url_for('dashboard_page'))
@app.route('/dashboard')
@login_required
def dashboard_page():
postc = len(Certificate.query.order_by(Certificate.id).all())
postct = len(Contact.query.order_by(Contact.id).all())
postf = len(Feedback.query.order_by(Feedback.id).all())
postn = len(Newsletter.query.order_by(Newsletter.id).all())
return render_template('dashboard.html', favTitle=favTitle, postc=postc, postct=postct, postf=postf, postn=postn, user=current_user)
@app.route("/view/groups", methods=['GET', 'POST'])
@login_required
def view_org_page():
if current_user.is_staff:
post = Group.query.order_by(Group.id).all()
else:
post = Group.query.filter_by(
user_id=current_user.id).order_by(Group.id).all()
return render_template('org_table.html', post=post, favTitle=favTitle, user=current_user)
@app.route("/view/users", methods=['GET', 'POST'])
@login_required
@admin_required
def view_users_page():
post = Users.query.order_by(Users.id).all()
return render_template('users_table.html', post=post, favTitle=favTitle, user=current_user)