-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
3345 lines (3070 loc) · 137 KB
/
Copy pathapp.py
File metadata and controls
3345 lines (3070 loc) · 137 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 flask import Flask, render_template, request, redirect, url_for, flash, session, make_response, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, BooleanField, TextAreaField, SelectField, DateField, FileField
from wtforms.validators import InputRequired, Email, Length, EqualTo, ValidationError, Optional
from flask_wtf.file import FileField, FileAllowed
from werkzeug.security import generate_password_hash, check_password_hash
from werkzeug.utils import secure_filename
from flask_mail import Mail, Message
from itsdangerous import URLSafeTimedSerializer, SignatureExpired, BadSignature
import secrets
import os
import json
from datetime import datetime
from io import BytesIO
from dotenv import load_dotenv
# Google OAuth imports
try:
from google.oauth2 import id_token
from google.auth.transport import requests as google_requests
GOOGLE_AUTH_AVAILABLE = True
except ImportError:
GOOGLE_AUTH_AVAILABLE = False
# Load environment variables
load_dotenv()
try:
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter, A4
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle
from reportlab.lib import colors
from reportlab.lib.units import inch
PDF_AVAILABLE = True
except ImportError:
PDF_AVAILABLE = False
app = Flask(__name__)
# Configuration
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY', secrets.token_hex(16))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///carhub.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# Email configuration (using environment variables)
app.config['MAIL_SERVER'] = os.getenv('MAIL_SERVER', 'smtp.gmail.com')
app.config['MAIL_PORT'] = int(os.getenv('MAIL_PORT', 587))
app.config['MAIL_USE_TLS'] = os.getenv('MAIL_USE_TLS', 'True').lower() == 'true'
app.config['MAIL_USERNAME'] = os.getenv('MAIL_USERNAME', 'your-email@gmail.com')
app.config['MAIL_PASSWORD'] = os.getenv('MAIL_PASSWORD', 'your-app-password')
app.config['MAIL_DEFAULT_SENDER'] = os.getenv('MAIL_DEFAULT_SENDER', os.getenv('MAIL_USERNAME', 'your-email@gmail.com'))
# Google OAuth configuration
app.config['GOOGLE_CLIENT_ID'] = os.getenv('GOOGLE_CLIENT_ID')
app.config['GOOGLE_CLIENT_SECRET'] = os.getenv('GOOGLE_CLIENT_SECRET')
# File upload configuration
UPLOAD_FOLDER = 'static/uploads/profiles'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB max file size
# Ensure upload directory exists
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
# Initialize extensions
db = SQLAlchemy(app)
mail = Mail(app)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
login_manager.login_message = 'Please log in to access this page.'
login_manager.login_message_category = 'info'
serializer = URLSafeTimedSerializer(app.config['SECRET_KEY'])
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
# User Model
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
password_hash = db.Column(db.String(255), nullable=True) # Make nullable for Google users
is_verified = db.Column(db.Boolean, default=False)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
last_login = db.Column(db.DateTime)
# Google OAuth fields
google_id = db.Column(db.String(100), unique=True, nullable=True)
profile_picture = db.Column(db.String(200), nullable=True)
# Enhanced profile fields
first_name = db.Column(db.String(50), nullable=True)
last_name = db.Column(db.String(50), nullable=True)
phone = db.Column(db.String(20), nullable=True)
date_of_birth = db.Column(db.Date, nullable=True)
gender = db.Column(db.String(10), nullable=True)
address = db.Column(db.Text, nullable=True)
city = db.Column(db.String(100), nullable=True)
state = db.Column(db.String(100), nullable=True)
zip_code = db.Column(db.String(20), nullable=True)
country = db.Column(db.String(100), nullable=True)
occupation = db.Column(db.String(100), nullable=True)
bio = db.Column(db.Text, nullable=True)
preferred_contact_method = db.Column(db.String(20), default='email')
profile_updated_at = db.Column(db.DateTime, nullable=True)
def set_password(self, password):
self.password_hash = generate_password_hash(password)
def check_password(self, password):
if not self.password_hash:
return False
return check_password_hash(self.password_hash, password)
def is_google_user(self):
return self.google_id is not None
def get_full_name(self):
"""Get user's full name"""
if self.first_name and self.last_name:
return f"{self.first_name} {self.last_name}"
elif self.first_name:
return self.first_name
elif self.last_name:
return self.last_name
else:
return self.username
def get_profile_completion_percentage(self):
"""Calculate profile completion percentage"""
fields = [
self.first_name, self.last_name, self.phone, self.date_of_birth,
self.gender, self.address, self.city, self.state, self.zip_code,
self.country, self.occupation, self.bio
]
completed_fields = sum(1 for field in fields if field)
return int((completed_fields / len(fields)) * 100)
def __repr__(self):
return f'<User {self.username}>'
def __repr__(self):
return f'<User {self.username}>'
# Payment and Order Models
class Car(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
slug = db.Column(db.String(100), unique=True, nullable=False)
price = db.Column(db.Float, nullable=False)
category = db.Column(db.String(50), nullable=False)
description = db.Column(db.Text)
video_url = db.Column(db.String(200))
created_at = db.Column(db.DateTime, default=datetime.utcnow)
def __repr__(self):
return f'<Car {self.name}>'
class Order(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
car_id = db.Column(db.Integer, db.ForeignKey('car.id'), nullable=False)
total_amount = db.Column(db.Float, nullable=False)
cancellation_fee = db.Column(db.Float, default=0.0) # Track cancellation fees
payment_status = db.Column(db.String(20), default='pending')
order_status = db.Column(db.String(20), default='pending') # Track order status
payment_method = db.Column(db.String(50))
transaction_id = db.Column(db.String(100))
billing_name = db.Column(db.String(100), nullable=False)
billing_email = db.Column(db.String(120), nullable=False)
billing_phone = db.Column(db.String(20), nullable=False)
billing_address = db.Column(db.Text, nullable=False)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
# Relationships
user = db.relationship('User', backref=db.backref('orders', lazy=True))
car = db.relationship('Car', backref=db.backref('orders', lazy=True))
def __repr__(self):
return f'<Order {self.id}>'
class FinanceApplication(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
car_id = db.Column(db.String(50)) # Can be string since it comes from URL params
car_name = db.Column(db.String(200), nullable=False)
car_price = db.Column(db.String(50), nullable=False)
full_name = db.Column(db.String(100), nullable=False)
email = db.Column(db.String(120), nullable=False)
phone = db.Column(db.String(20), nullable=False)
annual_income = db.Column(db.String(50), nullable=False)
employment_status = db.Column(db.String(50), nullable=False)
credit_score_range = db.Column(db.String(50))
address = db.Column(db.Text, nullable=False)
selected_plan = db.Column(db.String(50), nullable=False)
application_status = db.Column(db.String(20), default='pending')
created_at = db.Column(db.DateTime, default=datetime.utcnow)
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
# Relationships
user = db.relationship('User', backref=db.backref('finance_applications', lazy=True))
def __repr__(self):
return f'<FinanceApplication {self.id}>'
class UserActivity(db.Model):
__tablename__ = 'user_activity_log' # Explicit table name to avoid conflicts
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
activity_type = db.Column(db.String(50), nullable=False) # login, logout, view_car, order_placed, etc.
description = db.Column(db.String(255), nullable=False)
ip_address = db.Column(db.String(45), nullable=True) # IPv4/IPv6
user_agent = db.Column(db.String(500), nullable=True)
activity_data = db.Column(db.Text, nullable=True) # JSON string for additional data (changed from metadata)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
# Relationships
user = db.relationship('User', backref=db.backref('activities', lazy=True, order_by='UserActivity.created_at.desc()'))
def __repr__(self):
return f'<UserActivity {self.activity_type} by {self.user_id}>'
class PartOrder(db.Model):
__tablename__ = 'part_orders'
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
part_id = db.Column(db.String(50), nullable=False) # e.g., 'turbo-001'
part_name = db.Column(db.String(200), nullable=False)
part_number = db.Column(db.String(100), nullable=False)
brand = db.Column(db.String(100), nullable=False)
category = db.Column(db.String(100), nullable=False)
quantity = db.Column(db.Integer, default=1, nullable=False)
unit_price = db.Column(db.Float, nullable=False)
total_amount = db.Column(db.Float, nullable=False)
payment_status = db.Column(db.String(20), default='pending')
order_status = db.Column(db.String(20), default='processing') # processing, shipped, delivered, cancelled
payment_method = db.Column(db.String(50))
transaction_id = db.Column(db.String(100))
billing_name = db.Column(db.String(100), nullable=False)
billing_email = db.Column(db.String(120), nullable=False)
billing_phone = db.Column(db.String(20), nullable=False)
billing_address = db.Column(db.Text, nullable=False)
shipping_address = db.Column(db.Text, nullable=True) # Can be different from billing
tracking_number = db.Column(db.String(100), nullable=True)
notes = db.Column(db.Text, nullable=True)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
# Relationships
user = db.relationship('User', backref=db.backref('part_orders', lazy=True))
def __repr__(self):
return f'<PartOrder {self.id} - {self.part_name}>'
# Forms
class LoginForm(FlaskForm):
email = StringField('Email', validators=[InputRequired(), Email()])
password = PasswordField('Password', validators=[InputRequired()])
remember_me = BooleanField('Remember Me')
submit = SubmitField('Sign In')
class SignUpForm(FlaskForm):
username = StringField('Username', validators=[
InputRequired(),
Length(min=4, max=20, message="Username must be between 4 and 20 characters")
])
email = StringField('Email', validators=[InputRequired(), Email()])
password = PasswordField('Password', validators=[
InputRequired(),
Length(min=8, message="Password must be at least 8 characters long")
])
password2 = PasswordField('Confirm Password', validators=[
InputRequired(),
EqualTo('password', message='Passwords must match')
])
submit = SubmitField('Create Account')
def validate_username(self, username):
user = User.query.filter_by(username=username.data).first()
if user:
raise ValidationError('Username already exists. Choose a different one.')
def validate_email(self, email):
user = User.query.filter_by(email=email.data).first()
if user:
raise ValidationError('Email already registered. Please use a different email.')
class ForgotPasswordForm(FlaskForm):
email = StringField('Email', validators=[InputRequired(), Email()])
submit = SubmitField('Send Reset Link')
class ResetPasswordForm(FlaskForm):
password = PasswordField('New Password', validators=[
InputRequired(),
Length(min=8, message="Password must be at least 8 characters long")
])
password2 = PasswordField('Confirm New Password', validators=[
InputRequired(),
EqualTo('password', message='Passwords must match')
])
submit = SubmitField('Reset Password')
class PaymentForm(FlaskForm):
billing_name = StringField('Full Name', validators=[
InputRequired(),
Length(min=2, max=100, message="Name must be between 2 and 100 characters")
])
billing_email = StringField('Email', validators=[InputRequired(), Email()])
billing_phone = StringField('Phone Number', validators=[
InputRequired(),
Length(min=10, max=20, message="Please enter a valid phone number")
])
billing_address = StringField('Address', validators=[
InputRequired(),
Length(min=10, max=500, message="Please enter a complete address")
])
payment_method = StringField('Payment Method', validators=[InputRequired()])
card_number = StringField('Card Number')
card_expiry = StringField('Expiry Date (MM/YY)')
card_cvv = StringField('CVV')
submit = SubmitField('Complete Payment')
class ProfileForm(FlaskForm):
username = StringField('Username', validators=[
InputRequired(),
Length(min=4, max=20, message="Username must be between 4 and 20 characters")
])
email = StringField('Email Address', validators=[Optional()], render_kw={'readonly': True})
profile_picture = FileField('Profile Picture', validators=[Optional(), FileAllowed(['jpg', 'jpeg', 'png'], 'Images only!')])
first_name = StringField('First Name', validators=[Optional(), Length(max=50)])
last_name = StringField('Last Name', validators=[Optional(), Length(max=50)])
phone = StringField('Phone Number', validators=[Optional(), Length(max=20)])
date_of_birth = DateField('Date of Birth', validators=[Optional()])
gender = SelectField('Gender', choices=[
('', 'Select Gender'),
('male', 'Male'),
('female', 'Female'),
('other', 'Other'),
('prefer_not_to_say', 'Prefer not to say')
], validators=[Optional()])
address = TextAreaField('Address', validators=[Optional(), Length(max=500)])
city = StringField('City', validators=[Optional(), Length(max=100)])
state = StringField('State', validators=[Optional(), Length(max=100)])
zip_code = StringField('ZIP Code', validators=[Optional(), Length(max=20)])
country = StringField('Country', validators=[Optional(), Length(max=100)])
occupation = StringField('Occupation', validators=[Optional(), Length(max=100)])
bio = TextAreaField('Bio', validators=[Optional(), Length(max=1000)])
preferred_contact_method = SelectField('Preferred Contact Method', choices=[
('email', 'Email'),
('phone', 'Phone'),
('both', 'Both')
], validators=[Optional()])
submit = SubmitField('Update Profile')
def validate_username(self, username):
# Only validate if username has changed
if username.data != current_user.username:
user = User.query.filter_by(username=username.data).first()
if user:
raise ValidationError('Username already exists. Please choose a different one.')
# Helper functions
def log_user_activity(user_id, activity_type, description, metadata=None):
"""Log user activity"""
try:
activity = UserActivity(
user_id=user_id,
activity_type=activity_type,
description=description,
ip_address=request.remote_addr if request else None,
user_agent=request.headers.get('User-Agent', '') if request else None,
activity_data=json.dumps(metadata) if metadata else None
)
db.session.add(activity)
db.session.commit()
except Exception as e:
print(f"Error logging activity: {e}")
def is_admin(user):
"""Check if user is admin"""
return user and user.is_authenticated and user.email == 'admin@carhub.com'
def send_email(subject, recipient, template, **kwargs):
"""Send email using Flask-Mail"""
try:
msg = Message(subject, recipients=[recipient])
msg.html = template
mail.send(msg)
return True
except Exception as e:
print(f"Error sending email: {e}")
return False
def generate_reset_token(email):
"""Generate password reset token"""
return serializer.dumps(email, salt='password-reset-salt')
def verify_reset_token(token, expiration=3600):
"""Verify password reset token"""
try:
email = serializer.loads(token, salt='password-reset-salt', max_age=expiration)
return email
except (SignatureExpired, BadSignature):
return None
# Routes
@app.route('/')
def index():
return render_template('index.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
if current_user.is_authenticated:
return redirect(url_for('index'))
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user and user.check_password(form.password.data):
# Update last login
user.last_login = datetime.utcnow()
db.session.commit()
# Login user with Flask-Login
login_user(user, remember=form.remember_me.data)
# Log login activity
log_user_activity(user.id, 'login', f'User {user.username} logged in successfully')
flash('Welcome back! You have been logged in successfully.', 'success')
next_page = request.args.get('next')
return redirect(next_page) if next_page else redirect(url_for('index'))
else:
# Log failed login attempt
if user:
log_user_activity(user.id, 'login_failed', f'Failed login attempt for user {user.username}')
flash('Invalid email or password. Please try again.', 'error')
return render_template('login.html', form=form)
@app.route('/auth/google', methods=['POST'])
def google_auth():
"""Handle Google OAuth authentication"""
if not GOOGLE_AUTH_AVAILABLE:
return jsonify({'success': False, 'message': 'Google OAuth is not available'}), 500
try:
# Get the credential from the request
data = request.get_json()
credential = data.get('credential') if data else None
if not credential:
return jsonify({'success': False, 'message': 'No credential provided'}), 400
# Verify the Google ID token
idinfo = id_token.verify_oauth2_token(
credential,
google_requests.Request(),
app.config['GOOGLE_CLIENT_ID']
)
# Extract user information
google_id = idinfo['sub']
email = idinfo['email']
name = idinfo['name']
picture = idinfo.get('picture', '')
# Check if user exists in your database
user = User.query.filter_by(email=email).first()
if not user:
# Create new user with Google info
# Generate a username from email
username = email.split('@')[0]
counter = 1
original_username = username
while User.query.filter_by(username=username).first():
username = f"{original_username}{counter}"
counter += 1
user = User(
username=username,
email=email,
google_id=google_id,
profile_picture=picture,
is_verified=True # Google accounts are pre-verified
)
db.session.add(user)
else:
# Update existing user with Google info
if not user.google_id:
user.google_id = google_id
user.profile_picture = picture
user.is_verified = True
# Update last login
user.last_login = datetime.utcnow()
db.session.commit()
# Log the user in
login_user(user, remember=True)
return jsonify({
'success': True,
'message': 'Successfully signed in with Google',
'redirect_url': url_for('dashboard')
})
except ValueError as e:
return jsonify({'success': False, 'message': f'Invalid Google token: {str(e)}'}), 400
except Exception as e:
return jsonify({'success': False, 'message': f'Authentication failed: {str(e)}'}), 500
@app.route('/sign_up', methods=['GET', 'POST'])
def sign_up():
if current_user.is_authenticated:
return redirect(url_for('index'))
form = SignUpForm()
if form.validate_on_submit():
# Check if user already exists
existing_user = User.query.filter(
(User.username == form.username.data) |
(User.email == form.email.data)
).first()
if existing_user:
if existing_user.username == form.username.data:
flash('Username already exists. Please choose a different one.', 'error')
else:
flash('Email already registered. Please use a different email.', 'error')
else:
# Create new user
user = User(
username=form.username.data,
email=form.email.data
)
user.set_password(form.password.data)
try:
db.session.add(user)
db.session.commit()
flash('Account created successfully! You can now log in.', 'success')
return redirect(url_for('login'))
except Exception as e:
db.session.rollback()
flash('An error occurred while creating your account. Please try again.', 'error')
return render_template('sign_up.html', form=form)
@app.route('/forgot_password', methods=['GET', 'POST'])
def forgot_password():
form = ForgotPasswordForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user:
# Generate reset token
token = generate_reset_token(user.email)
reset_url = url_for('reset_password', token=token, _external=True)
# Email template
email_template = f'''
<html>
<body style="font-family: Arial, sans-serif; background-color: #f4f4f4; padding: 20px;">
<div style="max-width: 600px; margin: 0 auto; background-color: white; padding: 30px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
<h2 style="color: #7c4dff; text-align: center;">CarHub Password Reset</h2>
<p>Hello {user.username},</p>
<p>You have requested to reset your password. Click the link below to reset your password:</p>
<div style="text-align: center; margin: 30px 0;">
<a href="{reset_url}" style="background-color: #7c4dff; color: white; padding: 12px 30px; text-decoration: none; border-radius: 5px; display: inline-block;">Reset Password</a>
</div>
<p><strong>Note:</strong> This link will expire in 1 hour.</p>
<p>If you didn't request this reset, please ignore this email.</p>
<p>Best regards,<br>CarHub Team</p>
</div>
</body>
</html>
'''
if send_email('CarHub - Password Reset Request', user.email, email_template):
flash('Password reset link has been sent to your email.', 'info')
else:
flash('Error sending email. Please try again later.', 'error')
else:
# Don't reveal if email exists or not for security
flash('If an account with that email exists, a password reset link has been sent.', 'info')
return render_template('forgot_password.html', form=form)
@app.route('/reset_password/<token>', methods=['GET', 'POST'])
def reset_password(token):
email = verify_reset_token(token)
if not email:
flash('Invalid or expired reset token.', 'error')
return redirect(url_for('forgot_password'))
user = User.query.filter_by(email=email).first()
if not user:
flash('Invalid reset token.', 'error')
return redirect(url_for('forgot_password'))
form = ResetPasswordForm()
if form.validate_on_submit():
user.set_password(form.password.data)
db.session.commit()
flash('Your password has been reset successfully. You can now log in.', 'success')
return redirect(url_for('login'))
return render_template('reset_password.html', form=form)
@app.route('/logout')
@login_required
def logout():
# Log logout activity before logging out
log_user_activity(current_user.id, 'logout', f'User {current_user.username} logged out')
logout_user()
flash('You have been logged out successfully.', 'info')
return redirect(url_for('index'))
@app.route('/cars')
def cars():
return render_template('cars.html')
@app.route('/video')
def video():
return render_template('video_gallery.html')
@app.route('/about', methods=['GET', 'POST'])
def about():
if request.method == 'POST':
try:
# Get form data
name = request.form.get('name')
email = request.form.get('email')
rating = request.form.get('rating')
feedback_type = request.form.get('feedback-type')
message = request.form.get('message')
# Validate required fields
if not all([name, email, rating, feedback_type, message]):
flash('Please fill in all required fields.', 'error')
return render_template('about.html')
# Create email message
subject = f"New Feedback from {name} - CarHub"
html_body = f"""
<html>
<body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333;">
<div style="max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #ddd; border-radius: 10px;">
<h2 style="color: #7c4dff; text-align: center;">New Feedback from CarHub</h2>
<hr style="border-color: #7c4dff;">
<p><strong>Customer Details:</strong></p>
<ul style="list-style: none; padding: 0;">
<li style="padding: 5px 0;"><strong>Name:</strong> {name}</li>
<li style="padding: 5px 0;"><strong>Email:</strong> {email}</li>
<li style="padding: 5px 0;"><strong>Rating:</strong> {rating}/5 ⭐</li>
<li style="padding: 5px 0;"><strong>Feedback Type:</strong> {feedback_type.title()}</li>
</ul>
<p><strong>Message:</strong></p>
<div style="background: #f9f9f9; padding: 15px; border-radius: 5px; margin: 10px 0;">
{message}
</div>
<hr style="border-color: #ddd;">
<p style="color: #666; font-size: 0.9em; text-align: center;">
Submitted on: {datetime.now().strftime('%Y-%m-%d at %H:%M:%S')}
</p>
</div>
</body>
</html>
"""
# Send email
try:
msg = Message(
subject=subject,
recipients=[app.config['MAIL_USERNAME']], # Send to configured email
html=html_body,
reply_to=email
)
mail.send(msg)
print(f"Email sent successfully to {app.config['MAIL_USERNAME']}")
except Exception as email_error:
print(f"Email sending failed: {email_error}")
# Continue without failing the form submission
pass
flash('Thank you for your feedback! We\'ll get back to you soon.', 'success')
return redirect(url_for('about'))
except Exception as e:
flash('Sorry, there was an error sending your feedback. Please try again.', 'error')
print(f"Email error: {e}")
return render_template('about.html')
@app.route('/services')
def services():
return render_template('services.html')
@app.route('/contact', methods=['GET', 'POST'])
def contact():
if request.method == 'POST':
# Get form data
first_name = request.form.get('firstName')
last_name = request.form.get('lastName')
email = request.form.get('email')
phone = request.form.get('phone')
subject = request.form.get('subject')
message = request.form.get('message')
newsletter = request.form.get('newsletter')
# In a real app, you would:
# 1. Save the message to database
# 2. Send email notification to admin
# 3. Send confirmation email to user
# 4. Add proper validation and error handling
# For now, we'll just flash a success message
flash('Thank you for your message! We\'ll get back to you within 24 hours.', 'success')
return redirect(url_for('contact'))
return render_template('contact.html')
@app.route('/inventory')
def inventory():
# Enhanced car parts inventory data with unique and diverse product names
inventory_parts = [
{
'id': 'turbo-001',
'name': 'Garrett GT2860RS Turbocharger',
'category': 'Engine Parts',
'brand': 'Garrett Motion',
'part_number': 'GTM-2860RS-001',
'price': '$2,850',
'status': 'In Stock',
'compatibility': 'BMW M3, M4, M5',
'image': 'parts/turbocharger.jpg',
'description': 'High-performance ball bearing turbocharger with advanced aerodynamics for maximum efficiency and power output.',
'warranty': '2 Years',
'condition': 'New'
},
{
'id': 'brake-002',
'name': 'Brembo GT Racing Ceramic Pads',
'category': 'Brake System',
'brand': 'Brembo',
'part_number': 'BRM-GTRC-002',
'price': '$485',
'status': 'In Stock',
'compatibility': 'Porsche 911, Cayman',
'image': 'parts/brake-pads.jpg',
'description': 'Premium ceramic brake pads designed for track and street performance with minimal dust production.',
'warranty': '1 Year',
'condition': 'New'
},
{
'id': 'susp-003',
'name': 'Bilstein B16 PSS10 Coilovers',
'category': 'Suspension',
'brand': 'Bilstein',
'part_number': 'BIL-B16-PSS10',
'price': '$1,650',
'status': 'Low Stock',
'compatibility': 'Audi A4, A6, S4',
'image': 'parts/coilover.jpg',
'description': 'Motorsport-derived coilover suspension system with 10-way adjustable damping.',
'warranty': '2 Years',
'condition': 'New'
},
{
'id': 'air-004',
'name': 'K&N Apollo Cold Air Intake',
'category': 'Engine Parts',
'brand': 'K&N Engineering',
'part_number': 'KN-APOLLO-CAI',
'price': '$320',
'status': 'In Stock',
'compatibility': 'Honda Civic Type R',
'image': 'parts/air-filter.jpg',
'description': 'Complete cold air intake system with high-flow filter for increased horsepower and torque.',
'warranty': '1 Year',
'condition': 'New'
},
{
'id': 'exh-005',
'name': 'Akrapovic Evolution Titanium System',
'category': 'Exhaust',
'brand': 'Akrapovic',
'part_number': 'AKR-EVO-TI-V1',
'price': '$3,200',
'status': 'Pre-Order',
'compatibility': 'Lamborghini Huracan',
'image': 'parts/exhaust-system.jpg',
'description': 'Full titanium exhaust system with valve control and distinctive Akrapovic sound signature.',
'warranty': '2 Years',
'condition': 'New'
},
{
'id': 'trans-006',
'name': 'ZF 8HP76 Performance Transmission',
'category': 'Transmission',
'brand': 'ZF Friedrichshafen',
'part_number': 'ZF-8HP76-PERF',
'price': '$8,500',
'status': 'Out of Stock',
'compatibility': 'BMW X5, X6, 7 Series',
'image': 'parts/transmission.jpg',
'description': 'High-performance 8-speed automatic transmission with sport programming and launch control.',
'warranty': '3 Years',
'condition': 'Remanufactured'
},
{
'id': 'ign-007',
'name': 'NGK Iridium IX Performance Coils',
'category': 'Electrical',
'brand': 'NGK Spark Plugs',
'part_number': 'NGK-IRIX-COIL-SET',
'price': '$295',
'status': 'In Stock',
'compatibility': 'Toyota Supra, Lexus RC F',
'image': 'parts/ignition-coils.jpg',
'description': 'Premium iridium ignition coil set for enhanced combustion efficiency and reliability.',
'warranty': '1 Year',
'condition': 'New'
},
{
'id': 'hood-008',
'name': 'Seibon Carbon Fiber Vented Hood',
'category': 'Body Parts',
'brand': 'Seibon Carbon',
'part_number': 'SB-CF-HOOD-GTR',
'price': '$1,850',
'status': 'Low Stock',
'compatibility': 'Nissan GT-R R35',
'image': 'parts/carbon-hood.jpg',
'description': 'Lightweight carbon fiber hood with functional heat extraction vents and UV-resistant clear coat.',
'warranty': '1 Year',
'condition': 'New'
},
{
'id': 'seat-009',
'name': 'Recaro Pole Position Racing Seats',
'category': 'Interior',
'brand': 'Recaro',
'part_number': 'REC-POLE-POS-ABE',
'price': '$2,400',
'status': 'In Stock',
'compatibility': 'Universal Fitment',
'image': 'parts/racing-seats.jpg',
'description': 'FIA-approved racing seats with advanced side support and premium Dinamica upholstery.',
'warranty': '2 Years',
'condition': 'New'
},
{
'id': 'oil-010',
'name': 'Mobil 1 Extended Performance 0W-20',
'category': 'Engine Parts',
'brand': 'Mobil 1',
'part_number': 'MOB1-EP-0W20-5Q',
'price': '$85',
'status': 'In Stock',
'compatibility': 'Most Modern Engines',
'image': 'parts/engine-oil.jpg',
'description': 'Full synthetic motor oil providing up to 20,000 miles of protection with superior thermal stability.',
'warranty': 'N/A',
'condition': 'New'
},
{
'id': 'tire-011',
'name': 'Michelin Pilot Sport Cup 2 R',
'category': 'Wheels-Tires',
'brand': 'Michelin',
'part_number': 'MICH-PSC2R-295',
'price': '$1,200',
'status': 'Pre-Order',
'compatibility': 'Performance Vehicles',
'image': 'parts/tires.jpg',
'description': 'Track-focused semi-slick tires with exceptional grip and cornering performance for competitive driving.',
'warranty': '6 Months',
'condition': 'New'
},
{
'id': 'fuel-012',
'name': 'Bosch EV14 High-Flow Injectors',
'category': 'Engine Parts',
'brand': 'Bosch',
'part_number': 'BSH-EV14-1000CC',
'price': '$650',
'status': 'Out of Stock',
'compatibility': 'Mercedes AMG C63',
'image': 'parts/fuel-injectors.jpg',
'description': 'High-flow fuel injectors with precision spray pattern for optimized fuel delivery and performance.',
'warranty': '2 Years',
'condition': 'New'
}
]
return render_template('inventory.html', parts=inventory_parts)
@app.route('/part-details/<part_id>')
def part_details(part_id):
# Log user activity for viewing part details
if current_user.is_authenticated:
log_user_activity(
user_id=current_user.id,
activity_type='part_view',
description=f'Viewed part details for {part_id}',
metadata={'part_id': part_id}
)
# Enhanced car parts inventory data - matches the inventory route data
inventory_parts = [
{
'id': 'turbo-001',
'name': 'Garrett GT2860RS Turbocharger',
'category': 'Engine Parts',
'brand': 'Garrett Motion',
'part_number': 'GTM-2860RS-001',
'price': '$2,850',
'status': 'In Stock',
'compatibility': 'BMW M3, M4, M5',
'image': 'parts/turbocharger.jpg',
'description': 'High-performance ball bearing turbocharger with advanced aerodynamics for maximum efficiency and power output. Features precision-balanced compressor and turbine wheels.',
'warranty': '2 Years',
'condition': 'New',
'specifications': {
'Boost Pressure': '1.5 bar',
'Material': 'Inconel Turbine',
'Weight': '15.2 kg',
'Compressor': '60mm'
},
'features': [
'Advanced ceramic ball bearings',
'Integrated wastegate control',
'Heat-resistant coating',
'Precision-balanced assembly',
'OEM-grade quality'
]
},
{
'id': 'brake-002',
'name': 'Brembo GT Racing Ceramic Pads',
'category': 'Brake System',
'brand': 'Brembo',
'part_number': 'BRM-GTRC-002',
'price': '$485',
'status': 'In Stock',
'compatibility': 'Porsche 911, Cayman',
'image': 'parts/brake-pads.jpg',
'description': 'Premium ceramic brake pads designed for track and street performance with minimal dust production and superior heat dissipation.',
'warranty': '1 Year',
'condition': 'New',
'specifications': {
'Material': 'Carbon Ceramic',
'Operating Temp': '0-800°C',
'Friction Coefficient': '0.42',
'Thickness': '15mm'
},
'features': [
'Low dust formula',
'Excellent heat dissipation',
'Consistent pedal feel',
'Extended pad life',
'Reduced brake fade'
]
},
{
'id': 'susp-003',
'name': 'Bilstein B16 PSS10 Coilovers',
'category': 'Suspension',
'brand': 'Bilstein',
'part_number': 'BIL-B16-PSS10',
'price': '$1,650',
'status': 'Low Stock',
'compatibility': 'Audi A4, A6, S4',
'image': 'parts/coilover.jpg',
'description': 'Motorsport-derived coilover suspension system with 10-way adjustable damping for ultimate handling precision.',
'warranty': '2 Years',
'condition': 'New',
'specifications': {
'Adjustability': '10-way damping',
'Spring Rate': 'Progressive',
'Ride Height': '25-55mm drop',
'Material': 'Aluminum/Steel'