55 lines
2.1 KiB
Python
55 lines
2.1 KiB
Python
# Copyright (c) 2026 PowerOn AG
|
|
# All rights reserved.
|
|
"""Ensure new users receive a Home mandate on first login."""
|
|
|
|
import logging
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
def ensureHomeMandate(rootInterface, user) -> None:
|
|
"""Ensure user has a Home mandate, but only if they have no mandate memberships
|
|
AND no pending invitations.
|
|
|
|
Invited users should NOT get a Home mandate — they join existing mandates via
|
|
invitation acceptance and can create their own later via onboarding.
|
|
"""
|
|
userId = str(user.id)
|
|
userMandates = rootInterface.getUserMandates(userId)
|
|
|
|
if userMandates:
|
|
for um in userMandates:
|
|
mandate = rootInterface.getMandate(um.mandateId)
|
|
if mandate and (mandate.name or "").startswith("Home ") and not mandate.isSystem:
|
|
return
|
|
logger.debug(
|
|
f"User {user.username} has {len(userMandates)} mandate(s) but no Home — skipping auto-creation"
|
|
)
|
|
return
|
|
|
|
try:
|
|
normalizedEmail = (user.email or "").strip().lower() if user.email else None
|
|
pendingByUsername = rootInterface.getInvitationsByTargetUsername(user.username)
|
|
pendingByEmail = (
|
|
rootInterface.getInvitationsByEmail(normalizedEmail) if normalizedEmail else []
|
|
)
|
|
seenIds = set()
|
|
for inv in pendingByUsername + pendingByEmail:
|
|
if inv.id in seenIds:
|
|
continue
|
|
seenIds.add(inv.id)
|
|
if not inv.revokedAt and (inv.currentUses or 0) < (inv.maxUses or 1):
|
|
logger.info(
|
|
f"User {user.username} has pending invitation(s) — skipping Home mandate creation"
|
|
)
|
|
return
|
|
except Exception as e:
|
|
logger.warning(f"Could not check pending invitations for {user.username}: {e}")
|
|
|
|
homeMandateLabel = f"Home {user.username}"
|
|
rootInterface._provisionMandateForUser(
|
|
userId=userId,
|
|
mandateLabel=homeMandateLabel,
|
|
planKey="TRIAL_14D",
|
|
)
|
|
logger.info(f"Created Home mandate '{homeMandateLabel}' for user {user.username}")
|