-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1737 lines (1430 loc) · 65.2 KB
/
app.py
File metadata and controls
1737 lines (1430 loc) · 65.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import hmac
import os
import hashlib
import random
from functools import wraps
import string
import secrets
import urllib.parse
from urllib.parse import urlparse
from flask import Flask, render_template, url_for, abort, request, redirect, jsonify, flash, send_from_directory, current_app, g, make_response
import redis
import time
import logging
from datetime import datetime, timezone, timedelta
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
from flask_caching import Cache
from flask_babel import Babel, _
from flask_babel import lazy_gettext as _l
import requests
import settings
import email_tools
import twilio_sms
import bleach
from email_validator import validate_email, EmailNotValidError
def setup_logger():
# Configure the logging system
"""Configure root logging handlers and output format for the web app.
Returns:
None.
"""
logging.basicConfig(level=logging.WARNING, handlers=[]) # Do not add the implicit handler
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
# Create a handler and set the formatter
handler = logging.StreamHandler()
handler.setFormatter(formatter)
# Add the handler to the root logger
logging.getLogger().addHandler(handler)
setup_logger()
import db
app = Flask(__name__)
app.config['SECRET_KEY'] = settings.APP_SEC_KEY
app.config['REMEMBER_COOKIE_DURATION'] = timedelta(days=30) # Example: 30 days
app.config['SESSION_COOKIE_DURATION '] = timedelta(days=5) # Example: 30 days
app.config['BABEL_DEFAULT_LOCALE'] = 'en'
app.config['LANGUAGES'] = ['en', 'es', 'hi', 'zh'] # Supported languages
def normalize_language_code(lang_code):
"""Normalize locale tags (e.g. zh-CN, es-419) to a supported app language.
Args:
lang_code: Raw locale string from route/cookie/browser headers.
Returns:
str: Normalized locale in app.config['LANGUAGES'] or default locale.
"""
default_lang = app.config['BABEL_DEFAULT_LOCALE']
supported_langs = app.config['LANGUAGES']
if not lang_code:
return default_lang
normalized = str(lang_code).strip().lower().replace('_', '-')
if normalized in supported_langs:
return normalized
# Map regional/script variants to base language (e.g. zh-CN -> zh).
base_lang = normalized.split('-', 1)[0]
if base_lang in supported_langs:
return base_lang
return default_lang
def resolve_preferred_language():
"""Resolve language preference using cookie first, then Accept-Language headers.
Returns:
str: One of app.config['LANGUAGES'].
"""
lang_cookie = request.cookies.get('lang', False)
if lang_cookie:
return normalize_language_code(lang_cookie)
# Iterate explicit header preferences to support variants like zh-CN, es-419, hi-IN.
for browser_lang, _quality in request.accept_languages:
mapped_lang = normalize_language_code(browser_lang)
if mapped_lang in app.config['LANGUAGES']:
return mapped_lang
# Keep best_match as a final fallback.
best_match = request.accept_languages.best_match(app.config['LANGUAGES'])
return normalize_language_code(best_match)
def get_locale():
# Extract language from the URL 'lang' parameter
"""Resolve the active UI language from route parameters with fallback to default locale.
Returns:
str: Active locale code.
"""
lang = normalize_language_code(request.view_args.get('lang', app.config['BABEL_DEFAULT_LOCALE']))
logging.warning(f"lang: {lang}")
return lang
def ensure_language(func):
"""Wrap a view to keep language prefix and cookie preference aligned for GET requests.
Args:
func: View function to decorate.
Returns:
callable: Wrapped view function.
"""
def wrapper(*args, **kwargs):
# Skip language redirect logic for POST requests
if request.method == "POST":
return func(*args, **kwargs)
lang = normalize_language_code(kwargs.get('lang', app.config['BABEL_DEFAULT_LOCALE']))
preferred_lang = resolve_preferred_language()
if preferred_lang and preferred_lang != lang:
query_st = request.query_string.decode()
if query_st:
query_st = "?"+query_st
new_path = request.path + query_st
if lang != app.config['BABEL_DEFAULT_LOCALE']:
new_path = new_path.replace(f"/{lang}", "")
if preferred_lang != app.config['BABEL_DEFAULT_LOCALE']:
new_path = f"/{preferred_lang}{new_path}"
logging.warning(f"redirect: {new_path}")
return redirect(new_path or "/")
return func(*args, **kwargs)
wrapper.__name__ = func.__name__ # Required by Flask
return wrapper
@app.before_request
def before_request():
# Set `g.lang` so templates can use the active language
"""Initialize per-request language helpers used by templates before view execution.
Returns:
None.
"""
g.img_lang = ''
if request.view_args:
g.lang = normalize_language_code(request.view_args.get('lang', app.config['BABEL_DEFAULT_LOCALE']))
if g.lang != 'en':
g.img_lang = "_" + g.lang
def get_timezone():
"""Provide timezone information for Flask-Babel from the current request context user.
Returns:
str | None: User timezone if available.
"""
user = getattr(g, 'user', None)
if user is not None:
return user.timezone
babel = Babel(app, locale_selector=get_locale, timezone_selector=get_timezone)
app.config.update(settings.WEB_CACHE_SETT)
cache = Cache(app)
db.cache.init_app(app)
RECAPTCHA_SECRET_KEY = settings.APP_RECAPTCHA_SECRET_KEY
RECAPTCHA_PUBLIC_KEY = settings.RECAPTCHA_PUBLIC_KEY
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
login_manager.login_message = _l("Please log in to access this page.")
redis_client = redis.StrictRedis(
host=settings.REDIS_HOST,
port=settings.REDIS_PORT,
db=settings.WEB_REDIS_DB,
decode_responses=True
)
DOMAIN = settings.APP_DOMAIN
API_URL = settings.API_DOMAIN
RELEASE_VERSION = "1.0.8"
@app.context_processor
def inject_global_variables():
"""Inject global template variables such as API URL, domain, and support pending flag.
Returns:
dict: Values exposed to Jinja templates.
"""
CONTACT_PENDING = False
SITE_LOGO_FILE = os.getenv("SITE_LOGO_FILE", "logos/waterlevel.pro.png")
try:
cache_key = f'users_support'
result = redis_client.get(cache_key)
if result and int(result) > 0:
CONTACT_PENDING = True
except Exception as ex:
logging.exception(ex)
return {
'API_URL': API_URL,
'DOMAIN': DOMAIN,
'RELEASE_VERSION': RELEASE_VERSION,
"CONTACT_PENDING": CONTACT_PENDING,
"SITE_LOGO_FILE": SITE_LOGO_FILE,
"TRACKING_CONFIG": {
"enable_tracking": settings.WLP_ENABLE_TRACKING,
"ga_measurement_id": settings.WLP_GA_MEASUREMENT_ID,
"twitter_pixel_id": settings.WLP_TWITTER_PIXEL_ID,
"enable_adsense": settings.WLP_ENABLE_ADSENSE,
"adsense_client_id": settings.WLP_ADSENSE_CLIENT_ID,
},
}
@app.context_processor
def utility_processor():
"""Expose URL helper functions to templates for locale-aware endpoint generation.
Returns:
dict: Utility functions for Jinja templates.
"""
def url_with_lang(endpoint, **kwargs):
lang = g.get('lang', 'en')
# Do not add a prefix for the default language
if lang == app.config['BABEL_DEFAULT_LOCALE']:
kwargs.pop('lang', None)
return url_for(endpoint, **kwargs)
# Add a prefix for non-default languages
return url_for(endpoint, lang=lang, **kwargs)
return dict(url_with_lang=url_with_lang)
# Load user callback function required by Flask-Login
@login_manager.user_loader
def load_user(user_id):
"""Load a user record for Flask-Login from the persistent store.
Args:
user_id: User identifier from session.
Returns:
db.User | None: Authenticated user model or None.
"""
user_data = db.get_user_by_id(user_id)
if user_data:
return db.User(user_data.id, user_data.email, user_data.passw, user_data.is_admin)
return None
def admin_login_required(func):
"""Restrict access to admin-only views while preserving Flask compatibility behavior.
Args:
func: View function requiring admin access.
Returns:
callable: Wrapped view function enforcing admin checks.
"""
@wraps(func)
def decorated_view(*args, **kwargs):
print("decorated_view decorated_view decorated_view")
if request.method in {"OPTIONS"} or current_app.config.get("LOGIN_DISABLED"):
print("LOGIN DISABLED")
elif not current_user.is_authenticated or not current_user.is_admin:
return login_manager.unauthorized()
else:
print("LOGIN PASS")
# flask 1.x compatibility
# current_app.ensure_sync is only available in Flask >= 2.0
if callable(getattr(current_app, "ensure_sync", None)):
return current_app.ensure_sync(func)(*args, **kwargs)
return func(*args, **kwargs)
return decorated_view
@app.route('/sensor_stats', methods=['GET'])
def sensor_stats():
"""Return hourly aggregated stats (last 24 hours) for a given sensor public key.
Query params:
- public_key: sensor public key or 'demo'
Returns JSON with 24 hourly buckets (oldest first) containing either
`percent` and `voltage` (averages) or `offline: true` when no data.
"""
key = request.args.get('public_key')
if not key:
return jsonify({'error': 'missing public_key'}), 400
if key == 'demo':
key = settings.DEMO_S1_PUB_KEY
history_key = f'tin-history/{key}'
now = int(time.time())
# Align buckets to hour boundaries and include the current hour
# Use the next hour boundary as the end so the 24 buckets cover the
# last 24 one-hour windows including the current hour.
end = (now - (now % 3600)) + 3600
start = end - 24 * 3600
buckets = []
for i in range(24):
bucket_start = start + i * 3600
bucket_end = bucket_start + 3599
try:
items = redis_client.zrangebyscore(history_key, bucket_start, bucket_end)
except Exception:
items = []
if not items:
buckets.append({
'hour_start': bucket_start,
'offline': True
})
continue
# parse items "percent|voltage" (legacy) or
# "percent|voltage|unique_suffix" (current)
percents = []
volts = []
for it in items:
try:
parts = it.split('|')
if len(parts) < 2:
continue
p, v = parts[0], parts[1]
percents.append(float(p))
volts.append(float(v))
except Exception:
continue
# Return integer percent values (no decimals) for frontend charts
avg_percent = int(round(sum(percents) / len(percents))) if percents else None
avg_voltage = round(sum(volts) / len(volts), 2) if volts else None
buckets.append({
'hour_start': bucket_start,
'offline': False,
'percent': avg_percent,
'voltage': avg_voltage
})
return jsonify({'buckets': buckets})
@app.route('/sensor_stats_hour', methods=['GET'])
def sensor_stats_hour():
"""Return raw samples for a single hour bucket for a given sensor.
Query params:
- public_key: sensor public key or 'demo'
- hour_start: epoch seconds for the bucket start
Response: JSON with `samples`: list of { ts, percent, voltage }
"""
key = request.args.get('public_key')
hour_start = request.args.get('hour_start')
if not key or hour_start is None:
return jsonify({'error': 'missing parameters'}), 400
try:
hour_start = int(hour_start)
except Exception:
return jsonify({'error': 'invalid hour_start'}), 400
if key == 'demo':
key = settings.DEMO_S1_PUB_KEY
history_key = f'tin-history/{key}'
bucket_start = hour_start
bucket_end = bucket_start + 3599
try:
items = redis_client.zrangebyscore(history_key, bucket_start, bucket_end, withscores=True)
except Exception:
items = []
samples = []
for member, score in items:
try:
parts = member.split('|')
if len(parts) < 2:
continue
p, v = parts[0], parts[1]
samples.append({
'ts': int(score),
'percent': float(p),
'voltage': float(v)
})
except Exception:
continue
# sort by timestamp ascending
samples.sort(key=lambda x: x['ts'])
return jsonify({'samples': samples})
@app.route('/relay_consumption_stats', methods=['GET'])
def relay_consumption_stats():
"""Return relay daily stats with estimated costs/energy for a selected period.
Query params:
- public_key: relay public key or 'demorelay'
- month: optional YYYY-MM (defaults to current month)
- start_date/end_date: optional YYYY-MM-DD custom range (both required)
"""
key = request.args.get('public_key')
if not key:
return jsonify({'error': 'missing public_key'}), 400
if key == 'demorelay':
key = settings.DEMO_RELAY_PUB_KEY
relay_info = db.DevicesDB.load_device_by_public_key(key)
if not relay_info:
return jsonify({'error': 'invalid public_key'}), 404
if int(relay_info.type) != 3:
return jsonify({'error': 'public_key is not a relay device'}), 400
today = datetime.now(timezone.utc).date()
month_param = (request.args.get('month') or '').strip()
start_date_param = (request.args.get('start_date') or '').strip()
end_date_param = (request.args.get('end_date') or '').strip()
range_mode = 'month'
period_start = None
period_end = None
if start_date_param or end_date_param:
if not start_date_param or not end_date_param:
return jsonify({'error': 'start_date and end_date are both required'}), 400
try:
period_start = datetime.strptime(start_date_param, '%Y-%m-%d').date()
period_end = datetime.strptime(end_date_param, '%Y-%m-%d').date()
except Exception:
return jsonify({'error': 'invalid date format, expected YYYY-MM-DD'}), 400
if period_end < period_start:
return jsonify({'error': 'end_date should be >= start_date'}), 400
if (period_end - period_start).days > 366:
return jsonify({'error': 'date range too large (max 367 days)'}), 400
range_mode = 'custom'
else:
if month_param:
try:
month_dt = datetime.strptime(month_param, '%Y-%m').date()
except Exception:
return jsonify({'error': 'invalid month format, expected YYYY-MM'}), 400
month_start = month_dt.replace(day=1)
else:
month_start = today.replace(day=1)
month_param = month_start.strftime('%Y-%m')
if month_start.month == 12:
next_month_start = month_start.replace(year=month_start.year + 1, month=1)
else:
next_month_start = month_start.replace(month=month_start.month + 1)
month_end = next_month_start - timedelta(days=1)
period_start = month_start
period_end = today if (month_start.year == today.year and month_start.month == today.month) else month_end
supported_currency_codes = {
'USD', 'DOP', 'EUR', 'MXN', 'COP', 'ARS', 'CLP', 'PEN', 'INR', 'CNY'
}
relay_settings = db.DevicesDB.load_device_settings(relay_info.id, 3)
water_cost_per_m3 = float(settings.DEFAULT_WATER_COST_PER_M3)
relay_power_watts = float(settings.DEFAULT_RELAY_POWER_WATTS)
energy_cost_per_kwh = float(settings.DEFAULT_ENERGY_COST_PER_KWH)
currency_code = str(settings.DEFAULT_RELAY_CURRENCY).upper()
if relay_settings:
try:
water_cost_per_m3 = float(relay_settings.get('WATER_COST_PER_M3', water_cost_per_m3) or water_cost_per_m3)
except Exception:
water_cost_per_m3 = float(settings.DEFAULT_WATER_COST_PER_M3)
try:
relay_power_watts = float(relay_settings.get('RELAY_POWER_WATTS', relay_power_watts) or relay_power_watts)
except Exception:
relay_power_watts = float(settings.DEFAULT_RELAY_POWER_WATTS)
try:
energy_cost_per_kwh = float(relay_settings.get('ENERGY_COST_PER_KWH', energy_cost_per_kwh) or energy_cost_per_kwh)
except Exception:
energy_cost_per_kwh = float(settings.DEFAULT_ENERGY_COST_PER_KWH)
try:
currency_candidate = str(relay_settings.get('CURRENCY_CODE', currency_code) or currency_code).strip().upper()
if currency_candidate in supported_currency_codes:
currency_code = currency_candidate
except Exception:
currency_code = str(settings.DEFAULT_RELAY_CURRENCY).upper()
if water_cost_per_m3 <= 0:
water_cost_per_m3 = float(settings.DEFAULT_WATER_COST_PER_M3)
if relay_power_watts <= 0:
relay_power_watts = float(settings.DEFAULT_RELAY_POWER_WATTS)
if energy_cost_per_kwh <= 0:
energy_cost_per_kwh = float(settings.DEFAULT_ENERGY_COST_PER_KWH)
days = db.DevicesDB.get_relay_daily_stats(
relay_info.id,
start_date=period_start,
end_date=period_end
)
enriched_days = []
for item in days:
liters = float(item.get('liters', 0.0) or 0.0)
on_minutes = int(item.get('on_minutes', 0) or 0)
water_m3 = liters / 1000.0
water_cost = water_m3 * water_cost_per_m3
on_hours = on_minutes / 60.0
energy_kwh = (relay_power_watts * on_hours) / 1000.0
energy_cost = energy_kwh * energy_cost_per_kwh
energy_wh = relay_power_watts * on_hours
enriched_days.append({
'day': item.get('day'),
'on_minutes': on_minutes,
'liters': round(liters, 2),
'water_cost': round(water_cost, 4),
'energy_cost': round(energy_cost, 4),
'energy_wh': round(energy_wh, 2)
})
return jsonify({
'days': enriched_days,
'period': {
'mode': range_mode,
'start_date': period_start.strftime('%Y-%m-%d'),
'end_date': period_end.strftime('%Y-%m-%d'),
'month': month_param if range_mode == 'month' else None,
'is_current_month': bool(
range_mode == 'month' and
period_start.year == today.year and
period_start.month == today.month
)
},
'settings': {
'water_cost_per_m3': round(water_cost_per_m3, 4),
'relay_power_watts': round(relay_power_watts, 2),
'energy_cost_per_kwh': round(energy_cost_per_kwh, 4),
'currency_code': currency_code
}
})
def validate_recaptcha(response):
"""Verify a reCAPTCHA token against Google verification endpoint.
Args:
response: reCAPTCHA token submitted by the client.
Returns:
bool: True when verification succeeds.
"""
data = {
'secret': RECAPTCHA_SECRET_KEY,
'response': response
}
response = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data)
result = response.json()
return result['success']
@app.route('/login', methods=['GET', 'POST'], strict_slashes=False)
@app.route('/<lang>/login', methods=['GET', 'POST'], strict_slashes=False)
@ensure_language
def login(lang='en'):
"""Handle user login flow including form validation and session creation.
Args:
lang: Active locale used in localized routes.
Returns:
flask.Response: Rendered page or redirect response.
"""
if request.method == 'POST':
username = request.form['email']
password = request.form['password']
recaptcha_response = request.form['g-recaptcha-response']
remember = request.form.get('remember') == 'on'
# Validate reCAPTCHA response
is_valid_recaptcha = validate_recaptcha(recaptcha_response)
if not is_valid_recaptcha:
# Here you can process the form submission, e.g., send an email
flash(_('Please verify that you are not a robot.'), 'warning')
return render_template('login.html', RECAPTCHA_PUBLIC_KEY=RECAPTCHA_PUBLIC_KEY)
password = hashlib.sha256(password.encode()).hexdigest()
user_data = db.try_login(username, password)
if user_data and user_data.passw == password:
if not user_data.confirmed:
flash(_('Confirm your user email, check inbox or retry register with same email.'), 'warning')
return render_template('login.html', RECAPTCHA_PUBLIC_KEY=RECAPTCHA_PUBLIC_KEY)
user = db.User(user_data.id, user_data.email, user_data.passw, user_data.is_admin)
login_user(user, remember=remember)
return redirect(url_for('devices'))
else:
flash(_('Invalid username or password'), 'warning')
return render_template('login.html', RECAPTCHA_PUBLIC_KEY=RECAPTCHA_PUBLIC_KEY)
@app.route('/register', methods=['GET', 'POST'], strict_slashes=False)
@app.route('/<lang>/register', methods=['GET', 'POST'], strict_slashes=False)
@ensure_language
def register(lang='en'):
"""Handle user registration flow with validation, anti-spam checks, and confirmation email trigger.
Args:
lang: Active locale used in localized routes.
Returns:
flask.Response: Rendered page or redirect response.
"""
if request.method == 'POST':
email = request.form['email']
password = request.form['password']
recaptcha_response = request.form['g-recaptcha-response']
# Validate reCAPTCHA response
is_valid_recaptcha = validate_recaptcha(recaptcha_response)
if not is_valid_recaptcha:
# Here you can process the form submission, e.g., send an email
flash('Invalid reCAPTCHA response', 'warning')
return render_template('register.html', RECAPTCHA_PUBLIC_KEY=RECAPTCHA_PUBLIC_KEY)
try:
# Validate and normalize the email address
valid = validate_email(email)
email = valid.email # Validated and normalized email
except EmailNotValidError as e:
flash('Invalid Email address used.', 'warning')
return render_template('register.html', RECAPTCHA_PUBLIC_KEY=RECAPTCHA_PUBLIC_KEY)
if not db.valid_4register(email):
flash('Email address already in use.', 'warning')
return render_template('register.html', RECAPTCHA_PUBLIC_KEY=RECAPTCHA_PUBLIC_KEY)
password = password.encode()
if not db.add_user(email, hashlib.sha256(password).hexdigest()):
flash('Fails to add user, contact support.', 'warning')
return render_template('register.html', RECAPTCHA_PUBLIC_KEY=RECAPTCHA_PUBLIC_KEY)
email_tools.send_register_email(email, lang=lang)
flash(_('Register email sent, check inbox.'), 'info')
return render_template('after_register.html')
return render_template('register.html', RECAPTCHA_PUBLIC_KEY=RECAPTCHA_PUBLIC_KEY)
@app.route('/user-confirm', methods=['GET'], strict_slashes=False)
@app.route('/<lang>/user-confirm', methods=['GET'], strict_slashes=False)
@ensure_language
def user_confirm(lang='en'):
"""Validate a user confirmation code and activate the account.
Args:
lang: Active locale used in localized routes.
Returns:
flask.Response: Rendered confirmation page or redirect.
"""
email = request.args.get('email')
code = request.args.get('code')
if email and code:
if email_tools.check_confirmation_code(email, code):
db.confirm_user(email)
flash(_('Confirm success!'), 'success')
else:
flash(_('Invalid confirmation code'), 'danger')
return render_template('user-confirm.html')
@app.route('/settings', methods=['GET', 'POST'], strict_slashes=False)
@app.route('/<lang>/settings', methods=['GET', 'POST'], strict_slashes=False)
@ensure_language
@login_required
def user_settings(lang='en'):
"""Display and update authenticated user settings, alerts, and contact preferences.
Args:
lang: Active locale used in localized routes.
Returns:
flask.Response: Rendered settings page or redirect.
"""
if request.method == 'POST':
action = request.form.get("action")
if action == 'update-phone':
phone = request.form.get("phone")
try:
phone = int(phone)
retry_amount = int(redis_client.incr(f"phone/{phone}"))
redis_client.expire(f"phone/{phone}", 86400) # 24 hours expire
if retry_amount > 3:
flash('Verify number retry exceeded, wait 24 hours.', 'danger')
return redirect(url_for('user_settings'))
code = random.randint(100000, 900000)
twilio_sms.send_phone_verify_code(phone, code)
data = f"{settings.APP_SEC_KEY}-{phone}-{code}"
auth_hash = hashlib.sha256(data.encode()).hexdigest()
return render_template('phone_verify.html', auth_hash=auth_hash, phone=phone)
except Exception as ex:
logging.exception(ex)
flash(_('Invalid phone number, use only numbers!'), 'danger')
return redirect(url_for('user_settings'))
elif action == 'verify-phone':
code = request.form.get("code")
phone = int(request.form.get("phone"))
auth_hash = request.form.get("auth_hash")
data = f"{settings.APP_SEC_KEY}-{phone}-{code}"
auth_hash_check = hashlib.sha256(data.encode()).hexdigest()
if auth_hash_check == auth_hash:
current_user.set_phone(phone)
flash('Phone verify success!', 'success')
return redirect(url_for('user_settings'))
else:
code_retry_amount = int(redis_client.incr(f"phone-code/{phone}"))
redis_client.expire(f"phone-code/{phone}", 86400) # 24 hours expire
if code_retry_amount > 10:
flash('Verify code retry exceeded, wait 24 hours!', 'danger')
return redirect(url_for('user_settings'))
flash('Invalid code try again!', 'warning')
return render_template('phone_verify.html', auth_hash=auth_hash, phone=phone)
elif action == "update-alert-settings":
email = request.form.get("email")
sms = request.form.get("sms")
frequency = int(request.form.get("frequency"))
if frequency < 1 or frequency > 48:
flash(_('Invalid frequency value!'), 'danger')
return redirect(url_for('user_settings'))
current_user.set_setting('email-alert', 'on' if email else 'off')
current_user.set_setting('sms-alert', 'on' if sms else 'off')
current_user.set_setting('frequency-alert', frequency)
flash(_('Alert settings update success!'), 'success')
return redirect(url_for('user_settings'))
user = db.get_user_by_id(current_user.get_id())
user_settings = db.User.get_user_settings(current_user.id)
sms_credits = db.User.get_sms_credits(current_user.id)
if request.args.get('return', '') == "smscredits":
flash('Thanks for your purchase, depending on funding sources, it could take some minutes to complete the processing.', 'success')
if request.args.get('return', '') == "cancel":
flash('SMS Credits Buy Canceled','warning')
return render_template('settings.html',
user=user, user_settings=user_settings, sms_credits=sms_credits)
@app.route('/index', strict_slashes=False)
@app.route('/', methods=['GET', 'POST'], strict_slashes=False)
@app.route('/<lang>', methods=['GET', 'POST'], strict_slashes=False)
@ensure_language
def index(lang='en'):
"""Render the localized home page.
Args:
lang: Active locale used in localized routes.
Returns:
flask.Response: Rendered index template.
"""
return render_template('index.html')
def generate_secure_random_string(length=16):
"""Generate a cryptographically secure random alphanumeric string.
Args:
length: Desired number of characters.
Returns:
str: Randomly generated token.
"""
alphabet = string.ascii_letters + string.digits
password = ''
while True:
password = ''.join(secrets.choice(alphabet) for i in range(length))
if (any(c.islower() for c in password)
and any(c.isupper() for c in password)
and sum(c.isdigit() for c in password) >= 3):
break
return password
@app.route('/admin_dashboard', methods=['GET', 'POST'], strict_slashes=False)
@login_required
def admin_dashboard():
"""Render the admin dashboard with users and support summary information.
Returns:
flask.Response: Rendered admin dashboard page.
"""
is_admin = current_user.is_admin
if request.method == 'POST':
action = request.form.get("action")
if action == "add-sms-credits" and is_admin:
user_id = int(request.form.get("user_id"))
credits = float(request.form.get("credits"))
db.User.add_sms_credits(user_id, credits)
flash('Credits added!', category='success')
return render_template('admin_dashboard.html')
if action == 'list-sensor' and is_admin:
return jsonify(db.DevicesDB.get_all_devices_by_type([1, 2]))
if action == 'list-relay' and is_admin:
return jsonify(db.DevicesDB.get_all_devices_by_type(3))
if action == 'list-users' and is_admin:
return jsonify(db.User.get_all_users())
if action == 'list-users-support' and is_admin:
return jsonify(db.Support.get_all_users_support())
if action in ['add-sensor', 'add-relay']:
private_key = request.form.get("private_key")
public_key = request.form.get("public_key")
dev_name = request.form.get("name", '')
recaptcha_response = request.form['g-recaptcha-response']
# Validate reCAPTCHA response
is_valid_recaptcha = validate_recaptcha(recaptcha_response)
if not is_valid_recaptcha:
# Here you can process the form submission, e.g., send an email
flash('Invalid recaptcha!', category='danger')
return redirect(url_for('add_sensor' if action == 'add-sensor' else 'add_relay'))
if not private_key:
private_key = generate_secure_random_string(22)
if not public_key:
public_key = generate_secure_random_string(22)
note = request.form.get("note", '')
stype = int(request.form.get("stype", 1))
device_id = 1 if action == 'add-sensor' else 3
private_key_format = f"{device_id}prv{private_key}"
public_key_format = f"{device_id}pub{public_key}"
if db.DevicesDB.add_device(private_key_format, public_key_format, note, device_id):
flash(
f"Device added <br>public_key: <b>{public_key_format}</b> <br>"
f"private_key: <b>{private_key_format}</b>",
category='success')
current_user.add_device(public_key_format, name=dev_name, can_admin=1)
else:
flash('Fail to add new device!', category='danger')
return redirect(url_for('add_sensor'))
if is_admin:
return render_template('admin_dashboard.html')
else:
return redirect(url_for('user_settings'))
else:
if is_admin:
report_files = os.listdir(settings.REPORTS_FOLDER)
web_report_files = [fl for fl in report_files if 'api' not in fl.lower()]
api_report_files = [fl for fl in report_files if 'api' in fl.lower()]
return render_template('admin_dashboard.html',
web_report_files=web_report_files, api_report_files=api_report_files)
else:
return redirect(url_for('login'))
@app.route('/add_sensor', methods=['GET'], strict_slashes=False)
@login_required
def add_sensor():
"""Create a new sensor device record from admin dashboard inputs.
Returns:
flask.Response: Redirect response back to admin area.
"""
is_admin = current_user.is_admin
return render_template('add_sensor.html', RECAPTCHA_PUBLIC_KEY=RECAPTCHA_PUBLIC_KEY,
is_admin=is_admin)
@app.route('/add_relay', methods=['GET'], strict_slashes=False)
@login_required
def add_relay():
"""Create a new relay device record from admin dashboard inputs.
Returns:
flask.Response: Redirect response back to admin area.
"""
return render_template('add_relay.html', RECAPTCHA_PUBLIC_KEY=RECAPTCHA_PUBLIC_KEY)
def validate_recaptcha(response):
"""Verify a reCAPTCHA token against Google verification endpoint.
Args:
response: reCAPTCHA token submitted by the client.
Returns:
bool: True when verification succeeds.
"""
data = {
'secret': RECAPTCHA_SECRET_KEY,
'response': response
}
response = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data)
result = response.json()
return result['success']
@app.route('/logout', strict_slashes=False)
@app.route('/<lang>/logout', methods=['GET', 'POST'], strict_slashes=False)
@ensure_language
@login_required
def logout(lang='en'):
"""Terminate current user session and redirect to localized login page.
Args:
lang: Active locale used in localized routes.
Returns:
flask.Response: Redirect response.
"""
logout_user()
return redirect(url_for('index'))
def get_relay_event_text(event_code):
"""Convert relay event code to a localized human-readable label.
Args:
event_code: Numeric relay event code.
Returns:
str: Localized event description.
"""
RELAY_EVENTS_CODE = {
0: ("NO_EVENT", _("No event reported")),
1: ("BLIND_AREA", _("Sensor reach near the blind area!")),
2: ("BLIND_AREA_DANGER", _("Sensor reach near the danger blind area!")),
3: ("NOT_FLOW", _("No water inflow detected!")),
4: ("OFFLINE", _("Offline long time detected!")),
5: ("IDDLE_SENSOR", _("Offline sensor detected!")),
6: ("END_LEVEL_EVENT", _("Reach End Level percent!")),
7: ("START_LEVEL_EVENT", _("Reach Start Level percent!")),
8: ("SETUP_WIFI", _("Wifi setup started")),
9: ("BOOT", _("Device boot!")),
10: ("PUMP_ON", _("Pump ON")),
11: ("PUMP_OFF", _("Pump OFF")),
12: ("DATA_POST_FAIL", _("Fail to post data check internet connection")),
13: ("BTN_PRESS", _("WiFi Reset button pressed")),
14: ("SENSOR_FAULT", _("Sensor fault or cable disconnected!"))
}
return RELAY_EVENTS_CODE[event_code][1]
def format_hours(hours):
"""Format uptime hours into a human-readable days/hours string.
Args:
hours: Total uptime in hours.
Returns:
str: Formatted uptime text.
"""
days = hours // 24
remaining_hours = hours % 24
parts = []
if days > 0:
parts.append(f"{days} day{'s' if days != 1 else ''}")
if remaining_hours > 0 or days == 0:
parts.append(f"{remaining_hours} hour{'s' if remaining_hours != 1 else ''}")
return ' and '.join(parts)