|
| 1 | +from uuid import uuid4 |
| 2 | +from fastapi import APIRouter, Depends, Form |
| 3 | +from fastapi.responses import RedirectResponse |
| 4 | +from fastapi.exceptions import HTTPException |
| 5 | +from pydantic import EmailStr |
| 6 | +from sqlmodel import Session, select |
| 7 | +from logging import getLogger |
| 8 | + |
| 9 | +from utils.dependencies import get_authenticated_user |
| 10 | +from utils.db import get_session |
| 11 | +from utils.models import User, Role, Account, Invitation, ValidPermissions, Organization |
| 12 | +from utils.invitations import send_invitation_email |
| 13 | +from exceptions.http_exceptions import ( |
| 14 | + UserIsAlreadyMemberError, |
| 15 | + ActiveInvitationExistsError, |
| 16 | + InvalidRoleForOrganizationError, |
| 17 | + OrganizationNotFoundError, |
| 18 | + InvitationEmailSendError, |
| 19 | +) |
| 20 | +from exceptions.exceptions import EmailSendFailedError |
| 21 | + |
| 22 | +# Setup logger |
| 23 | +logger = getLogger("uvicorn.error") |
| 24 | + |
| 25 | +router = APIRouter( |
| 26 | + prefix="/invitations", |
| 27 | + tags=["invitations"], |
| 28 | +) |
| 29 | + |
| 30 | + |
| 31 | +@router.post("/", name="create_invitation") |
| 32 | +async def create_invitation( |
| 33 | + current_user: User = Depends(get_authenticated_user), |
| 34 | + session: Session = Depends(get_session), |
| 35 | + invitee_email: EmailStr = Form(...), |
| 36 | + role_id: int = Form(...), |
| 37 | + organization_id: int = Form(...), |
| 38 | +): |
| 39 | + # Fetch the organization |
| 40 | + organization = session.get(Organization, organization_id) |
| 41 | + if not organization: |
| 42 | + raise OrganizationNotFoundError() |
| 43 | + |
| 44 | + # Check if the current user has permission to invite users to this organization |
| 45 | + if not current_user.has_permission(ValidPermissions.INVITE_USER, organization): |
| 46 | + raise HTTPException(status_code=403, detail="You don't have permission to invite users to this organization") |
| 47 | + |
| 48 | + # Verify the role exists and belongs to this organization |
| 49 | + role = session.get(Role, role_id) |
| 50 | + if not role: |
| 51 | + raise HTTPException(status_code=404, detail="Role not found") |
| 52 | + if role.organization_id != organization_id: |
| 53 | + raise InvalidRoleForOrganizationError() |
| 54 | + |
| 55 | + # Check if invitee is already a member of the organization |
| 56 | + existing_account = session.exec(select(Account).where(Account.email == invitee_email)).first() |
| 57 | + if existing_account: |
| 58 | + # Check if any user with this account is already a member |
| 59 | + existing_user = session.exec(select(User).where(User.account_id == existing_account.id)).first() |
| 60 | + if existing_user: |
| 61 | + # Check if user has any role in this organization |
| 62 | + if any(role.organization_id == organization_id for role in existing_user.roles): |
| 63 | + raise UserIsAlreadyMemberError() |
| 64 | + |
| 65 | + # Check for active invitations with the same email |
| 66 | + active_invitations = Invitation.get_active_for_org(session, organization_id) |
| 67 | + if any(invitation.invitee_email == invitee_email for invitation in active_invitations): |
| 68 | + raise ActiveInvitationExistsError() |
| 69 | + |
| 70 | + # Create the invitation |
| 71 | + token = str(uuid4()) |
| 72 | + invitation = Invitation( |
| 73 | + organization_id=organization_id, |
| 74 | + role_id=role_id, |
| 75 | + invitee_email=invitee_email, |
| 76 | + token=token, |
| 77 | + ) |
| 78 | + |
| 79 | + session.add(invitation) |
| 80 | + |
| 81 | + try: |
| 82 | + # Refresh to ensure relationships are loaded *before* sending email |
| 83 | + session.flush() # Ensure invitation gets an ID if needed by email sender, flush changes |
| 84 | + session.refresh(invitation) |
| 85 | + # Ensure organization is loaded before passing to email function |
| 86 | + # (May already be loaded, but explicit refresh is safer) |
| 87 | + if not invitation.organization: |
| 88 | + session.refresh(organization) # Refresh the org object fetched earlier |
| 89 | + invitation.organization = organization # Assign if needed |
| 90 | + |
| 91 | + # Send email synchronously BEFORE committing |
| 92 | + send_invitation_email(invitation, session) |
| 93 | + |
| 94 | + # Commit *only* if email sending was successful |
| 95 | + session.commit() |
| 96 | + session.refresh(invitation) # Refresh again after commit if needed elsewhere |
| 97 | + |
| 98 | + except EmailSendFailedError as e: |
| 99 | + logger.error(f"Invitation email failed for {invitee_email} in org {organization_id}: {e}") |
| 100 | + session.rollback() # Rollback the invitation creation |
| 101 | + raise InvitationEmailSendError() # Raise HTTP 500 |
| 102 | + except Exception as e: |
| 103 | + # Catch any other unexpected errors during flush/refresh/email/commit |
| 104 | + logger.error( |
| 105 | + f"Unexpected error during invitation creation/sending for {invitee_email} " |
| 106 | + f"in org {organization_id}: {e}", |
| 107 | + exc_info=True |
| 108 | + ) |
| 109 | + session.rollback() |
| 110 | + raise HTTPException(status_code=500, detail="An unexpected error occurred.") |
| 111 | + |
| 112 | + # Redirect back to organization page (PRG pattern) |
| 113 | + return RedirectResponse(url=f"/organizations/{organization_id}", status_code=303) |
0 commit comments