-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate_admin.py
More file actions
69 lines (58 loc) · 1.93 KB
/
Copy pathcreate_admin.py
File metadata and controls
69 lines (58 loc) · 1.93 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
import asyncio
import getpass
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
from app.auth import get_password_hash, get_user_by_login
from app.db.database import get_session
from app.db.models import User
async def create_admin(db: AsyncSession, user_data: dict) -> User:
"""
Create a new user.
"""
hashed_password = get_password_hash(user_data["password"])
admin = User(login=user_data["login"], hashed_password=hashed_password, is_admin=True)
db.add(admin)
try:
await db.commit()
await db.refresh(admin)
return admin
except IntegrityError:
await db.rollback()
raise ValueError(f"User with login '{user_data['login']}' already exists")
async def input_password() -> str:
"""
Input password from the console.
"""
password = ""
while not password:
password1 = getpass.getpass("Enter the password: ")
if not password1:
continue
password2 = getpass.getpass("Re-enter the password: ")
if password1 == password2:
password = password1
break
print("Passwords do not match. Try again.")
return password
async def main():
"""
Create an administrator.
"""
print("\n*****Creating an administrator*****\n")
async for db in get_session():
while True:
login = input("Enter the name of the administrator: ")
existing_user = await get_user_by_login(db, login)
if existing_user:
print("User already exists. Choose a different username")
continue
if login:
break
print()
password = await input_password()
user_data = {"login": login, "password": password}
admin = await create_admin(db, user_data)
if admin:
print("Admin created successfully")
if __name__ == "__main__":
asyncio.run(main())