125 lines
4.5 KiB
Python
125 lines
4.5 KiB
Python
from datetime import datetime, timezone, timedelta
|
|
from typing import Optional
|
|
import httpx
|
|
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.
|
|
"""
|
|
async with db.begin_nested():
|
|
# 1. Person létrehozása
|
|
new_person = Person(
|
|
first_name=user_in.first_name,
|
|
last_name=user_in.last_name
|
|
)
|
|
db.add(new_person)
|
|
await db.flush()
|
|
|
|
# 2. User létrehozása
|
|
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
|
|
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
|
|
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,
|
|
is_transferable=False # Master Book v1.1: Privát flotta nem eladható
|
|
)
|
|
db.add(new_org)
|
|
|
|
# 5. Audit Log
|
|
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
|
|
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
|
|
|
|
return new_user
|
|
|
|
@staticmethod
|
|
async def verify_vies_vat(vat_number: str) -> bool:
|
|
"""
|
|
EU VIES API lekérdezése az adószám hitelességének ellenőrzéséhez.
|
|
"""
|
|
try:
|
|
# Tisztítás: csak számok és országkód (pl. HU12345678)
|
|
clean_vat = "".join(filter(str.isalnum, vat_number)).upper()
|
|
async with httpx.AsyncClient() as client:
|
|
# Mock vagy valós API hívás helye
|
|
# Példa: response = await client.get(f"https://vies-api.eu/check/{clean_vat}")
|
|
return True # Jelenleg elfogadjuk teszteléshez
|
|
except Exception:
|
|
return False
|
|
|
|
@staticmethod
|
|
async def upgrade_to_company(db: AsyncSession, user_id: int, org_id: int, vat_number: str):
|
|
"""
|
|
Szervezet előléptetése Verified/Unverified céggé (Master Book v1.2).
|
|
"""
|
|
is_valid = await AuthService.verify_vies_vat(vat_number)
|
|
|
|
# 30 napos türelmi idő számítása
|
|
grace_period = datetime.now(timezone.utc) + timedelta(days=30)
|
|
|
|
stmt = text("""
|
|
UPDATE data.organizations
|
|
SET is_verified = :verified,
|
|
verification_expires_at = :expires,
|
|
org_type = 'fleet_owner',
|
|
is_transferable = True
|
|
WHERE id = :id AND owner_id = :uid
|
|
""")
|
|
|
|
await db.execute(stmt, {
|
|
"verified": is_valid,
|
|
"expires": None if is_valid else grace_period,
|
|
"id": org_id,
|
|
"uid": user_id
|
|
})
|
|
await db.commit()
|
|
|
|
@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 |