-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
3327 lines (2723 loc) · 126 KB
/
Copy pathapp.py
File metadata and controls
3327 lines (2723 loc) · 126 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
"""
Secure Medication Navigator Application
Enhanced with proper security, CSRF protection, and complete admin functionality
"""
from flask import Flask, render_template, request, redirect, url_for, flash, jsonify, session, abort, Blueprint
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
from flask_wtf.csrf import CSRFProtect
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from flask_talisman import Talisman
from flask_mail import Mail, Message
from flask_caching import Cache
from werkzeug.security import generate_password_hash, check_password_hash
from werkzeug.utils import secure_filename
import secrets
from datetime import datetime, timedelta, timezone, time
import os
from functools import wraps
from sqlalchemy import Numeric
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
import atexit
import string
import random
import json
# Utility function for timezone-aware datetime
def utc_now():
return datetime.now(timezone.utc)
from config.secure_config import config
from sms_templates import SMSTemplates
from forms import (
LoginForm, SignupForm, MedicineForm, CategoryForm,
ManufacturerForm, ChangePasswordForm, ProfileForm, ReminderForm,
FamilyMemberForm, CaregiverPermissionForm, EmergencyContactForm,
EnhancedFamilyMemberForm, EnhancedCaregiverPermissionForm,
ForgotPasswordForm, ResetPasswordForm, ForgotPasswordOTPForm,
VerifyOTPForm, ResetPasswordOTPForm
)
# Initialize Flask app
app = Flask(__name__)
# Load configuration
config_name = os.getenv('FLASK_ENV', 'development')
app.config.from_object(config[config_name])
# Enable template auto-reload for development
app.config['TEMPLATES_AUTO_RELOAD'] = True
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0 # Disable caching in development
# Initialize extensions
db = SQLAlchemy(app)
csrf = CSRFProtect(app)
mail = Mail(app)
# Initialize cache with fallback mechanism
def init_cache_with_fallback():
"""Initialize cache with Redis fallback to Simple cache"""
try:
# Try to initialize Redis cache first
import redis
redis_client = redis.Redis(
host='localhost',
port=6379,
decode_responses=True,
socket_connect_timeout=5,
socket_timeout=5
)
# Test Redis connection
redis_client.ping()
# If Redis is available, use Redis cache
app.config.update({
'CACHE_TYPE': 'RedisCache',
'CACHE_REDIS_URL': 'redis://localhost:6379/1',
'CACHE_DEFAULT_TIMEOUT': 300,
'CACHE_KEY_PREFIX': 'mednavigator_'
})
except Exception as e:
# Fall back to Simple cache if Redis is not available
app.config.update({
'CACHE_TYPE': 'SimpleCache',
'CACHE_DEFAULT_TIMEOUT': 300,
'CACHE_THRESHOLD': 1000
})
return Cache(app)
cache = init_cache_with_fallback()
# Initialize services
medicine_service = None
notification_service = None
celery = None
# Security middleware
talisman = Talisman(
app,
force_https=False, # Set to True in production
strict_transport_security=True,
content_security_policy={
'default-src': "'self'",
'script-src': "'self' 'unsafe-inline' cdn.jsdelivr.net cdnjs.cloudflare.com",
'style-src': "'self' 'unsafe-inline' cdn.jsdelivr.net cdnjs.cloudflare.com",
'font-src': "'self' cdnjs.cloudflare.com",
'img-src': "'self' data:",
'connect-src': "'self' cdn.jsdelivr.net cdnjs.cloudflare.com", # Allow source maps
}
)
# Rate limiting with explicit storage configuration
# Configure storage based on environment
storage_uri = "memory://" if config_name == 'development' else os.getenv('REDIS_URL', 'memory://')
limiter = Limiter(
key_func=get_remote_address,
app=app,
default_limits=["1000 per hour"],
storage_uri=storage_uri,
strategy="fixed-window"
)
# Login manager
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'auth.login'
# Email Helper Function
login_manager.login_message = 'Please log in to access this page.'
login_manager.login_message_category = 'info'
# Database Models (keeping existing models but with slight enhancements)
class User(UserMixin, db.Model):
__tablename__ = 'users'
user_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
username = db.Column(db.String(50), unique=True, nullable=False, index=True)
email = db.Column(db.String(100), unique=True, nullable=False, index=True)
password_hash = db.Column(db.String(255), nullable=False)
first_name = db.Column(db.String(50))
last_name = db.Column(db.String(50))
phone_number = db.Column(db.String(20))
date_of_birth = db.Column(db.Date)
# Additional demographic fields
gender = db.Column(db.String(20))
weight = db.Column(db.Float) # in kg
height = db.Column(db.Float) # in cm
# Basic medical information
allergies = db.Column(db.Text) # JSON string or comma-separated
medical_conditions = db.Column(db.Text) # JSON string or comma-separated
# Profile customization
profile_picture = db.Column(db.String(255)) # filename/path
# System fields
is_admin = db.Column(db.Boolean, default=False, nullable=False)
is_active = db.Column(db.Boolean, default=True, nullable=False)
email_verified = db.Column(db.Boolean, default=False, nullable=False)
last_login = db.Column(db.DateTime)
failed_login_attempts = db.Column(db.Integer, default=0)
account_locked_until = db.Column(db.DateTime)
created_at = db.Column(db.DateTime, default=utc_now, nullable=False)
updated_at = db.Column(db.DateTime, default=utc_now, onupdate=utc_now, nullable=False)
# Relationships
medicines = db.relationship('Medicine', backref='user', lazy=True, cascade='all, delete-orphan')
reminders = db.relationship('Reminder', backref='user', lazy=True, cascade='all, delete-orphan')
def get_id(self):
return str(self.user_id)
def set_password(self, password):
self.password_hash = generate_password_hash(password)
def check_password(self, password):
return check_password_hash(self.password_hash, password)
def is_account_locked(self):
if self.account_locked_until:
return datetime.now(timezone.utc) < self.account_locked_until
return False
def lock_account(self, minutes=30):
self.account_locked_until = datetime.now(timezone.utc) + timedelta(minutes=minutes)
self.failed_login_attempts = 0
@property
def full_name(self):
if self.first_name and self.last_name:
return f"{self.first_name} {self.last_name}"
return self.username
class Category(db.Model):
__tablename__ = 'categories'
category_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(100), nullable=False, unique=True, index=True)
description = db.Column(db.Text)
icon = db.Column(db.String(50))
color = db.Column(db.String(7))
is_active = db.Column(db.Boolean, default=True, nullable=False)
created_at = db.Column(db.DateTime, default=utc_now, nullable=False)
updated_at = db.Column(db.DateTime, default=utc_now, onupdate=utc_now, nullable=False)
medicines = db.relationship('Medicine', backref='category', lazy=True)
class Manufacturer(db.Model):
__tablename__ = 'manufacturers'
manufacturer_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(200), nullable=False, unique=True, index=True)
contact_person = db.Column(db.String(100))
email = db.Column(db.String(100))
phone = db.Column(db.String(20))
address = db.Column(db.Text)
website = db.Column(db.String(200))
country = db.Column(db.String(100))
license_number = db.Column(db.String(100))
is_active = db.Column(db.Boolean, default=True, nullable=False)
created_at = db.Column(db.DateTime, default=utc_now, nullable=False)
updated_at = db.Column(db.DateTime, default=utc_now, onupdate=utc_now, nullable=False)
medicines = db.relationship('Medicine', backref='manufacturer', lazy=True)
class Medicine(db.Model):
__tablename__ = 'medicines'
medicine_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(200), nullable=False, index=True)
generic_name = db.Column(db.String(200))
brand_name = db.Column(db.String(200))
dosage_form = db.Column(db.String(50))
strength = db.Column(db.String(50), nullable=False)
price = db.Column(Numeric(10, 2), nullable=False, default=0)
currency = db.Column(db.String(3), default='USD')
# User-focused medicine tracking fields
reason_for_taking = db.Column(db.Text)
color = db.Column(db.String(50))
shape = db.Column(db.String(50))
medicine_image = db.Column(db.String(255)) # Store image filename/path
dosage = db.Column(db.String(100), nullable=False)
frequency = db.Column(db.String(50), nullable=False)
food_instructions = db.Column(db.String(100))
# Schedule and timing
start_date = db.Column(db.Date, nullable=False)
end_date = db.Column(db.Date)
is_ongoing = db.Column(db.Boolean, default=False)
timing_1 = db.Column(db.Time)
timing_2 = db.Column(db.Time)
timing_3 = db.Column(db.Time)
timing_4 = db.Column(db.Time)
# Prescription and refill information
doctor_name = db.Column(db.String(200))
total_quantity = db.Column(db.Integer, nullable=False)
unit_of_measurement = db.Column(db.String(20), nullable=False, default='pieces')
refill_reminder_days = db.Column(db.Integer, default=7)
# Legacy inventory fields (for backward compatibility)
batch_number = db.Column(db.String(100), index=True)
lot_number = db.Column(db.String(100))
stock_quantity = db.Column(db.Integer, default=0, nullable=False)
minimum_stock_level = db.Column(db.Integer, default=5)
manufacture_date = db.Column(db.Date)
expiry_date = db.Column(db.Date, index=True)
purchase_date = db.Column(db.Date)
description = db.Column(db.Text)
usage_instructions = db.Column(db.Text)
side_effects = db.Column(db.Text)
storage_conditions = db.Column(db.String(200))
prescription_required = db.Column(db.Boolean, default=False)
is_active = db.Column(db.Boolean, default=True, nullable=False)
is_controlled_substance = db.Column(db.Boolean, default=False)
category_id = db.Column(db.Integer, db.ForeignKey('categories.category_id'), nullable=False, index=True)
manufacturer_id = db.Column(db.Integer, db.ForeignKey('manufacturers.manufacturer_id'), nullable=False, index=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.user_id'), nullable=False, index=True)
created_at = db.Column(db.DateTime, default=utc_now, nullable=False)
updated_at = db.Column(db.DateTime, default=utc_now, onupdate=utc_now, nullable=False)
reminders = db.relationship('Reminder', backref='medicine', lazy=True, cascade='all, delete-orphan')
# Add database columns for status tracking
is_expired = db.Column(db.Boolean, default=False, nullable=False, index=True)
is_low_stock = db.Column(db.Boolean, default=False, nullable=False, index=True)
@property
def days_to_expiry(self):
if self.expiry_date:
return (self.expiry_date - datetime.now().date()).days
return None
@property
def days_to_end(self):
if self.end_date:
return (self.end_date - datetime.now().date()).days
return None
@property
def is_near_expiry(self):
"""Check if medicine is near expiry (within 30 days) but not expired"""
if self.expiry_date:
days = self.days_to_expiry
return days is not None and 0 <= days <= 30
return False
@property
def is_treatment_ended(self):
"""Check if treatment has ended"""
if self.end_date:
return self.end_date < datetime.now().date()
return False
@property
def needs_refill(self):
"""Check if medicine needs refill based on remaining quantity"""
if self.total_quantity and self.refill_reminder_days:
return self.total_quantity <= self.refill_reminder_days
return False
# Template properties for easier access in templates
@property
def treatment_ended(self):
return self.is_treatment_ended
@property
def refill_needed(self):
return self.needs_refill
@property
def status(self):
if self.is_treatment_ended:
return 'treatment_ended'
elif self.expiry_date and self.is_expired:
return 'expired'
elif self.is_near_expiry:
return 'near_expiry'
elif self.needs_refill:
return 'refill_needed'
elif self.is_low_stock:
return 'low_stock'
else:
return 'active'
def update_status(self):
"""Update medicine status based on current date and stock levels"""
# Update expiry status
if self.expiry_date:
self.is_expired = self.expiry_date < datetime.now().date()
else:
self.is_expired = False
# Update low stock status
self.is_low_stock = self.stock_quantity <= self.minimum_stock_level
return self
class Reminder(db.Model):
__tablename__ = 'reminders'
reminder_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
title = db.Column(db.String(200), nullable=False)
description = db.Column(db.Text)
reminder_type = db.Column(db.String(50), nullable=False)
reminder_date = db.Column(db.DateTime, nullable=False, index=True)
is_recurring = db.Column(db.Boolean, default=False)
recurrence_pattern = db.Column(db.String(50))
is_completed = db.Column(db.Boolean, default=False)
is_active = db.Column(db.Boolean, default=True, nullable=False)
email_notification = db.Column(db.Boolean, default=True)
sms_notification = db.Column(db.Boolean, default=False)
push_notification = db.Column(db.Boolean, default=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.user_id'), nullable=False, index=True)
medicine_id = db.Column(db.Integer, db.ForeignKey('medicines.medicine_id'), index=True)
created_at = db.Column(db.DateTime, default=utc_now, nullable=False)
updated_at = db.Column(db.DateTime, default=utc_now, onupdate=utc_now, nullable=False)
class AuditLog(db.Model):
__tablename__ = 'audit_logs'
log_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.user_id'), index=True)
action = db.Column(db.String(100), nullable=False, index=True)
table_name = db.Column(db.String(50), nullable=False)
record_id = db.Column(db.Integer)
old_values = db.Column(db.JSON)
new_values = db.Column(db.JSON)
ip_address = db.Column(db.String(45))
user_agent = db.Column(db.String(500))
timestamp = db.Column(db.DateTime, default=utc_now, nullable=False, index=True)
# Relationships
user = db.relationship('User', backref='audit_logs')
# Enhanced User Profile Models for Multi-user Support
class UserProfile(db.Model):
"""Extended user profile with demographics and medical information"""
__tablename__ = 'user_profiles'
profile_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.user_id'), nullable=False, unique=True)
# Demographics
gender = db.Column(db.String(20))
weight = db.Column(db.Float) # in kg
height = db.Column(db.Float) # in cm
blood_type = db.Column(db.String(5))
# Medical Information
allergies = db.Column(db.Text) # JSON string of allergies
medical_conditions = db.Column(db.Text) # JSON string of conditions
medications_allergic_to = db.Column(db.Text) # JSON string
medical_notes = db.Column(db.Text)
# Profile customization
profile_picture = db.Column(db.String(255)) # filename/path
theme_preference = db.Column(db.String(20), default='light')
timezone = db.Column(db.String(50), default='UTC')
language = db.Column(db.String(10), default='en')
# Privacy settings
profile_visibility = db.Column(db.String(20), default='private') # private, family, public
share_medical_info = db.Column(db.Boolean, default=False)
created_at = db.Column(db.DateTime, default=utc_now, nullable=False)
updated_at = db.Column(db.DateTime, default=utc_now, onupdate=utc_now, nullable=False)
# Relationships
user = db.relationship('User', backref=db.backref('profile', uselist=False, cascade='all, delete-orphan'))
class FamilyMember(db.Model):
"""Family members and dependents managed by primary user"""
__tablename__ = 'family_members'
member_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
primary_user_id = db.Column(db.Integer, db.ForeignKey('users.user_id'), nullable=False, index=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.user_id'), nullable=True, index=True) # If they have own account
# Basic Info
first_name = db.Column(db.String(50), nullable=False)
last_name = db.Column(db.String(50), nullable=False)
email = db.Column(db.String(100))
phone_number = db.Column(db.String(20))
date_of_birth = db.Column(db.Date)
# Relationship
relationship_type = db.Column(db.String(30), nullable=False) # child, spouse, parent, dependent, other
relationship_notes = db.Column(db.Text)
# Demographics (similar to UserProfile)
gender = db.Column(db.String(20))
weight = db.Column(db.Float)
height = db.Column(db.Float)
blood_type = db.Column(db.String(5))
# Medical Information
allergies = db.Column(db.Text)
medical_conditions = db.Column(db.Text)
medications_allergic_to = db.Column(db.Text)
medical_notes = db.Column(db.Text)
# Status
is_active = db.Column(db.Boolean, default=True, nullable=False)
needs_supervision = db.Column(db.Boolean, default=False) # For children/dependents
# Profile picture
profile_picture = db.Column(db.String(255))
created_at = db.Column(db.DateTime, default=utc_now, nullable=False)
updated_at = db.Column(db.DateTime, default=utc_now, onupdate=utc_now, nullable=False)
# Relationships
primary_user = db.relationship('User', foreign_keys=[primary_user_id], backref='family_members')
linked_user = db.relationship('User', foreign_keys=[user_id], backref='linked_family_member', uselist=False)
@property
def full_name(self):
return f"{self.first_name} {self.last_name}"
@property
def age(self):
if self.date_of_birth:
today = datetime.now().date()
return today.year - self.date_of_birth.year - ((today.month, today.day) < (self.date_of_birth.month, self.date_of_birth.day))
return None
class EmergencyContact(db.Model):
"""Emergency contacts for users and family members"""
__tablename__ = 'emergency_contacts'
contact_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.user_id'), nullable=True, index=True)
family_member_id = db.Column(db.Integer, db.ForeignKey('family_members.member_id'), nullable=True, index=True)
# Contact Information
name = db.Column(db.String(100), nullable=False)
relationship = db.Column(db.String(50), nullable=False)
primary_phone = db.Column(db.String(20), nullable=False)
secondary_phone = db.Column(db.String(20))
email = db.Column(db.String(100))
address = db.Column(db.Text)
# Priority and availability
priority_order = db.Column(db.Integer, default=1) # 1 = primary, 2 = secondary, etc.
is_medical_contact = db.Column(db.Boolean, default=False) # Doctor, hospital, etc.
availability_notes = db.Column(db.Text)
# Status
is_active = db.Column(db.Boolean, default=True, nullable=False)
verified = db.Column(db.Boolean, default=False)
created_at = db.Column(db.DateTime, default=utc_now, nullable=False)
updated_at = db.Column(db.DateTime, default=utc_now, onupdate=utc_now, nullable=False)
# Relationships
user = db.relationship('User', backref='emergency_contacts')
family_member = db.relationship('FamilyMember', backref='emergency_contacts')
class CaregiverPermission(db.Model):
"""Caregiver access permissions for family management"""
__tablename__ = 'caregiver_permissions'
permission_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
grantor_user_id = db.Column(db.Integer, db.ForeignKey('users.user_id'), nullable=False, index=True) # Who grants access
caregiver_user_id = db.Column(db.Integer, db.ForeignKey('users.user_id'), nullable=False, index=True) # Who gets access
family_member_id = db.Column(db.Integer, db.ForeignKey('family_members.member_id'), nullable=True, index=True) # For specific family member
# Permission levels
can_view_medicines = db.Column(db.Boolean, default=False)
can_manage_medicines = db.Column(db.Boolean, default=False)
can_view_reminders = db.Column(db.Boolean, default=False)
can_manage_reminders = db.Column(db.Boolean, default=False)
can_view_medical_info = db.Column(db.Boolean, default=False)
can_manage_profile = db.Column(db.Boolean, default=False)
can_view_emergency_contacts = db.Column(db.Boolean, default=False)
can_manage_emergency_contacts = db.Column(db.Boolean, default=False)
# Time-based access
access_start_date = db.Column(db.Date)
access_end_date = db.Column(db.Date)
# Status and notes
is_active = db.Column(db.Boolean, default=True, nullable=False)
notes = db.Column(db.Text)
created_at = db.Column(db.DateTime, default=utc_now, nullable=False)
updated_at = db.Column(db.DateTime, default=utc_now, onupdate=utc_now, nullable=False)
# Relationships
grantor = db.relationship('User', foreign_keys=[grantor_user_id], backref='granted_permissions')
caregiver = db.relationship('User', foreign_keys=[caregiver_user_id], backref='caregiver_permissions')
family_member = db.relationship('FamilyMember', backref='caregiver_permissions')
# Constraints to prevent self-permissions
__table_args__ = (
db.CheckConstraint('grantor_user_id != caregiver_user_id', name='no_self_permission'),
)
class PasswordResetToken(db.Model):
"""Model for storing password reset tokens and OTP codes"""
__tablename__ = 'password_reset_tokens'
token_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.user_id'), nullable=False, index=True)
# Token details
reset_token = db.Column(db.String(255), unique=True, index=True) # For email reset links
otp_code = db.Column(db.String(6), index=True) # For OTP verification
token_type = db.Column(db.String(20), nullable=False) # 'email_link' or 'otp'
# Security and tracking
ip_address = db.Column(db.String(45))
user_agent = db.Column(db.String(500))
# Status and expiry
is_used = db.Column(db.Boolean, default=False, nullable=False)
expires_at = db.Column(db.DateTime, nullable=False, index=True)
used_at = db.Column(db.DateTime)
created_at = db.Column(db.DateTime, default=utc_now, nullable=False)
# Relationships
user = db.relationship('User', backref='reset_tokens')
def is_expired(self):
"""Check if token is expired"""
return datetime.now(timezone.utc) > self.expires_at.replace(tzinfo=timezone.utc)
def is_valid(self):
"""Check if token is valid (not used and not expired)"""
return not self.is_used and not self.is_expired()
@staticmethod
def generate_otp():
"""Generate a 6-digit OTP code"""
return ''.join([str(random.randint(0, 9)) for _ in range(6)])
@staticmethod
def generate_reset_token():
"""Generate a secure reset token"""
return secrets.token_urlsafe(64)
@login_manager.user_loader
def load_user(user_id):
return db.session.get(User, int(user_id))
# Notification Services
class NotificationService:
"""Enhanced notification service with multiple channels"""
@staticmethod
def send_email_notification(user, subject, template_name, context=None, plain_template=None):
"""Send HTML email notification with template"""
try:
if context is None:
context = {}
# Add common context variables
context.update({
'user': user,
'now': datetime.now().date(),
'url_for': url_for
})
# Handle URL generation for email templates
with app.test_request_context():
# Render HTML template
html_body = render_template(f'emails/{template_name}.html', **context)
# Render plain text template if provided
text_body = None
if plain_template:
text_body = render_template(f'emails/{plain_template}.txt', **context)
msg = Message(
subject=subject,
recipients=[user.email],
html=html_body,
body=text_body
)
mail.send(msg)
app.logger.info(f"Email notification sent to {user.email}: {subject}")
return True
except Exception as e:
app.logger.error(f"Failed to send email notification: {e}")
return False
@staticmethod
def send_reminder_notification(user, reminder, medicine=None):
"""Send reminder notification via email and SMS"""
try:
subject = f"Medication Reminder: {reminder.title}"
context = {
'reminder': reminder,
'medicine': medicine
}
notifications_sent = []
# Send email notification if enabled
if reminder.email_notification and user.email:
email_sent = NotificationService.send_email_notification(
user, subject, 'reminder_notification', context, 'reminder_notification'
)
if email_sent:
notifications_sent.append('email')
# Send SMS notification if enabled
if reminder.sms_notification and user.phone_number:
sms_sent = NotificationService.send_sms_notification(user, reminder, medicine)
if sms_sent:
notifications_sent.append('sms')
app.logger.info(f"Reminder notifications sent via {', '.join(notifications_sent)} for reminder {reminder.reminder_id}")
return len(notifications_sent) > 0
except Exception as e:
app.logger.error(f"Failed to send reminder notifications: {e}")
return False
@staticmethod
def send_sms_notification(user, reminder, medicine=None):
"""Send SMS notification for reminder using templates"""
try:
# Check if SMS is enabled
if not os.getenv('SMS_NOTIFICATIONS_ENABLED', 'False').lower() == 'true':
app.logger.info("SMS notifications are disabled")
return False
# Check if user has phone number
if not user.phone_number:
app.logger.warning(f"User {user.username} has no phone number for SMS")
return False
try:
from twilio.rest import Client
except ImportError:
app.logger.error("Twilio package not installed")
return False
account_sid = os.getenv('TWILIO_ACCOUNT_SID')
auth_token = os.getenv('TWILIO_AUTH_TOKEN')
twilio_phone = os.getenv('TWILIO_PHONE_NUMBER')
if not all([account_sid, auth_token, twilio_phone]):
app.logger.error("Twilio credentials not configured")
return False
client = Client(account_sid, auth_token)
# Use SMS template for message
message_body = SMSTemplates.reminder_notification(user, reminder, medicine)
message = client.messages.create(
body=message_body,
from_=twilio_phone,
to=user.phone_number
)
app.logger.info(f"SMS notification sent to {user.phone_number} for reminder {reminder.reminder_id}")
return True
except Exception as e:
app.logger.error(f"Failed to send SMS notification: {e}")
return False
@staticmethod
def send_welcome_notification(user):
"""Send welcome email to new users"""
try:
subject = "Welcome to Medication Navigator! 🎉"
return NotificationService.send_email_notification(
user, subject, 'welcome', {}, 'welcome'
)
except Exception as e:
app.logger.error(f"Failed to send welcome notification: {e}")
return False
@staticmethod
def send_expiry_alert(user, medicines):
"""Send expiry alert for medicines"""
try:
expired_count = sum(1 for m in medicines if m.is_expired)
expiring_count = len(medicines) - expired_count
if expired_count > 0 and expiring_count > 0:
subject = f"⚠️ {expired_count} Expired & {expiring_count} Expiring Soon"
elif expired_count > 0:
subject = f"🚨 {expired_count} Medicine(s) Expired"
else:
subject = f"📅 {expiring_count} Medicine(s) Expiring Soon"
context = {'medicines': medicines}
return NotificationService.send_email_notification(
user, subject, 'expiry_alert', context, 'expiry_alert'
)
except Exception as e:
app.logger.error(f"Failed to send expiry alert: {e}")
return False
@staticmethod
def send_low_stock_alert(user, medicines):
"""Send low stock alert for medicines"""
try:
subject = f"📦 {len(medicines)} Medicine(s) Running Low"
context = {'medicines': medicines}
return NotificationService.send_email_notification(
user, subject, 'low_stock_digest', context, 'low_stock_digest'
)
except Exception as e:
app.logger.error(f"Failed to send low stock alert: {e}")
return False
@staticmethod
def send_password_change_alert(user):
"""Send password change confirmation"""
try:
subject = "🔐 Password Changed Successfully"
context = {'change_time': datetime.now()}
# Send email notification
email_sent = NotificationService.send_email_notification(
user, subject, 'password_change', context
)
# Send SMS notification if user has phone number
sms_sent = False
if user.phone_number and os.getenv('SMS_NOTIFICATIONS_ENABLED', 'False').lower() == 'true':
sms_sent = NotificationService.send_sms_alert(user, 'password_change')
return email_sent or sms_sent
except Exception as e:
app.logger.error(f"Failed to send password change alert: {e}")
return False
@staticmethod
def send_sms_alert(user, alert_type, data=None):
"""Send various SMS alerts using templates"""
try:
if not os.getenv('SMS_NOTIFICATIONS_ENABLED', 'False').lower() == 'true':
return False
if not user.phone_number:
return False
try:
from twilio.rest import Client
except ImportError:
app.logger.error("Twilio package not installed")
return False
account_sid = os.getenv('TWILIO_ACCOUNT_SID')
auth_token = os.getenv('TWILIO_AUTH_TOKEN')
twilio_phone = os.getenv('TWILIO_PHONE_NUMBER')
if not all([account_sid, auth_token, twilio_phone]):
return False
client = Client(account_sid, auth_token)
# Generate message based on alert type
if alert_type == 'welcome':
message_body = SMSTemplates.welcome_message(user)
elif alert_type == 'password_change':
message_body = SMSTemplates.password_change_alert(user)
elif alert_type == 'expiry' and data:
message_body = SMSTemplates.expiry_alert(user, data)
elif alert_type == 'low_stock' and data:
message_body = SMSTemplates.low_stock_alert(user, data)
elif alert_type == 'medicine_added' and data:
message_body = SMSTemplates.medicine_added_confirmation(user, data)
elif alert_type == 'critical_expiry' and data:
message_body = SMSTemplates.critical_expiry_alert(user, data)
else:
return False
message = client.messages.create(
body=message_body,
from_=twilio_phone,
to=user.phone_number
)
app.logger.info(f"SMS alert '{alert_type}' sent to {user.phone_number}")
return True
except Exception as e:
app.logger.error(f"Failed to send SMS alert '{alert_type}': {e}")
return False
@staticmethod
def send_password_reset_email(user, reset_url):
"""Send password reset link via email"""
try:
subject = "🔐 Password Reset Request"
context = {
'reset_url': reset_url,
'expiry_hours': 1
}
return NotificationService.send_email_notification(
user, subject, 'password_reset', context, 'password_reset'
)
except Exception as e:
app.logger.error(f"Failed to send password reset email to {user.email}: {e}")
return False
class ReminderScheduler:
"""Enhanced reminder scheduling service"""
@staticmethod
def check_due_reminders():
"""Check for due reminders and send notifications"""
with app.app_context():
try:
now = datetime.now()
# Get reminders due in the next minute
due_reminders = Reminder.query.filter(
Reminder.is_active == True,
Reminder.is_completed == False,
Reminder.reminder_date <= now,
Reminder.reminder_date >= now - timedelta(minutes=1)
).all()
notifications_sent = 0
for reminder in due_reminders:
user = reminder.user
medicine = reminder.medicine if reminder.medicine_id else None
# Send notifications using enhanced service
if NotificationService.send_reminder_notification(user, reminder, medicine):
notifications_sent += 1
# Mark as completed if not recurring
if not reminder.is_recurring:
reminder.is_completed = True
else:
# Schedule next occurrence for recurring reminders
ReminderScheduler.schedule_next_occurrence(reminder)
# Log the action
log_action('REMINDER_SENT', 'reminders', reminder.reminder_id)
if due_reminders:
db.session.commit()
app.logger.info(f"Processed {len(due_reminders)} due reminders, sent {notifications_sent} notifications")
except Exception as e:
app.logger.error(f"Error checking due reminders: {e}")
db.session.rollback()
@staticmethod
def schedule_next_occurrence(reminder):
"""Schedule next occurrence for recurring reminders"""
try:
if not reminder.is_recurring or not reminder.recurrence_pattern:
return
current_date = reminder.reminder_date
if reminder.recurrence_pattern == 'daily':
next_date = current_date + timedelta(days=1)
elif reminder.recurrence_pattern == 'weekly':
next_date = current_date + timedelta(weeks=1)
elif reminder.recurrence_pattern == 'monthly':
# Add one month (approximate)
next_date = current_date + timedelta(days=30)
else:
return
reminder.reminder_date = next_date
app.logger.info(f"Scheduled next occurrence for reminder {reminder.reminder_id} at {next_date}")
except Exception as e:
app.logger.error(f"Error scheduling next occurrence for reminder {reminder.reminder_id}: {e}")
@staticmethod
def send_daily_expiry_alerts():
"""Send daily expiry alerts to users"""
with app.app_context():
try:
now = datetime.now().date()
# Get all users
users = User.query.filter_by(is_active=True).all()
alerts_sent = 0
for user in users:
# Get user's expired and expiring medicines
user_medicines = Medicine.query.filter_by(user_id=user.user_id)
expiring_medicines = user_medicines.filter(
db.or_(
Medicine.is_expired == True,
db.and_(
Medicine.expiry_date <= now + timedelta(days=7),
Medicine.expiry_date > now
)
)
).all()
if expiring_medicines:
if NotificationService.send_expiry_alert(user, expiring_medicines):
alerts_sent += 1
app.logger.info(f"Sent daily expiry alerts to {alerts_sent} users")
except Exception as e: