"""Passwordless-user onboarding — one-time set-password links sent by webhook. An admin creates a user with just a name/email/role (see ``user_service.create_user_without_password``). To let that user in, the admin clicks "Send Email": this service issues a one-time token and POSTs a payload carrying it to an admin-configured webhook URL (intended for a Power Automate flow that actually sends the email — the exact webhook contract is still being finalized, hence the configurable URL rather than a hardcoded integration). The same mechanism, and the same button, is reused for password resets on existing users. """ from __future__ import annotations import logging import secrets from datetime import datetime, timedelta import requests from sqlalchemy.orm import Session from app.config import settings from app.domain.errors import BusinessRuleViolation, EntityNotFoundError from app.models.password_setup_token import PasswordSetupToken from app.models.user import User logger = logging.getLogger(__name__) _WEBHOOK_URL_CONFIG_KEY = "password_setup.webhook_url" _TOKEN_TTL = timedelta(hours=24) def _read_system_config(db: Session, key: str) -> str | None: from app.models.system_config import SystemConfig # avoid circular at import time row = db.query(SystemConfig).filter(SystemConfig.key == key).first() return row.value if row else None def get_password_webhook_url(db: Session) -> str | None: """Return the configured Power-Automate-style webhook URL, or None.""" return _read_system_config(db, _WEBHOOK_URL_CONFIG_KEY) or None def set_password_webhook_url(db: Session, url: str) -> None: """Persist the webhook URL. Does not commit; caller commits.""" from app.models.system_config import SystemConfig row = db.query(SystemConfig).filter(SystemConfig.key == _WEBHOOK_URL_CONFIG_KEY).first() if row: row.value = url else: db.add(SystemConfig(key=_WEBHOOK_URL_CONFIG_KEY, value=url)) def create_setup_token(db: Session, user: User) -> PasswordSetupToken: """Issue a fresh one-time token for *user*, invalidating any unused ones. Does not commit; caller commits. """ db.query(PasswordSetupToken).filter( PasswordSetupToken.user_id == user.id, PasswordSetupToken.used_at.is_(None), ).delete() token = PasswordSetupToken( user_id=user.id, token=secrets.token_urlsafe(32), expires_at=datetime.utcnow() + _TOKEN_TTL, ) db.add(token) db.flush() return token def send_password_setup_email(db: Session, user: User) -> None: """Issue a token and POST it to the configured webhook. Raises BusinessRuleViolation if no webhook URL is configured yet. Does not commit; caller commits (the token must be persisted even if the webhook call itself fails, so a fresh "Send Email" retry works). """ webhook_url = get_password_webhook_url(db) if not webhook_url: raise BusinessRuleViolation( "No password-setup webhook is configured yet — set one in Settings first." ) token = create_setup_token(db, user) set_password_url = f"{settings.PLATFORM_URL}/set-password?token={token.token}" try: requests.post( webhook_url, json={ "email": user.email, "full_name": user.full_name, "set_password_url": set_password_url, }, timeout=10, ) except requests.RequestException: # Best-effort: the token still exists, so the admin can retry # "Send Email" once the webhook endpoint is reachable again. logger.warning("Password-setup webhook call failed for user %s", user.id, exc_info=True) def _get_valid_token_or_raise(db: Session, token: str) -> PasswordSetupToken: row = db.query(PasswordSetupToken).filter(PasswordSetupToken.token == token).first() if row is None: raise EntityNotFoundError("Password setup token", token) if row.used_at is not None: raise BusinessRuleViolation("This link has already been used") if row.expires_at < datetime.utcnow(): raise BusinessRuleViolation("This link has expired — ask an admin to send a new one") return row def validate_token(db: Session, token: str) -> User: """Return the token's owning user if the token is valid, else raise.""" row = _get_valid_token_or_raise(db, token) return row.user def consume_token_and_set_password(db: Session, token: str, new_password: str) -> User: """Set *new_password* for the token's user and mark the token used. Does not commit; caller commits. """ from app.auth import hash_password row = _get_valid_token_or_raise(db, token) user = row.user user.hashed_password = hash_password(new_password) user.must_change_password = False row.used_at = datetime.utcnow() db.flush() return user