-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathseed.py
More file actions
74 lines (55 loc) · 2.02 KB
/
Copy pathseed.py
File metadata and controls
74 lines (55 loc) · 2.02 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
from __future__ import annotations
import asyncio
from typing import TYPE_CHECKING
import structlog
from argon2 import PasswordHasher
from sqlalchemy import select
from python_api.db.models import User, UserRole
if TYPE_CHECKING:
from sqlalchemy.ext.asyncio import AsyncSession
from python_api.db.session import dispose_engine, get_session_factory
logger = structlog.get_logger()
ph = PasswordHasher()
ROLES = [
{"title": "admin", "description": "Administrator with full access"},
{"title": "normal", "description": "Regular user"},
]
ADMIN_EMAIL = "admin@example.com"
ADMIN_PASSWORD = "admin123"
async def seed() -> None:
session_factory = get_session_factory()
async with session_factory() as session:
await _seed_roles(session)
await _seed_admin(session)
await session.commit()
await dispose_engine()
logger.info("Seed completed")
async def _seed_roles(session: AsyncSession) -> None:
for role_data in ROLES:
result = await session.execute(
select(UserRole).where(UserRole.title == role_data["title"])
)
existing = result.scalar_one_or_none()
if existing is None:
session.add(UserRole(**role_data))
logger.info("Created role", title=role_data["title"])
else:
logger.info("Role already exists", title=role_data["title"])
async def _seed_admin(session: AsyncSession) -> None:
result = await session.execute(select(User).where(User.email == ADMIN_EMAIL))
existing = result.scalar_one_or_none()
if existing is not None:
logger.info("Admin user already exists")
return
result = await session.execute(select(UserRole).where(UserRole.title == "admin"))
admin_role = result.scalar_one()
admin = User(
email=ADMIN_EMAIL,
password_hash=ph.hash(ADMIN_PASSWORD),
role_id=admin_role.id,
is_active=True,
)
session.add(admin)
logger.info("Created admin user", email=ADMIN_EMAIL)
if __name__ == "__main__":
asyncio.run(seed())