81 lines
3.1 KiB
Python
81 lines
3.1 KiB
Python
from datetime import datetime, timezone
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
from sqlalchemy import select, and_, text
|
|
|
|
from app.models.identity import User, Person, Wallet
|
|
from app.models.organization import Organization, OrgType
|
|
from app.schemas.auth import UserRegister
|
|
from app.core.security import get_password_hash
|
|
from app.services.email_manager import email_manager
|
|
|
|
class AuthService:
|
|
@staticmethod
|
|
async def register_new_user(db: AsyncSession, user_in: UserRegister, ip_address: str):
|
|
"""
|
|
Master Book v1.0 szerinti atomikus regisztrációs folyamat.
|
|
"""
|
|
# Az AsyncSession.begin() biztosítja az ATOMICitást
|
|
async with db.begin_nested(): # beágyazott tranzakció a biztonságért
|
|
# 1. Person létrehozása (Identity Level)
|
|
new_person = Person(
|
|
first_name=user_in.first_name,
|
|
last_name=user_in.last_name
|
|
)
|
|
db.add(new_person)
|
|
await db.flush() # ID generáláshoz
|
|
|
|
# 2. User létrehozása (Technical Access)
|
|
new_user = User(
|
|
email=user_in.email,
|
|
hashed_password=get_password_hash(user_in.password),
|
|
person_id=new_person.id,
|
|
is_active=True
|
|
)
|
|
db.add(new_user)
|
|
await db.flush()
|
|
|
|
# 3. Economy: Wallet inicializálás (0 Coin, 0 XP)
|
|
new_wallet = Wallet(
|
|
user_id=new_user.id,
|
|
coin_balance=0.00,
|
|
xp_balance=0
|
|
)
|
|
db.add(new_wallet)
|
|
|
|
# 4. Fleet: Automatikus Privát Flotta létrehozása
|
|
new_org = Organization(
|
|
name=f"{user_in.last_name} {user_in.first_name} saját flottája",
|
|
org_type=OrgType.INDIVIDUAL,
|
|
owner_id=new_user.id
|
|
)
|
|
db.add(new_org)
|
|
|
|
# 5. Audit Log (SQLAlchemy Core hívással a sebességért)
|
|
audit_stmt = text("""
|
|
INSERT INTO data.audit_logs (user_id, action, endpoint, method, ip_address, created_at)
|
|
VALUES (:uid, 'USER_REGISTERED', '/api/v1/auth/register', 'POST', :ip, :now)
|
|
""")
|
|
await db.execute(audit_stmt, {
|
|
"uid": new_user.id,
|
|
"ip": ip_address,
|
|
"now": datetime.now(timezone.utc)
|
|
})
|
|
|
|
# 6. Üdvözlő email (Subject paraméter nélkül - Spec v1.1)
|
|
try:
|
|
await email_manager.send_email(
|
|
recipient=user_in.email,
|
|
template_key="registration",
|
|
variables={"first_name": user_in.first_name},
|
|
user_id=new_user.id
|
|
)
|
|
except Exception:
|
|
pass # Email hiba ne állítsa meg a tranzakciót
|
|
|
|
return new_user
|
|
|
|
@staticmethod
|
|
async def check_email_availability(db: AsyncSession, email: str) -> bool:
|
|
query = select(User).where(and_(User.email == email, User.is_deleted == False))
|
|
result = await db.execute(query)
|
|
return result.scalar_one_or_none() is None |