source: uc_users.py@ 95cf703

main
Last change on this file since 95cf703 was 95cf703, checked in by teo <teodorbogoeski@…>, 4 months ago

Initial commit: FRRUAS CLI prototype

  • Property mode set to 100644
File size: 2.7 KB
Line 
1import getpass
2
3import bcrypt
4
5from db import get_connection, pick_from_list
6
7
8def register_user():
9 """UC0009: Register a New User."""
10 print("\n=== Register a New User ===\n")
11
12 # Step 1: Show available roles
13 with get_connection() as conn:
14 with conn.cursor() as cur:
15 cur.execute("SELECT type_id, type_name, description FROM user_types ORDER BY type_id")
16 roles = cur.fetchall()
17
18 print(" Available roles:")
19 role_items = [f"{r[1]} - {r[2]}" for r in roles]
20 role_idx = pick_from_list(" Select role: ", role_items)
21 if role_idx is None:
22 return
23 type_id = roles[role_idx][0]
24 role_name = roles[role_idx][1]
25
26 # Step 2: Enter user details
27 first_name = input(" First name: ").strip()
28 if not first_name:
29 print(" First name is required.")
30 return
31
32 last_name = input(" Last name: ").strip()
33 if not last_name:
34 print(" Last name is required.")
35 return
36
37 email = input(" Email: ").strip()
38 if not email:
39 print(" Email is required.")
40 return
41
42 # Step 3: Check email uniqueness
43 with get_connection() as conn:
44 with conn.cursor() as cur:
45 cur.execute("SELECT COUNT(*) FROM users WHERE email = %s", (email,))
46 exists = cur.fetchone()[0]
47 if exists > 0:
48 print(f"\n ERROR: A user with email '{email}' already exists.")
49 return
50
51 # Step 4: Enter password
52 password = getpass.getpass(" Initial password: ").strip()
53 if not password:
54 print(" Password is required.")
55 return
56 password_confirm = getpass.getpass(" Confirm password: ").strip()
57 if password != password_confirm:
58 print(" Passwords do not match.")
59 return
60
61 # Step 5: Hash and insert
62 hashed = bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode()
63
64 conn = get_connection()
65 try:
66 with conn.cursor() as cur:
67 cur.execute(
68 """
69 INSERT INTO users (first_name, last_name, email, password, type_id)
70 VALUES (%s, %s, %s, %s, %s)
71 RETURNING user_id, first_name, last_name, email
72 """,
73 (first_name, last_name, email, hashed, type_id),
74 )
75 result = cur.fetchone()
76 conn.commit()
77
78 # Step 6: Confirmation
79 print(f"\n User created successfully!")
80 print(f" User ID: {result[0]}")
81 print(f" Name: {result[1]} {result[2]}")
82 print(f" Email: {result[3]}")
83 print(f" Role: {role_name}")
84 except Exception as e:
85 conn.rollback()
86 print(f"\n Error creating user: {e}")
87 finally:
88 conn.close()
Note: See TracBrowser for help on using the repository browser.