-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathauth_routes.py
More file actions
799 lines (676 loc) · 24.3 KB
/
auth_routes.py
File metadata and controls
799 lines (676 loc) · 24.3 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
"""
Authentication Routes - Multi-method Authentication for Farmers
Handles: Registration, Login, Profile Management
Supports: Passkey (biometric) and PIN-based authentication
"""
from flask import Blueprint, request, jsonify
import psycopg2
import os
from datetime import datetime
from dotenv import load_dotenv
import hashlib
import bcrypt
load_dotenv('.env')
auth_bp = Blueprint('auth', __name__, url_prefix='/api/auth')
# Database connection helper
def get_db_connection():
return psycopg2.connect(
host=os.getenv('PGHOST'),
port=os.getenv('PGPORT'),
database=os.getenv('PGDATABASE'),
user=os.getenv('PGUSER'),
password=os.getenv('PGPASSWORD')
)
# Generate deterministic wallet address from passkey credential
def generate_wallet_address(credential_id: str) -> str:
"""
Generate deterministic wallet address from Passkey credential ID
Uses Ethereum address format (0x + 40 hex chars)
"""
# Hash credential_id to create deterministic address
hash_result = hashlib.sha256(f"aquamind_wallet_{credential_id}".encode()).hexdigest()
# Take first 40 chars and format as Ethereum address
return f"0x{hash_result[:40]}"
@auth_bp.route('/register-passkey', methods=['POST'])
def register_passkey():
"""
Register new user with Passkey
Request body:
{
"full_name": "Nguyen Van A",
"phone": "0912345678",
"email": "optional@email.com",
"farm_name": "Nong trai Van A",
"farm_location_lat": 10.762622,
"farm_location_lon": 106.660172,
"farm_area_hectares": 2.5,
"current_crop": "coffee",
"passkey_credential_id": "ABC123...",
"passkey_public_key": "MII...",
"passkey_transports": ["internal", "hybrid"]
}
Returns:
{
"success": true,
"user_id": 1,
"wallet_address": "0x...",
"message": "Đăng ký thành công!"
}
"""
try:
data = request.json
# Validate required fields
required = ['full_name', 'phone', 'passkey_credential_id', 'passkey_public_key']
for field in required:
if not data.get(field):
return jsonify({
'success': False,
'error': f'Thiếu trường bắt buộc: {field}'
}), 400
# Generate wallet address from passkey credential
wallet_address = generate_wallet_address(data['passkey_credential_id'])
conn = get_db_connection()
cur = conn.cursor()
# Check if phone already exists
cur.execute("SELECT id FROM users WHERE phone = %s", (data['phone'],))
existing = cur.fetchone()
if existing:
cur.close()
conn.close()
return jsonify({
'success': False,
'error': 'Số điện thoại đã được đăng ký'
}), 400
# Check if passkey credential already exists
cur.execute(
"SELECT id FROM users WHERE passkey_credential_id = %s",
(data['passkey_credential_id'],)
)
existing_passkey = cur.fetchone()
if existing_passkey:
cur.close()
conn.close()
return jsonify({
'success': False,
'error': 'Passkey này đã được đăng ký'
}), 400
# Insert new user
insert_query = """
INSERT INTO users (
full_name, phone, email,
passkey_credential_id, passkey_public_key, passkey_counter, passkey_transports,
passkey_created_at_vn,
wallet_address, wallet_created_at_vn,
farm_name, farm_location_lat, farm_location_lon, farm_area_hectares, current_crop,
is_active, created_at_vn, updated_at_vn, last_login_at_vn
) VALUES (
%s, %s, %s,
%s, %s, %s, %s,
NOW() AT TIME ZONE 'Asia/Ho_Chi_Minh',
%s, NOW() AT TIME ZONE 'Asia/Ho_Chi_Minh',
%s, %s, %s, %s, %s,
TRUE, NOW() AT TIME ZONE 'Asia/Ho_Chi_Minh', NOW() AT TIME ZONE 'Asia/Ho_Chi_Minh', NOW() AT TIME ZONE 'Asia/Ho_Chi_Minh'
)
RETURNING id, wallet_address
"""
cur.execute(insert_query, (
data['full_name'],
data['phone'],
data.get('email'),
data['passkey_credential_id'],
data['passkey_public_key'],
0, # Initial counter
data.get('passkey_transports', []),
wallet_address,
data.get('farm_name'),
data.get('farm_location_lat'),
data.get('farm_location_lon'),
data.get('farm_area_hectares'),
data.get('current_crop')
))
user_id, wallet_addr = cur.fetchone()
conn.commit()
cur.close()
conn.close()
print(f"✅ New user registered: {data['full_name']} (ID: {user_id}, Wallet: {wallet_addr})")
return jsonify({
'success': True,
'user_id': user_id,
'wallet_address': wallet_addr,
'message': f'Đăng ký thành công! Ví của bạn: {wallet_addr}'
}), 201
except Exception as e:
print(f"❌ Registration error: {e}")
return jsonify({
'success': False,
'error': str(e)
}), 500
@auth_bp.route('/login-passkey', methods=['POST'])
def login_passkey():
"""
Login with Passkey
Request body:
{
"passkey_credential_id": "ABC123..."
}
Returns:
{
"success": true,
"user": {
"id": 1,
"full_name": "Nguyen Van A",
"phone": "0912345678",
"wallet_address": "0x...",
"farm_name": "Nong trai Van A",
"current_crop": "coffee",
...
}
}
"""
try:
data = request.json
credential_id = data.get('passkey_credential_id')
if not credential_id:
return jsonify({
'success': False,
'error': 'Thiếu passkey_credential_id'
}), 400
conn = get_db_connection()
cur = conn.cursor()
# Find user by credential_id
cur.execute("""
SELECT
id, full_name, phone, email,
wallet_address,
farm_name, farm_location_lat, farm_location_lon, farm_area_hectares, current_crop,
passkey_counter,
is_active
FROM users
WHERE passkey_credential_id = %s
""", (credential_id,))
user_row = cur.fetchone()
if not user_row:
cur.close()
conn.close()
return jsonify({
'success': False,
'error': 'Không tìm thấy tài khoản với Passkey này'
}), 404
# Check if active
if not user_row[11]: # is_active
cur.close()
conn.close()
return jsonify({
'success': False,
'error': 'Tài khoản đã bị vô hiệu hóa'
}), 403
# Update last login and counter
new_counter = user_row[10] + 1
cur.execute("""
UPDATE users
SET last_login_at_vn = NOW() AT TIME ZONE 'Asia/Ho_Chi_Minh',
passkey_last_used_at_vn = NOW() AT TIME ZONE 'Asia/Ho_Chi_Minh',
passkey_counter = %s,
updated_at_vn = NOW() AT TIME ZONE 'Asia/Ho_Chi_Minh'
WHERE id = %s
""", (new_counter, user_row[0]))
conn.commit()
cur.close()
conn.close()
# Build user object
user = {
'id': user_row[0],
'full_name': user_row[1],
'phone': user_row[2],
'email': user_row[3],
'wallet_address': user_row[4],
'farm_name': user_row[5],
'farm_location_lat': user_row[6],
'farm_location_lon': user_row[7],
'farm_area_hectares': user_row[8],
'current_crop': user_row[9],
}
print(f"✅ User logged in: {user['full_name']} (ID: {user['id']})")
return jsonify({
'success': True,
'user': user,
'message': f'Chào mừng {user["full_name"]}!'
}), 200
except Exception as e:
print(f"❌ Login error: {e}")
return jsonify({
'success': False,
'error': str(e)
}), 500
@auth_bp.route('/profile/<int:user_id>', methods=['GET'])
def get_profile(user_id):
"""Get user profile by ID"""
try:
conn = get_db_connection()
cur = conn.cursor()
cur.execute("""
SELECT
id, full_name, phone, email,
wallet_address, wallet_created_at_vn,
farm_name, farm_location_lat, farm_location_lon, farm_area_hectares, current_crop,
created_at_vn, last_login_at_vn
FROM users
WHERE id = %s AND is_active = TRUE
""", (user_id,))
row = cur.fetchone()
cur.close()
conn.close()
if not row:
return jsonify({
'success': False,
'error': 'Không tìm thấy người dùng'
}), 404
user = {
'id': row[0],
'full_name': row[1],
'phone': row[2],
'email': row[3],
'wallet_address': row[4],
'wallet_created_at': row[5].isoformat() if row[5] else None,
'farm_name': row[6],
'farm_location_lat': row[7],
'farm_location_lon': row[8],
'farm_area_hectares': row[9],
'current_crop': row[10],
'created_at': row[11].isoformat() if row[11] else None,
'last_login_at': row[12].isoformat() if row[12] else None,
}
return jsonify({
'success': True,
'user': user
}), 200
except Exception as e:
print(f"❌ Get profile error: {e}")
return jsonify({
'success': False,
'error': str(e)
}), 500
@auth_bp.route('/profile/<int:user_id>', methods=['PUT'])
def update_profile(user_id):
"""Update user profile"""
try:
data = request.json
conn = get_db_connection()
cur = conn.cursor()
# Build update query dynamically
allowed_fields = ['full_name', 'email', 'farm_name', 'farm_location_lat',
'farm_location_lon', 'farm_area_hectares', 'current_crop']
updates = []
values = []
for field in allowed_fields:
if field in data:
updates.append(f"{field} = %s")
values.append(data[field])
if not updates:
return jsonify({
'success': False,
'error': 'Không có trường nào để cập nhật'
}), 400
# Add updated_at
updates.append("updated_at_vn = NOW() AT TIME ZONE 'Asia/Ho_Chi_Minh'")
values.append(user_id)
query = f"UPDATE users SET {', '.join(updates)} WHERE id = %s AND is_active = TRUE RETURNING id"
cur.execute(query, values)
result = cur.fetchone()
if not result:
cur.close()
conn.close()
return jsonify({
'success': False,
'error': 'Không tìm thấy người dùng'
}), 404
conn.commit()
cur.close()
conn.close()
print(f"✅ User profile updated: ID {user_id}")
return jsonify({
'success': True,
'message': 'Cập nhật thông tin thành công!'
}), 200
except Exception as e:
print(f"❌ Update profile error: {e}")
return jsonify({
'success': False,
'error': str(e)
}), 500
# ====== PIN-based Authentication Routes ======
@auth_bp.route('/register-pin', methods=['POST'])
def register_pin():
"""
Register new user with PIN
Request body:
{
"full_name": "Nguyen Van A",
"email": "user@example.com",
"pin": "1234",
"phone": "0912345678",
"farm_name": "Nong trai Van A",
"farm_area_hectares": 2.5,
"current_crop": "coffee",
"wallet_address": "0x..."
}
Returns:
{
"success": true,
"user_id": 1,
"wallet_address": "0x...",
"message": "Đăng ký thành công!"
}
"""
try:
data = request.json
# Validate required fields
required = ['full_name', 'email', 'pin']
for field in required:
if not data.get(field):
return jsonify({
'success': False,
'error': f'Thiếu trường bắt buộc: {field}'
}), 400
# Validate PIN length
pin = data['pin']
if len(pin) < 4 or len(pin) > 6:
return jsonify({
'success': False,
'error': 'Mã PIN phải có 4-6 số'
}), 400
# Generate wallet address from email if not provided
wallet_address = data.get('wallet_address') or generate_wallet_address(data['email'])
# Hash PIN
pin_hash = bcrypt.hashpw(pin.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
conn = get_db_connection()
cur = conn.cursor()
# Check if email already exists
cur.execute("SELECT id FROM users WHERE email = %s", (data['email'],))
existing = cur.fetchone()
if existing:
cur.close()
conn.close()
return jsonify({
'success': False,
'error': 'Email đã được đăng ký'
}), 400
# Insert new user with PIN
insert_query = """
INSERT INTO users (
full_name, email, phone,
pin_hash,
wallet_address, wallet_created_at_vn,
farm_name, farm_area_hectares, current_crop,
is_active, created_at_vn, updated_at_vn, last_login_at_vn
) VALUES (
%s, %s, %s,
%s,
%s, NOW() AT TIME ZONE 'Asia/Ho_Chi_Minh',
%s, %s, %s,
TRUE, NOW() AT TIME ZONE 'Asia/Ho_Chi_Minh', NOW() AT TIME ZONE 'Asia/Ho_Chi_Minh', NOW() AT TIME ZONE 'Asia/Ho_Chi_Minh'
)
RETURNING id, wallet_address
"""
cur.execute(insert_query, (
data['full_name'],
data['email'],
data.get('phone'),
pin_hash,
wallet_address,
data.get('farm_name'),
data.get('farm_area_hectares'),
data.get('current_crop')
))
user_id, wallet_addr = cur.fetchone()
conn.commit()
cur.close()
conn.close()
print(f"✅ New user registered with PIN: {data['full_name']} (ID: {user_id}, Wallet: {wallet_addr})")
return jsonify({
'success': True,
'user_id': user_id,
'wallet_address': wallet_addr,
'message': f'Đăng ký thành công! Ví của bạn: {wallet_addr}'
}), 201
except Exception as e:
print(f"❌ PIN Registration error: {e}")
return jsonify({
'success': False,
'error': str(e)
}), 500
@auth_bp.route('/login-pin', methods=['POST'])
def login_pin():
"""
Login with PIN (accepts email or phone)
Request body:
{
"email_or_phone": "user@example.com hoặc 0912345678",
"pin": "1234"
}
Returns:
{
"success": true,
"user": {
"id": 1,
"full_name": "Nguyen Van A",
"phone": "0912345678",
"wallet_address": "0x...",
...
}
}
"""
try:
data = request.json
email_or_phone = data.get('email_or_phone')
pin = data.get('pin')
if not email_or_phone or not pin:
return jsonify({
'success': False,
'error': 'Thiếu email/số điện thoại hoặc mã PIN'
}), 400
conn = get_db_connection()
cur = conn.cursor()
# Find user by email OR phone
cur.execute("""
SELECT
id, full_name, phone, email,
wallet_address,
farm_name, farm_location_lat, farm_location_lon, farm_area_hectares, current_crop,
pin_hash,
is_active
FROM users
WHERE email = %s OR phone = %s
""", (email_or_phone, email_or_phone))
user_row = cur.fetchone()
if not user_row:
cur.close()
conn.close()
return jsonify({
'success': False,
'error': 'Không tìm thấy tài khoản với email/số điện thoại này'
}), 404
# Check if PIN hash exists
pin_hash = user_row[10]
if not pin_hash:
cur.close()
conn.close()
return jsonify({
'success': False,
'error': 'Tài khoản này không sử dụng xác thực PIN'
}), 400
# Verify PIN
if not bcrypt.checkpw(pin.encode('utf-8'), pin_hash.encode('utf-8')):
cur.close()
conn.close()
return jsonify({
'success': False,
'error': 'Mã PIN không đúng'
}), 401
# Check if active
if not user_row[11]: # is_active
cur.close()
conn.close()
return jsonify({
'success': False,
'error': 'Tài khoản đã bị vô hiệu hóa'
}), 403
# Update last login
cur.execute("""
UPDATE users
SET last_login_at_vn = NOW() AT TIME ZONE 'Asia/Ho_Chi_Minh',
updated_at_vn = NOW() AT TIME ZONE 'Asia/Ho_Chi_Minh'
WHERE id = %s
""", (user_row[0],))
conn.commit()
cur.close()
conn.close()
# Build user object
user = {
'id': user_row[0],
'full_name': user_row[1],
'phone': user_row[2],
'email': user_row[3],
'wallet_address': user_row[4],
'farm_name': user_row[5],
'farm_location_lat': user_row[6],
'farm_location_lon': user_row[7],
'farm_area_hectares': user_row[8],
'current_crop': user_row[9],
}
print(f"✅ User logged in with PIN: {user['full_name']} (ID: {user['id']})")
return jsonify({
'success': True,
'user': user,
'message': f'Chào mừng {user["full_name"]}!'
}), 200
except Exception as e:
print(f"❌ PIN Login error: {e}")
return jsonify({
'success': False,
'error': str(e)
}), 500
# ====== Zalo Account Linking ======
@auth_bp.route('/zalo/link-account', methods=['POST'])
def link_zalo_account():
"""
Link Zalo ID with user account using verification token
This endpoint is called after user:
1. Receives Zalo message with linking link (created by n8n)
2. Clicks the link and signs in to web
3. Confirms on web to complete linking
Request body:
{
"token": "abc123xyz...", # Token from zalo_link_sessions table
"user_id": 1 # Currently logged-in user ID (from auth)
}
Response:
{
"success": true,
"message": "Tài khoản Zalo đã được liên kết thành công!",
"zalo_id": "123456789",
"user_id": 1,
"full_name": "Nguyen Van A"
}
"""
try:
data = request.json
token = data.get('token')
user_id = data.get('user_id')
if not token or not user_id:
return jsonify({
'success': False,
'error': 'Missing required fields: token, user_id'
}), 400
conn = get_db_connection()
cur = conn.cursor()
try:
# 1. Verify token exists and get zalo_id from it
cur.execute("""
SELECT id, expires_at, is_used, zalo_id
FROM zalo_link_sessions
WHERE token = %s
""", (token,))
session_row = cur.fetchone()
if not session_row:
cur.close()
conn.close()
return jsonify({
'success': False,
'error': 'Token không hợp lệ hoặc không tồn tại'
}), 404
session_id, expires_at, is_used, zalo_id = session_row
# Check if token already used
if is_used:
cur.close()
conn.close()
return jsonify({
'success': False,
'error': 'Token đã được sử dụng rồi'
}), 400
# Check if token expired (comparing UTC times with timezone)
from datetime import datetime as dt, timezone
now_utc = dt.now(timezone.utc)
if now_utc > expires_at:
cur.close()
conn.close()
return jsonify({
'success': False,
'error': 'Token đã hết hạn (5 phút). Vui lòng yêu cầu liên kết lại.'
}), 400
# 2. Check if this zalo_chat_id is already linked to another user
cur.execute("""
SELECT id FROM users WHERE zalo_chat_id = %s AND id != %s
""", (zalo_id, user_id))
existing = cur.fetchone()
if existing:
cur.close()
conn.close()
return jsonify({
'success': False,
'error': 'Zalo ID này đã được liên kết với tài khoản khác'
}), 409
# 3. Update user with zalo_chat_id
cur.execute("""
UPDATE users
SET zalo_chat_id = %s,
updated_at_vn = NOW() AT TIME ZONE 'Asia/Ho_Chi_Minh'
WHERE id = %s
RETURNING id, full_name, zalo_chat_id
""", (zalo_id, user_id))
result = cur.fetchone()
if not result:
cur.close()
conn.close()
return jsonify({
'success': False,
'error': 'User không tồn tại'
}), 404
user_id_returned, full_name, zalo_chat_id_linked = result
# 4. Mark session token as used and link to user
cur.execute("""
UPDATE zalo_link_sessions
SET is_used = TRUE,
user_id = %s
WHERE id = %s
""", (user_id, session_id))
conn.commit()
print(f"✅ Zalo account linked!")
print(f" User: {full_name} (ID: {user_id_returned})")
print(f" Zalo ID: {zalo_chat_id_linked}")
return jsonify({
'success': True,
'message': 'Tài khoản Zalo đã được liên kết thành công!',
'zalo_id': zalo_chat_id_linked,
'user_id': user_id_returned,
'full_name': full_name
}), 200
finally:
cur.close()
conn.close()
except Exception as e:
print(f"❌ Link Zalo error: {e}")
return jsonify({
'success': False,
'error': str(e)
}), 500