-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate_admin.py
More file actions
772 lines (613 loc) · 24.1 KB
/
create_admin.py
File metadata and controls
772 lines (613 loc) · 24.1 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
"""
This module contains runtime logic for `create_admin.py`.
In simple terms, this file groups related code so the project can
handle one clear responsibility without mixing unrelated behavior.
"""
import base64
import csv
import os
import re
import secrets
import string
import sys
from datetime import datetime, timezone
from getpass import getpass
from pathlib import Path
from zoneinfo import ZoneInfo
from cryptography.fernet import Fernet, InvalidToken
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from django.db import IntegrityError
TOOL_NAME = "create_admin"
SENTINEL_PLAINTEXT = b"create_admin_tool_unlocked_v1"
LOCK_FILE = Path(__file__).resolve().parent / ".create_admin.lock"
ACCESS_TOKENS_FILE = Path(__file__).resolve().parent / "access_tokens.csv"
MAX_ACCESS_ATTEMPTS = 3
EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
TOKENS_HEADERS = ["Name", "email", "access token", "created at", "updated at"]
def setup_django():
"""
Simple purpose: run `setup_django` and complete its job safely.
This function exists to keep one task focused and easy to reuse.
Returns:
The updated result, status object, or `None` depending on flow.
Raises:
Does not raise intentionally; caller-level validation/handlers manage failures.
"""
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "aidra_backend.settings")
try:
import django
django.setup()
except Exception as exc:
print(f"Failed to initialize Django: {exc}")
sys.exit(1)
def _derive_key_from_code(code, salt_b64):
"""
Simple purpose: run `_derive_key_from_code` and complete its job safely.
This function exists to keep one task focused and easy to reuse.
Args:
code: Input value used by this step of the workflow.
salt_b64: Input value used by this step of the workflow.
Returns:
A result value that the caller uses in the next step.
Raises:
Does not raise intentionally; caller-level validation/handlers manage failures.
"""
salt = base64.urlsafe_b64decode(salt_b64.encode("utf-8"))
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=390000,
)
return base64.urlsafe_b64encode(kdf.derive(code.encode("utf-8")))
def _fernet_from_code(code, salt_b64):
"""
Simple purpose: run `_fernet_from_code` and complete its job safely.
This function exists to keep one task focused and easy to reuse.
Args:
code: Input value used by this step of the workflow.
salt_b64: Input value used by this step of the workflow.
Returns:
A result value that the caller uses in the next step.
Raises:
Does not raise intentionally; caller-level validation/handlers manage failures.
"""
key = _derive_key_from_code(code, salt_b64)
return Fernet(key)
def _load_tool_lock():
"""
Simple purpose: run `_load_tool_lock` and complete its job safely.
This function exists to keep one task focused and easy to reuse.
Returns:
A result value that the caller uses in the next step.
Raises:
Does not raise intentionally; caller-level validation/handlers manage failures.
"""
from accounts.models import ToolAccessLock
return ToolAccessLock.objects.filter(tool_name=TOOL_NAME, is_active=True).first()
def _verify_code_against_db(code, tool_lock):
"""
Simple purpose: run `_verify_code_against_db` and complete its job safely.
This function exists to keep one task focused and easy to reuse.
Args:
code: Input value used by this step of the workflow.
tool_lock: Input value used by this step of the workflow.
Returns:
A result value that the caller uses in the next step.
Raises:
Does not raise intentionally; caller-level validation/handlers manage failures.
"""
from django.contrib.auth.hashers import check_password
if not check_password(code, tool_lock.code_hash):
return False
try:
fernet = _fernet_from_code(code, tool_lock.kdf_salt)
plaintext = fernet.decrypt(tool_lock.encrypted_sentinel.encode("utf-8"))
return plaintext == SENTINEL_PLAINTEXT
except Exception:
return False
def _verify_or_create_lock_file(code, tool_lock):
"""
Simple purpose: run `_verify_or_create_lock_file` and complete its job safely.
This function exists to keep one task focused and easy to reuse.
Args:
code: Input value used by this step of the workflow.
tool_lock: Input value used by this step of the workflow.
Returns:
A result value that the caller uses in the next step.
Raises:
Does not raise intentionally; caller-level validation/handlers manage failures.
"""
try:
fernet = _fernet_from_code(code, tool_lock.kdf_salt)
if LOCK_FILE.exists():
encrypted = LOCK_FILE.read_bytes()
decrypted = fernet.decrypt(encrypted)
return decrypted == SENTINEL_PLAINTEXT
LOCK_FILE.write_bytes(fernet.encrypt(SENTINEL_PLAINTEXT))
return True
except (InvalidToken, OSError, ValueError):
return False
def authorize_script_access():
"""
Simple purpose: run `authorize_script_access` and complete its job safely.
This function exists to keep one task focused and easy to reuse.
Returns:
A result value that the caller uses in the next step.
Raises:
Does not raise intentionally; caller-level validation/handlers manage failures.
"""
print("Admin tool access is protected.")
tool_lock = _load_tool_lock()
if not tool_lock:
print("Tool lock is not configured in database. Run migrations first.")
return False, None
for attempt in range(1, MAX_ACCESS_ATTEMPTS + 1):
provided = getpass("Enter access code: ").strip()
if _verify_code_against_db(provided, tool_lock) and _verify_or_create_lock_file(provided, tool_lock):
return True, provided
remaining = MAX_ACCESS_ATTEMPTS - attempt
if remaining > 0:
print(f"Incorrect/invalid access code. Attempts left: {remaining}")
print("Access denied.")
return False, None
def generate_access_token(length=32):
"""
Simple purpose: run `generate_access_token` and complete its job safely.
This function exists to keep one task focused and easy to reuse.
Args:
length: Input value used by this step of the workflow.
Returns:
A newly created object or generated value.
Raises:
Does not raise intentionally; caller-level validation/handlers manage failures.
"""
alphabet = string.ascii_letters + string.digits
return "AIDRAx-" + "".join(secrets.choice(alphabet) for _ in range(length))
def _read_access_token_rows():
"""
Simple purpose: run `_read_access_token_rows` and complete its job safely.
This function exists to keep one task focused and easy to reuse.
Returns:
A result value that the caller uses in the next step.
Raises:
Does not raise intentionally; caller-level validation/handlers manage failures.
"""
if not ACCESS_TOKENS_FILE.exists():
return []
try:
with ACCESS_TOKENS_FILE.open("r", newline="", encoding="utf-8") as f:
reader = csv.DictReader(f)
rows = []
for row in reader:
rows.append(
{
"Name": (row.get("Name") or row.get("name") or "").strip(),
"email": (row.get("email") or "").strip().lower(),
"access token": (
row.get("access token")
or row.get("email access token")
or row.get("access_token")
or ""
).strip(),
"created at": (
row.get("created at")
or row.get("created_at")
or row.get("created_at_utc")
or ""
).strip(),
"updated at": (
row.get("updated at")
or row.get("updated_at_utc")
or ""
).strip(),
}
)
return rows
except Exception:
return []
def _write_access_token_rows(rows):
"""
Simple purpose: run `_write_access_token_rows` and complete its job safely.
This function exists to keep one task focused and easy to reuse.
Args:
rows: Input value used by this step of the workflow.
Returns:
A result value that the caller uses in the next step.
Raises:
Does not raise intentionally; caller-level validation/handlers manage failures.
"""
ACCESS_TOKENS_FILE.parent.mkdir(parents=True, exist_ok=True)
with ACCESS_TOKENS_FILE.open("w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=TOKENS_HEADERS)
writer.writeheader()
for row in rows:
writer.writerow(
{
"Name": (row.get("Name") or "").strip(),
"email": (row.get("email") or "").strip().lower(),
"access token": (row.get("access token") or "").strip(),
"created at": (row.get("created at") or "").strip(),
"updated at": (row.get("updated at") or "").strip(),
}
)
def _ist_time_label(dt=None):
"""
Simple purpose: run `_ist_time_label` and complete its job safely.
This function exists to keep one task focused and easy to reuse.
Args:
dt: Input value used by this step of the workflow.
Returns:
A result value that the caller uses in the next step.
Raises:
Does not raise intentionally; caller-level validation/handlers manage failures.
"""
if dt is None:
dt = datetime.now(timezone.utc)
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
return dt.astimezone(ZoneInfo("Asia/Kolkata")).strftime("%H:%M:%S IST")
def upsert_access_token_csv(name, email, access_token, created_at=None):
"""
Simple purpose: run `upsert_access_token_csv` and complete its job safely.
This function exists to keep one task focused and easy to reuse.
Args:
name: Input value used by this step of the workflow.
email: Input value used by this step of the workflow.
access_token: Input value used by this step of the workflow.
created_at: Input value used by this step of the workflow.
Returns:
A result value that the caller uses in the next step.
Raises:
Does not raise intentionally; caller-level validation/handlers manage failures.
"""
email = (email or "").strip().lower()
if not email:
return
rows = _read_access_token_rows()
now_ist = _ist_time_label()
created_at_ist = _ist_time_label(created_at) if created_at else now_ist
updated = False
for row in rows:
if (row.get("email") or "").strip().lower() == email:
row["Name"] = (name or row.get("Name") or "").strip()
row["access token"] = access_token
row["created at"] = (row.get("created at") or created_at_ist).strip()
row["updated at"] = now_ist
updated = True
break
if not updated:
rows.append(
{
"Name": (name or "").strip(),
"email": email,
"access token": access_token,
"created at": created_at_ist,
"updated at": now_ist,
}
)
_write_access_token_rows(rows)
def remove_access_token_csv(email):
"""
Simple purpose: run `remove_access_token_csv` and complete its job safely.
This function exists to keep one task focused and easy to reuse.
Args:
email: Input value used by this step of the workflow.
Returns:
A result value that the caller uses in the next step.
Raises:
Does not raise intentionally; caller-level validation/handlers manage failures.
"""
email = (email or "").strip().lower()
if not email:
return
rows = _read_access_token_rows()
rows = [r for r in rows if (r.get("email") or "").strip().lower() != email]
_write_access_token_rows(rows)
def sync_access_tokens_csv_with_db():
"""
Simple purpose: run `sync_access_tokens_csv_with_db` and complete its job safely.
This function exists to keep one task focused and easy to reuse.
Returns:
The updated result, status object, or `None` depending on flow.
Raises:
Does not raise intentionally; caller-level validation/handlers manage failures.
"""
from accounts.models import User
existing_rows_by_email = {
(row.get("email") or "").strip().lower(): row
for row in _read_access_token_rows()
if (row.get("email") or "").strip()
}
now_ist = _ist_time_label()
synced_rows = []
admins = User.objects.filter(role="admin").order_by("created_at")
for admin in admins:
email = (admin.email or "").strip().lower()
if not email:
continue
existing = existing_rows_by_email.get(email, {})
display_name = (
f"{(admin.first_name or '').strip()} {(admin.last_name or '').strip()}".strip()
or email
)
synced_rows.append(
{
"Name": display_name,
"email": email,
"access token": (admin.admin_access_token or "").strip(),
"created at": _ist_time_label(admin.created_at),
"updated at": now_ist,
}
)
_write_access_token_rows(synced_rows)
def prompt_non_empty(label):
"""
Simple purpose: run `prompt_non_empty` and complete its job safely.
This function exists to keep one task focused and easy to reuse.
Args:
label: Input value used by this step of the workflow.
Returns:
A result value that the caller uses in the next step.
Raises:
Does not raise intentionally; caller-level validation/handlers manage failures.
"""
while True:
value = input(label).strip()
if value:
return value
print("Value cannot be empty.")
def prompt_password():
"""
Simple purpose: run `prompt_password` and complete its job safely.
This function exists to keep one task focused and easy to reuse.
Returns:
A result value that the caller uses in the next step.
Raises:
Does not raise intentionally; caller-level validation/handlers manage failures.
"""
while True:
password = getpass("Password: ")
confirm = getpass("Confirm password: ")
if not password:
print("Password cannot be empty.")
continue
if password != confirm:
print("Passwords do not match.")
continue
return password
def rotate_access_code(current_code):
"""
Simple purpose: run `rotate_access_code` and complete its job safely.
This function exists to keep one task focused and easy to reuse.
Args:
current_code: Input value used by this step of the workflow.
Returns:
A result value that the caller uses in the next step.
Raises:
Does not raise intentionally; caller-level validation/handlers manage failures.
"""
from django.contrib.auth.hashers import make_password
from accounts.models import ToolAccessLock
print("\nRotate tool access code")
verify_current = getpass("Current access code: ").strip()
if not secrets.compare_digest(verify_current, current_code):
print("Current access code does not match.")
return current_code
new_code = getpass("New access code: ").strip()
confirm = getpass("Confirm new access code: ").strip()
if not new_code:
print("New code cannot be empty.")
return current_code
if new_code != confirm:
print("New access code confirmation failed.")
return current_code
tool_lock = ToolAccessLock.objects.filter(tool_name=TOOL_NAME, is_active=True).first()
if not tool_lock:
print("Tool lock not found.")
return current_code
salt_b64 = base64.urlsafe_b64encode(os.urandom(16)).decode("utf-8")
fernet = _fernet_from_code(new_code, salt_b64)
tool_lock.code_hash = make_password(new_code)
tool_lock.kdf_salt = salt_b64
tool_lock.encrypted_sentinel = fernet.encrypt(SENTINEL_PLAINTEXT).decode("utf-8")
tool_lock.save(update_fields=["code_hash", "kdf_salt", "encrypted_sentinel", "updated_at"])
LOCK_FILE.write_bytes(fernet.encrypt(SENTINEL_PLAINTEXT))
print("Access code rotated successfully.")
return new_code
def create_admin():
"""
Simple purpose: run `create_admin` and complete its job safely.
This function exists to keep one task focused and easy to reuse.
Returns:
A newly created object or generated value.
Raises:
Does not raise intentionally; caller-level validation/handlers manage failures.
"""
from django.contrib.auth.hashers import make_password
from django.contrib.auth.password_validation import validate_password
from django.core.exceptions import ValidationError
from accounts.models import User
print("\nCreate Admin")
email = prompt_non_empty("Email: ").lower()
if not EMAIL_RE.match(email):
print("Invalid email format.")
return
existing_user = User.objects.filter(email__iexact=email).only("role").first()
if existing_user:
role = (existing_user.role or "user").strip().lower()
if role == "student":
print("Cannot create admin: this email is already registered as a student.")
elif role == "faculty":
print("Cannot create admin: this email is already registered as a faculty member.")
elif role == "admin":
print("Cannot create admin: this email is already registered as an admin.")
else:
print(f"Cannot create admin: this email is already registered as role '{role}'.")
return
first_name = input("First name (optional): ").strip()
last_name = input("Last name (optional): ").strip()
password = prompt_password()
try:
validate_password(password)
except ValidationError as exc:
print("Password validation failed:")
for msg in exc.messages:
print(f"- {msg}")
return
access_token = generate_access_token(32)
try:
user = User.objects.create_user(
username=email,
email=email,
password=password,
role="admin",
first_name=first_name,
last_name=last_name,
is_staff=True,
is_superuser=True,
)
except IntegrityError:
print("Could not create admin because this email already exists in the database.")
return
user.admin_access_token = access_token
user.secret_key_hash = make_password(access_token)
user.failed_login_attempts = 0
user.locked_until = None
user.is_verified = True
user.status = "approved"
user.is_staff = True
user.is_superuser = True
user.save()
print("\nAdmin created successfully.")
print(f"Email: {user.email}")
print("Access token (save this securely):")
print(access_token)
display_name = f"{(user.first_name or '').strip()} {(user.last_name or '').strip()}".strip() or user.email
upsert_access_token_csv(display_name, user.email, access_token, created_at=user.created_at)
sync_access_tokens_csv_with_db()
print(f"Token updated in {ACCESS_TOKENS_FILE.name}.")
print("")
def list_admins():
"""
Simple purpose: run `list_admins` and complete its job safely.
This function exists to keep one task focused and easy to reuse.
Returns:
Requested data in the shape expected by the caller.
Raises:
Does not raise intentionally; caller-level validation/handlers manage failures.
"""
from accounts.models import User
admins = User.objects.filter(role="admin").order_by("created_at")
print("\nAdmins")
if not admins.exists():
print("No admins found.\n")
return
for idx, admin in enumerate(admins, 1):
name = f"{(admin.first_name or '').strip()} {(admin.last_name or '').strip()}".strip() or "-"
print(f"{idx}. {admin.email} | name: {name} | superuser: {bool(admin.is_superuser)}")
print("")
def delete_admin():
"""
Simple purpose: run `delete_admin` and complete its job safely.
This function exists to keep one task focused and easy to reuse.
Returns:
A result value that the caller uses in the next step.
Raises:
Does not raise intentionally; caller-level validation/handlers manage failures.
"""
from accounts.models import User
admins = list(User.objects.filter(role="admin").order_by("created_at"))
print("\nDelete Admin")
if not admins:
print("No admins found.\n")
return
for idx, admin in enumerate(admins, 1):
name = f"{(admin.first_name or '').strip()} {(admin.last_name or '').strip()}".strip() or "-"
print(f"{idx}. {admin.email} | name: {name}")
print("0. Cancel")
choice = input("Select admin number to delete: ").strip()
if choice == "0":
print("Cancelled.\n")
return
if not choice.isdigit():
print("Invalid option.\n")
return
idx = int(choice) - 1
if idx < 0 or idx >= len(admins):
print("Invalid option.\n")
return
if len(admins) == 1:
print("Cannot delete the last admin account.\n")
return
target = admins[idx]
confirm = input(f"Type DELETE to confirm removing {target.email}: ").strip()
if confirm != "DELETE":
print("Deletion cancelled.\n")
return
target.delete()
remove_access_token_csv(target.email)
sync_access_tokens_csv_with_db()
print(f"Admin deleted: {target.email}\n")
def ensure_all_admins_are_superusers():
"""
Simple purpose: run `ensure_all_admins_are_superusers` and complete its job safely.
This function exists to keep one task focused and easy to reuse.
Returns:
A result value that the caller uses in the next step.
Raises:
Does not raise intentionally; caller-level validation/handlers manage failures.
"""
from accounts.models import User
admins = User.objects.filter(role="admin")
for admin in admins:
changed = False
if not admin.is_staff:
admin.is_staff = True
changed = True
if not admin.is_superuser:
admin.is_superuser = True
changed = True
if changed:
admin.save(update_fields=["is_staff", "is_superuser"])
def main_menu(access_code):
"""
Simple purpose: run `main_menu` and complete its job safely.
This function exists to keep one task focused and easy to reuse.
Args:
access_code: Input value used by this step of the workflow.
Returns:
A result value that the caller uses in the next step.
Raises:
Does not raise intentionally; caller-level validation/handlers manage failures.
"""
while True:
print("=== Admin Management Menu ===")
print("1. Create admin")
print("2. List admins")
print("3. Delete admin")
print("4. Rotate tool access code")
print("5. Exit")
choice = input("Choose an option (1-5): ").strip()
if choice == "1":
create_admin()
elif choice == "2":
list_admins()
elif choice == "3":
delete_admin()
elif choice == "4":
access_code = rotate_access_code(access_code)
elif choice == "5":
print("Exiting.")
break
else:
print("Invalid option.\n")
if __name__ == "__main__":
setup_django()
ensure_all_admins_are_superusers()
sync_access_tokens_csv_with_db()
ok, active_code = authorize_script_access()
if not ok:
sys.exit(1)
main_menu(active_code)