Example #1
0
def update_member_role(
        organization_id: int,
        user_id: int,
        *,
        role: str = Body(..., embed=True),
        auth=Depends(authorization("organizations:edit_member")),
        db: Session = Depends(get_db),
        current_user: User = Depends(get_current_user),
):
    roles_order = [
        "admin", "owner", "manager", "contributor", "reader", "guest"
    ]

    if role not in roles_order:
        raise HTTPException(status_code=400,
                            detail=f"This role : {role} does not exist")

    user_in_db = user.get(db, id=user_id)

    if not user_in_db:
        raise HTTPException(status_code=404, detail="User not found")

    # Convert to sqlalchemy obj to UserOut schema for hidding password
    user_in_db = UserOut(**user_in_db.as_dict())

    current_user_roles = enforcer.get_roles_for_user_in_domain(
        str(current_user.id), str(organization_id))

    if len(current_user_roles) > 0:
        current_user_role = current_user_roles[0]

    if roles_order.index(current_user_role) >= roles_order.index(role):
        raise HTTPException(status_code=403,
                            detail="You can only set roles below yours")

    user_roles = enforcer.get_roles_for_user_in_domain(str(user_id),
                                                       str(organization_id))

    # Role exist for this user (it's a patch)
    if len(user_roles) > 0:
        user_role = user_roles[0]
        if roles_order.index(current_user_role) >= roles_order.index(
                user_role):
            raise HTTPException(status_code=403,
                                detail="You can't edit a role above yours")

        enforcer.delete_roles_for_user_in_domain(str(user_id), user_role,
                                                 str(organization_id))
        enforcer.add_role_for_user_in_domain(str(user_id), role,
                                             str(organization_id))
        # need ro reload handle new policy
        enforcer.load_policy()

    return dict(user_in_db, role=role)
Example #2
0
def remove_team(
        organization_id: int,
        team_id: int,
        *,
        auth=Depends(authorization("organizations:delete_team")),
        db: Session = Depends(get_db),
        current_user: User = Depends(get_current_user),
):
    """
    delete one team and its members by id
    """
    organization_in_db = organization.get(db, id=team_id)

    if not organization_in_db:
        raise HTTPException(status_code=404, detail="Team not found")

    try:
        members_in_db = crud.organization.get_members(db, id=team_id)

        for member in members_in_db:
            current_roles = enforcer.get_roles_for_user_in_domain(
                str(member["id"]), str(team_id))

            for current_role in current_roles:
                enforcer.delete_roles_for_user_in_domain(
                    str(member["id"]), current_role, str(team_id))
    except Exception as e:
        logging.error(e)
        return False
    organization.remove(db, id=team_id)
    return True
Example #3
0
def delete_teams(
        organization_id: int,
        *,
        auth=Depends(authorization("organizations:delete_team")),
        db: Session = Depends(get_db),
        current_user: User = Depends(get_current_user),
        team_ids_in: List[int],
):
    """
    bulk delete teams and their members
    """
    teams_out = []
    for team_id in team_ids_in:
        organization_in_db = organization.get(db, id=team_id)

        if not organization_in_db:
            raise HTTPException(status_code=404, detail="Team not found")

        try:
            members_in_db = crud.organization.get_members(db, id=team_id)

            for member in members_in_db:
                current_roles = enforcer.get_roles_for_user_in_domain(
                    str(member["id"]), str(team_id))

                for current_role in current_roles:
                    enforcer.delete_roles_for_user_in_domain(
                        str(member["id"]), current_role, str(team_id))
        except Exception as e:
            logging.error(e)
        organization.remove(db, id=team_id)
        teams_out.append(dict(organization_in_db.as_dict()))

    return teams_out
Example #4
0
def get_one(
    organization_id: Union[str, int],
    *,
    auth=Depends(permissive_authorization("organizations:get_one")),
    current_user: User = Depends(get_optional_current_active_user),
    db: Session = Depends(get_db)
) -> Optional[Organization]:
    """
    get one organization by id
    """

    organization_in_db = crud.organization.get_by_id_or_slug(
        db, id=organization_id)

    if not organization_in_db:
        raise HTTPException(status_code=404, detail="Organization not found")

    organization = organization_in_db.to_schema()

    if current_user:
        current_roles = enforcer.get_roles_for_user_in_domain(
            str(current_user.id), str(organization_in_db.id))
        if len(current_roles) > 0:
            organization.current_user_role = current_roles[0]
        if current_user.is_superuser:
            organization.current_user_role = 'admin'

    return organization
Example #5
0
def get_organization_root_nodes(
    *,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
) -> Optional[List[Organization]]:
    """
    **Admin only**; Get all organizations trees root nodes;
    """
    if not current_user.is_superuser:
        raise HTTPException(
            status_code=403,
            detail="You are not authorized to perform this action.")

    root_nodes_in_db = crud.organization.get_root_nodes(db)
    root_nodes = []
    for org_in_db in root_nodes_in_db:
        current_roles = enforcer.get_roles_for_user_in_domain(
            str(current_user.id), str(org_in_db.id))
        org = org_in_db.to_schema()
        if len(current_roles) > 0:
            org.current_user_role = current_roles[0]
            root_nodes.append(org)
        else:
            root_nodes.append(org)
    return root_nodes
Example #6
0
def create_organization_root_node(
    *,
    db: Session = Depends(get_db),
    organization_in: OrganizationCreateRoot,
    current_user: User = Depends(get_current_user),
) -> Optional[Organization]:
    """
    Create a new **root node for organizations tree**;
    
    If `owner_email` is present organization tree ownership will be affected to *existing or newly created user*,
    else organizations tree ownership will be affected to *superuser*.
    """
    if not current_user.is_superuser:
        raise HTTPException(
            status_code=403,
            detail="You are not authorized to perform this action.")
    new_organization_root_node = organization.create_root(
        db, obj_in=organization_in).to_schema()
    if organization_in.owner_email:
        user_in_db = user.get_by_email(db, email=organization_in.owner_email)
        if not user_in_db:
            user_in_db = user.create(
                db,
                obj_in=UserCreate(
                    full_name=organization_in.owner_email.split("@")[0],
                    email=organization_in.owner_email,
                    password=pwd.genword(),
                ),
            )
        if new_organization_root_node:
            send_new_invitation_email_task.delay(
                full_name=user_in_db.full_name,
                email_to=user_in_db.email,
                organization=new_organization_root_node.name,
                role="owner")
            enforcer.add_role_for_user_in_domain(
                str(user_in_db.id), "owner",
                str(new_organization_root_node.id))
            enforcer.load_policy()
    else:
        enforcer.add_role_for_user_in_domain(
            str(current_user.id), "owner", str(new_organization_root_node.id))
        enforcer.load_policy()
    current_roles = enforcer.get_roles_for_user_in_domain(
        str(current_user.id), str(new_organization_root_node.id))
    if len(current_roles) > 0:
        new_organization_root_node.current_user_role = current_roles[0]
    if current_user.is_superuser:
        new_organization_root_node.current_user_role = 'admin'
    # new_organization_root_node.current_user_role = current_roles[0]
    return new_organization_root_node
Example #7
0
def remove_member(
        organization_id: int,
        user_id: int,
        *,
        auth=Depends(authorization("organizations:remove_member")),
        db: Session = Depends(get_db),
        current_user: User = Depends(get_current_user),
):
    user_in_db = user.get(db, id=user_id)

    if not user_in_db:
        raise HTTPException(status_code=404, detail="User not found")

    current_roles = enforcer.get_roles_for_user_in_domain(
        str(user_id), str(organization_id))

    for current_role in current_roles:
        enforcer.delete_roles_for_user_in_domain(str(user_id), current_role,
                                                 str(organization_id))

    return True
Example #8
0
def init_db(db: Session) -> None:
    # Tables should be created with Alembic migrations
    # But if you don't want to use migrations, create
    # the tables un-commenting the next line
    # Base.metadata.create_all(bind=engine)

    # insert_organizations(db=db)

    organization_in_db = organization.get_by_name(db,
                                                  name=settings.ORGANIZATION)

    if not organization_in_db:
        organization_in = OrganizationCreate(name=settings.ORGANIZATION,
                                             slug=slug.slug(
                                                 settings.ORGANIZATION),
                                             mode="private")
        organization_in_db = organization.create(db, obj_in=organization_in)

    user_in_db = user.get_by_email(db, email=settings.FIRST_SUPERUSER)

    if not user_in_db:
        user_in = UserCreate(
            full_name=settings.FIRST_SUPERUSER_FULLNAME,
            email=settings.FIRST_SUPERUSER,
            password=settings.FIRST_SUPERUSER_PASSWORD,
        )

        user_in_db = user.create(db, obj_in=user_in)  # noqa: F841
        user_in_db.is_superuser = True
        user_in_db.is_verified = True
        db.add(user_in_db)
        db.commit()
        db.refresh(user_in_db)

    if len(enforcer.get_roles_for_user_in_domain("1", "1")) == 0:
        enforcer.add_role_for_user_in_domain("1", "admin", "1")