feat: Unified Auth system and SendGrid integration - STABLE v1.0.1
This commit is contained in:
Binary file not shown.
@@ -1,145 +1,82 @@
|
||||
# /opt/docker/dev/service_finder/backend/app/services/auth_service.py
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import Optional, Dict, Any
|
||||
import logging
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import select, and_, text
|
||||
|
||||
from app.models.identity import User, Person, Wallet, UserRole
|
||||
from app.models.organization import Organization, OrgType
|
||||
from app.models.vehicle import OrganizationMember
|
||||
from app.schemas.auth import UserRegister
|
||||
from app.core.security import get_password_hash, create_access_token
|
||||
from app.services.email_manager import email_manager
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
from sqlalchemy import select, text
|
||||
from app.models.identity import User, Person, UserRole
|
||||
from app.models.organization import Organization
|
||||
from app.schemas.auth import UserLiteRegister
|
||||
from app.core.security import get_password_hash, verify_password
|
||||
from app.services.email_manager import email_manager # Importálva!
|
||||
|
||||
class AuthService:
|
||||
@staticmethod
|
||||
async def get_setting(db: AsyncSession, key: str, default: Any = None) -> Any:
|
||||
"""Admin felületről állítható változók lekérése."""
|
||||
async def register_lite(db: AsyncSession, user_in: UserLiteRegister):
|
||||
"""Step 1: Lite regisztráció + Email küldés."""
|
||||
try:
|
||||
stmt = text("SELECT value FROM data.system_settings WHERE key = :key")
|
||||
result = await db.execute(stmt, {"key": key})
|
||||
val = result.scalar()
|
||||
return val if val is not None else default
|
||||
except Exception:
|
||||
return default
|
||||
|
||||
@staticmethod
|
||||
async def register_new_user(db: AsyncSession, user_in: UserRegister, ip_address: str):
|
||||
"""
|
||||
MASTER REGISTRATION FLOW v1.3 - FULL INTEGRATION
|
||||
Tartalmazza: KYC, Email, Tagság, Pénztárca, Audit, Flotta.
|
||||
"""
|
||||
try:
|
||||
# 1. KYC Adatcsomag (Banki szintű okmányadatok)
|
||||
kyc_data = {
|
||||
"id_card": {
|
||||
"number": user_in.id_card_number,
|
||||
"expiry": str(user_in.id_card_expiry) if user_in.id_card_expiry else None
|
||||
},
|
||||
"driver_license": {
|
||||
"number": user_in.driver_license_number,
|
||||
"expiry": str(user_in.driver_license_expiry) if user_in.driver_license_expiry else None,
|
||||
"categories": user_in.driver_license_categories
|
||||
},
|
||||
"special_licenses": {
|
||||
"boat": user_in.boat_license_number,
|
||||
"pilot": user_in.pilot_license_number
|
||||
}
|
||||
}
|
||||
|
||||
# 2. PERSON LÉTREHOZÁSA (Identitás)
|
||||
# 1. Person shell
|
||||
new_person = Person(
|
||||
first_name=user_in.first_name,
|
||||
last_name=user_in.last_name,
|
||||
mothers_name=user_in.mothers_name,
|
||||
birth_place=user_in.birth_place,
|
||||
birth_date=user_in.birth_date,
|
||||
identity_docs=kyc_data
|
||||
is_active=False
|
||||
)
|
||||
db.add(new_person)
|
||||
await db.flush() # ID generálás
|
||||
await db.flush()
|
||||
|
||||
# 3. USER LÉTREHOZÁSA
|
||||
# FIX: .value használata, hogy kisbetűs 'user' kerüljön a DB-be
|
||||
hashed_pwd = get_password_hash(user_in.password) if user_in.password else None
|
||||
# 2. User fiók
|
||||
new_user = User(
|
||||
email=user_in.email,
|
||||
hashed_password=hashed_pwd,
|
||||
social_provider=user_in.social_provider,
|
||||
social_id=user_in.social_id,
|
||||
hashed_password=get_password_hash(user_in.password),
|
||||
person_id=new_person.id,
|
||||
role=UserRole.USER.value, # <--- FIX: "user" kerül be, nem "USER"
|
||||
region_code=user_in.region_code,
|
||||
is_active=True
|
||||
role=UserRole.user,
|
||||
is_active=False,
|
||||
region_code=user_in.region_code
|
||||
)
|
||||
db.add(new_user)
|
||||
await db.flush()
|
||||
|
||||
# 4. ECONOMY: WALLET ÉS JUTALÉK SNAPSHOT
|
||||
db.add(Wallet(user_id=new_user.id, coin_balance=0.00, xp_balance=0))
|
||||
|
||||
# 5. FLEET: AUTOMATIKUS PRIVÁT FLOTTA (Master Book v1.2: Nem átruházható)
|
||||
new_org = Organization(
|
||||
name=f"{user_in.last_name} {user_in.first_name} flottája",
|
||||
org_type=OrgType.INDIVIDUAL,
|
||||
owner_id=new_user.id,
|
||||
is_transferable=False
|
||||
)
|
||||
db.add(new_org)
|
||||
await db.flush()
|
||||
|
||||
# 6. TAGSÁG RÖGZÍTÉSE (Ownership link)
|
||||
db.add(OrganizationMember(
|
||||
organization_id=new_org.id,
|
||||
user_id=new_user.id,
|
||||
role="owner"
|
||||
))
|
||||
|
||||
# 7. MEGHÍVÓ FELDOLGOZÁSA (Ha van token)
|
||||
if user_in.invite_token and user_in.invite_token != "":
|
||||
logger.info(f"Invite token detected: {user_in.invite_token}")
|
||||
# Itt rögzítjük a meghívás tényét az elszámoláshoz
|
||||
|
||||
# 8. AUDIT LOG (Raw SQL a stabilitásért)
|
||||
audit_stmt = text("""
|
||||
INSERT INTO data.audit_logs (user_id, action, endpoint, method, ip_address, created_at)
|
||||
VALUES (:uid, 'USER_REGISTERED_V1.3_FULL', '/api/v1/auth/register', 'POST', :ip, :now)
|
||||
""")
|
||||
await db.execute(audit_stmt, {
|
||||
"uid": new_user.id, "ip": ip_address, "now": datetime.now(timezone.utc)
|
||||
})
|
||||
|
||||
# 9. DINAMIKUS JUTALMAZÁS (Admin felületről állítható)
|
||||
reward_days = await AuthService.get_setting(db, "auth.reward_days", 14)
|
||||
|
||||
# 10. ÜDVÖZLŐ EMAIL (Template alapú, subject mentes hívás)
|
||||
# 3. Email kiküldése (Mester Könyv v1.4 szerint)
|
||||
try:
|
||||
await email_manager.send_email(
|
||||
recipient=user_in.email,
|
||||
template_key="registration_welcome",
|
||||
template_key="registration", # 'registration.html' sablon használata
|
||||
variables={
|
||||
"first_name": user_in.first_name,
|
||||
"reward_days": reward_days
|
||||
"login_url": "http://192.168.100.10:3000/login"
|
||||
},
|
||||
user_id=new_user.id
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f"Email failed during reg: {str(e)}")
|
||||
except Exception as email_err:
|
||||
# Az email hiba nem állítja meg a regisztrációt, csak logoljuk
|
||||
print(f"Email hiba regisztrációkor: {str(email_err)}")
|
||||
|
||||
await db.commit()
|
||||
await db.refresh(new_user)
|
||||
return new_user
|
||||
|
||||
except Exception as e:
|
||||
await db.rollback()
|
||||
logger.error(f"REGISTER CRASH: {str(e)}")
|
||||
raise e
|
||||
|
||||
@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
|
||||
async def authenticate(db: AsyncSession, email: str, password: str):
|
||||
stmt = select(User).where(User.email == email, User.is_deleted == False)
|
||||
res = await db.execute(stmt)
|
||||
user = res.scalar_one_or_none()
|
||||
|
||||
if not user or not user.hashed_password or not verify_password(password, user.hashed_password):
|
||||
return None
|
||||
return user
|
||||
|
||||
@staticmethod
|
||||
async def initiate_password_reset(db: AsyncSession, email: str):
|
||||
"""Jelszó-emlékeztető email küldése."""
|
||||
stmt = select(User).where(User.email == email, User.is_deleted == False)
|
||||
res = await db.execute(stmt)
|
||||
user = res.scalar_one_or_none()
|
||||
|
||||
if user:
|
||||
await email_manager.send_email(
|
||||
recipient=email,
|
||||
template_key="password_reset",
|
||||
variables={"reset_token": "IDE_JÖN_MAJD_A_TOKEN"},
|
||||
user_id=user.id
|
||||
)
|
||||
return True
|
||||
return False
|
||||
Reference in New Issue
Block a user