Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🚑️(teams) do not display add button when disallowed #676

Merged
merged 2 commits into from
Feb 4, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ and this project adheres to

### Fixed

- 🚑️(teams) do not display add button when disallowed #676
- 🚑️(plugins) fix name from SIRET specific case #674
- 🐛(api) restrict mailbox sync to enabled domains

Expand Down
2 changes: 1 addition & 1 deletion src/backend/core/api/client/viewsets.py
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,7 @@ class TeamViewSet(
):
"""Team ViewSet"""

permission_classes = [permissions.AccessPermission]
permission_classes = [permissions.TeamPermission, permissions.AccessPermission]
serializer_class = serializers.TeamSerializer
filter_backends = [filters.OrderingFilter]
ordering_fields = ["created_at", "name", "path"]
Expand Down
15 changes: 15 additions & 0 deletions src/backend/core/api/permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,3 +53,18 @@ def has_object_permission(self, request, view, obj):
"""Check permission for a given object."""
abilities = obj.get_abilities(request.user)
return abilities.get(request.method.lower(), False)


class TeamPermission(IsAuthenticated):
"""Permission class for team objects viewset."""

def has_permission(self, request, view):
"""Check permission only when the user tries to create a new team."""
if not super().has_permission(request, view):
return False

if request.method != "POST":
return True

abilities = request.user.get_abilities()
return abilities["teams"]["can_create"]
4 changes: 2 additions & 2 deletions src/backend/core/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -573,7 +573,7 @@ def get_abilities(self):
.get()
)

teams_can_view = user_info.teams_can_view
teams_can_view = user_info.teams_can_view or settings.FEATURES["TEAMS_DISPLAY"]
mailboxes_can_view = user_info.mailboxes_can_view

return {
Expand All @@ -585,7 +585,7 @@ def get_abilities(self):
),
},
"teams": {
"can_view": teams_can_view and settings.FEATURES["TEAMS_DISPLAY"],
"can_view": teams_can_view,
"can_create": teams_can_view and settings.FEATURES["TEAMS_CREATE"],
},
"mailboxes": {
Expand Down
41 changes: 40 additions & 1 deletion src/backend/core/tests/teams/test_core_api_teams_create.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from rest_framework.status import (
HTTP_201_CREATED,
HTTP_401_UNAUTHORIZED,
HTTP_403_FORBIDDEN,
)
from rest_framework.test import APIClient

Expand All @@ -28,7 +29,7 @@ def test_api_teams_create_anonymous():
assert not Team.objects.exists()


def test_api_teams_create_authenticated():
def test_api_teams_create_authenticated(settings):
"""
Authenticated users should be able to create teams and should automatically be declared
as the owner of the newly created team.
Expand All @@ -39,6 +40,14 @@ def test_api_teams_create_authenticated():
client = APIClient()
client.force_login(user)

settings.FEATURES = {
"TEAMS_DISPLAY": True,
"TEAMS_CREATE": True,
"CONTACTS_DISPLAY": False,
"CONTACTS_CREATE": False,
"MAILBOXES_CREATE": False,
}

response = client.post(
"/api/v1.0/teams/",
{
Expand All @@ -54,6 +63,36 @@ def test_api_teams_create_authenticated():
assert team.accesses.filter(role="owner", user=user).exists()


def test_api_teams_create_authenticated_feature_disabled(settings):
"""
Authenticated users should not be able to create teams when feature is disabled.
"""
organization = OrganizationFactory(with_registration_id=True)
user = UserFactory(organization=organization)

client = APIClient()
client.force_login(user)

settings.FEATURES = {
"TEAMS_DISPLAY": True,
"TEAMS_CREATE": False,
"CONTACTS_DISPLAY": False,
"CONTACTS_CREATE": False,
"MAILBOXES_CREATE": False,
}

response = client.post(
"/api/v1.0/teams/",
{
"name": "my team",
},
format="json",
)

assert response.status_code == HTTP_403_FORBIDDEN
assert not Team.objects.exists()


def test_api_teams_create_cannot_override_organization():
"""
Authenticated users should be able to create teams and not
Expand Down
11 changes: 9 additions & 2 deletions src/backend/core/tests/users/test_api_users_retrieve.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def test_api_users_retrieve_me_authenticated():
"abilities": {
"contacts": {"can_create": True, "can_view": True},
"mailboxes": {"can_create": False, "can_view": False},
"teams": {"can_create": False, "can_view": False},
"teams": {"can_create": True, "can_view": True},
},
"organization": {
"id": str(user.organization.pk),
Expand All @@ -66,11 +66,18 @@ def test_api_users_retrieve_me_authenticated():
}


def test_api_users_retrieve_me_authenticated_abilities():
def test_api_users_retrieve_me_authenticated_abilities(settings):
"""
Authenticated users should be able to retrieve their own user via the "/users/me" path
with the proper abilities.
"""
settings.FEATURES = {
"TEAMS_DISPLAY": False,
"TEAMS_CREATE": True,
"CONTACTS_DISPLAY": True,
"CONTACTS_CREATE": True,
"MAILBOXES_CREATE": True,
}
user = factories.UserFactory()

client = APIClient()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import fetchMock from 'fetch-mock';

import { useAuthStore } from '@/core/auth';
import { AppWrapper } from '@/tests/utils';

import { Panel } from '../components/Panel';
Expand All @@ -23,6 +24,19 @@ describe('PanelTeams', () => {
});

it('renders with no team to display', async () => {
useAuthStore.setState({
userData: {
id: '1',
email: '[email protected]',
name: 'Test User',
abilities: {
teams: { can_view: true, can_create: true },
mailboxes: { can_view: true },
contacts: { can_view: true },
},
},
});

fetchMock.mock(`end:/teams/?ordering=-created_at`, []);

render(<TeamList />, { wrapper: AppWrapper });
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { useTranslation } from 'react-i18next';
import IconAdd from '@/assets/icons/icon-add.svg';
import IconSort from '@/assets/icons/icon-sort.svg';
import { Box, BoxButton, StyledLink } from '@/components';
import { useAuthStore } from '@/core/auth';
import { useCunninghamTheme } from '@/cunningham';
import { TeamsOrdering } from '@/features/teams/team-management/api';

Expand All @@ -13,6 +14,9 @@ export const PanelActions = () => {
const { t } = useTranslation();
const { changeOrdering, ordering } = useTeamStore();
const { colorsTokens } = useCunninghamTheme();
const { userData } = useAuthStore();

const can_create = userData?.abilities?.teams.can_create ?? false;

const isSortAsc = ordering === TeamsOrdering.BY_CREATED_ON;

Expand Down Expand Up @@ -43,17 +47,19 @@ export const PanelActions = () => {
>
<IconSort width={30} height={30} aria-hidden="true" />
</BoxButton>
<StyledLink href="/teams/create">
<BoxButton
as="span"
$margin={{ all: 'auto' }}
aria-label={t('Add a team')}
$color={colorsTokens()['primary-600']}
tabIndex={-1}
>
<IconAdd width={27} height={27} aria-hidden="true" />
</BoxButton>
</StyledLink>
{can_create && (
<StyledLink href="/teams/create">
<BoxButton
as="span"
$margin={{ all: 'auto' }}
aria-label={t('Add a team')}
$color={colorsTokens()['primary-600']}
tabIndex={-1}
>
<IconAdd width={27} height={27} aria-hidden="true" />
</BoxButton>
</StyledLink>
)}
</Box>
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import React, { useRef } from 'react';
import { useTranslation } from 'react-i18next';

import { Box, Text } from '@/components';
import { useAuthStore } from '@/core/auth';
import { Team, useTeams } from '@/features/teams/team-management';

import { useTeamStore } from '../store';
Expand All @@ -17,6 +18,9 @@ interface PanelTeamsStateProps {

const TeamListState = ({ isLoading, isError, teams }: PanelTeamsStateProps) => {
const { t } = useTranslation();
const { userData } = useAuthStore();

const can_create = userData?.abilities?.teams.can_create ?? false;

if (isError) {
return (
Expand All @@ -42,11 +46,13 @@ const TeamListState = ({ isLoading, isError, teams }: PanelTeamsStateProps) => {
<Text as="p" $margin={{ vertical: 'none' }}>
{t('0 group to display.')}
</Text>
<Text as="p">
{t(
'Create your first team by clicking on the "Create a new team" button.',
)}
</Text>
{can_create && (
<Text as="p">
{t(
'Create your first team by clicking on the "Create a new team" button.',
)}
</Text>
)}
</Box>
);
}
Expand Down
13 changes: 11 additions & 2 deletions src/frontend/apps/e2e/__tests__/app-desk/config.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,18 @@ test.describe('Config', () => {
await page.goto('/');
await keyCloakSignIn(page, browserName, 'mail-member');

await expect(page.locator('menu')).toBeHidden();
await page
.locator('menu')
.first()
.getByLabel(`Mail Domains button`)
.click();
await expect(page).toHaveURL(/mail-domains\//);

await expect(page.getByText('Mail Domains')).toBeVisible();
await expect(
page
.getByLabel('Mail domains panel', { exact: true })
.getByText('Mail Domains'),
).toBeVisible();
});

test('it checks that the user abilities display teams', async ({
Expand Down
Loading