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

Make language choice peristent for users #1075

Draft
wants to merge 8 commits into
base: main
Choose a base branch
from
Draft
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
4 changes: 2 additions & 2 deletions .github/workflows/startup-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ jobs:
working-directory: ${{ env.frontend-directory }}
run: |
response=$(curl -d "username=admin@tests.com&password=1234" -H "Origin: https://localhost:8443" https://localhost:8443/login\?/login -k)
server_reponse='{"type":"redirect","status":302,"location":""}'
server_reponse='{"type":"redirect","status":302,"location":"/?refresh=1"}'
if [[ "$response" == "$server_reponse" ]]; then
echo "Success"
exit 0
Expand Down Expand Up @@ -264,7 +264,7 @@ jobs:
working-directory: ${{ env.frontend-directory }}
run: |
response=$(curl -d "username=admin@tests.com&password=1234" -H "Origin: https://localhost:8443" https://localhost:8443/login\?/login -k)
server_reponse='{"type":"redirect","status":302,"location":""}'
server_reponse='{"type":"redirect","status":302,"location":"/?refresh=1"}'
if [[ "$response" == "$server_reponse" ]]; then
echo "Success"
exit 0
Expand Down
1 change: 1 addition & 0 deletions backend/core/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@
path("iam/", include("iam.urls")),
path("serdes/", include("serdes.urls")),
path("settings/", include("global_settings.urls")),
path("user-preferences/", UserPreferencesView.as_view(), name="user-preferences"),
path("csrf/", get_csrf_token, name="get_csrf_token"),
path("build/", get_build, name="get_build"),
path("evidences/<uuid:pk>/upload/", UploadAttachmentView.as_view(), name="upload"),
Expand Down
41 changes: 32 additions & 9 deletions backend/core/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@
from rest_framework.renderers import JSONRenderer
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.status import HTTP_400_BAD_REQUEST, HTTP_403_FORBIDDEN
from rest_framework.utils.serializer_helpers import ReturnDict
from rest_framework.views import APIView

Expand Down Expand Up @@ -268,7 +267,7 @@ def quality_check_detail(self, request, pk):
}
return Response(res)
else:
return Response(status=HTTP_403_FORBIDDEN)
return Response(status=status.HTTP_403_FORBIDDEN)


class ThreatViewSet(BaseModelViewSet):
Expand Down Expand Up @@ -541,7 +540,7 @@ def quality_check_detail(self, request, pk):
risk_assessment = self.get_object()
return Response(risk_assessment.quality_check())
else:
return Response(status=HTTP_403_FORBIDDEN)
return Response(status=status.HTTP_403_FORBIDDEN)

@action(detail=True, methods=["get"], name="Get treatment plan data")
def plan(self, request, pk):
Expand Down Expand Up @@ -574,7 +573,7 @@ def plan(self, request, pk):
return Response(risk_assessment)

else:
return Response(status=HTTP_403_FORBIDDEN)
return Response(status=status.HTTP_403_FORBIDDEN)

@action(detail=True, name="Get treatment plan CSV")
def treatment_plan_csv(self, request, pk):
Expand Down Expand Up @@ -634,7 +633,9 @@ def treatment_plan_csv(self, request, pk):

return response
else:
return Response({"error": "Permission denied"}, status=HTTP_403_FORBIDDEN)
return Response(
{"error": "Permission denied"}, status=status.HTTP_403_FORBIDDEN
)

@action(detail=True, name="Get risk assessment CSV")
def risk_assessment_csv(self, request, pk):
Expand Down Expand Up @@ -680,7 +681,9 @@ def risk_assessment_csv(self, request, pk):

return response
else:
return Response({"error": "Permission denied"}, status=HTTP_403_FORBIDDEN)
return Response(
{"error": "Permission denied"}, status=status.HTTP_403_FORBIDDEN
)

@action(detail=True, name="Get risk assessment PDF")
def risk_assessment_pdf(self, request, pk):
Expand Down Expand Up @@ -1193,7 +1196,7 @@ def update(self, request, *args, **kwargs):
_data = {
"non_field_errors": "The justification can only be edited by the approver"
}
return Response(data=_data, status=HTTP_400_BAD_REQUEST)
return Response(data=_data, status=status.HTTP_400_BAD_REQUEST)
else:
return super().update(request, *args, **kwargs)

Expand Down Expand Up @@ -1305,7 +1308,7 @@ def update(self, request: Request, *args, **kwargs) -> Response:
if str(admin_group.pk) not in new_user_groups:
return Response(
{"error": "attemptToRemoveOnlyAdminUserGroup"},
status=HTTP_403_FORBIDDEN,
status=status.HTTP_403_FORBIDDEN,
)

return super().update(request, *args, **kwargs)
Expand All @@ -1317,7 +1320,7 @@ def destroy(self, request, *args, **kwargs):
if number_of_admin_users == 1:
return Response(
{"error": "attemptToDeleteOnlyAdminAccountError"},
status=HTTP_403_FORBIDDEN,
status=status.HTTP_403_FORBIDDEN,
)

return super().destroy(request, *args, **kwargs)
Expand Down Expand Up @@ -1532,6 +1535,26 @@ def my_assignments(self, request):
)


class UserPreferencesView(APIView):
permission_classes = [permissions.IsAuthenticated]

def get(self, request) -> Response:
return Response(request.user.preferences, status=status.HTTP_200_OK)

def patch(self, request) -> Response:
new_language = request.data.get("lang")
if new_language is None or new_language not in (
lang[0] for lang in settings.LANGUAGES
):
return Response(
{"error": "This language doesn't exist."},
status=status.HTTP_400_BAD_REQUEST,
)
request.user.preferences["lang"] = new_language
request.user.save()
return Response({}, status=status.HTTP_200_OK)


@cache_page(60 * SHORT_CACHE_TTL)
@vary_on_cookie
@api_view(["GET"])
Expand Down
17 changes: 17 additions & 0 deletions backend/iam/migrations/0009_user_preferences.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Generated by Django 5.1.1 on 2024-11-22 01:25

from django.db import migrations, models


class Migration(migrations.Migration):
dependencies = [
("iam", "0008_user_is_third_party"),
]

operations = [
migrations.AddField(
model_name="user",
name="preferences",
field=models.JSONField(default=dict),
),
]
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def create_emailaddress_objects(apps, schema_editor):

class Migration(migrations.Migration):
dependencies = [
("iam", "0008_user_is_third_party"),
("iam", "0009_user_preferences"),
]

operations = [
Expand Down
1 change: 1 addition & 0 deletions backend/iam/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,7 @@ class User(AbstractBaseUser, AbstractBaseModel, FolderMixin):
first_name = models.CharField(_("first name"), max_length=150, blank=True)
email = models.CharField(max_length=100, unique=True)
first_login = models.BooleanField(default=True)
preferences = models.JSONField(default=dict)
is_sso = models.BooleanField(default=False)
is_third_party = models.BooleanField(default=False)
is_active = models.BooleanField(
Expand Down
1 change: 1 addition & 0 deletions backend/iam/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ def post(self, request) -> Response:


class CurrentUserView(views.APIView):
# Is this condition really necessary if we have permission_classes = [permissions.IsAuthenticated] ?
permission_classes = [permissions.IsAuthenticated]

def get(self, request) -> Response:
Expand Down
6 changes: 6 additions & 0 deletions enterprise/frontend/src/routes/+layout.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import '../app.postcss';
import '@fortawesome/fontawesome-free/css/all.min.css';
import ParaglideSvelte from './ParaglideJsProvider.svelte';
import { browser } from '$app/environment';

import { computePosition, autoUpdate, offset, shift, flip, arrow } from '@floating-ui/dom';

Expand Down Expand Up @@ -97,6 +98,11 @@
? `data:${$faviconB64.mimeType};base64, ${$faviconB64.data}`
: favicon;
});

$: if (browser && $page.url.searchParams.has('refresh')) {
$page.url.searchParams.delete('refresh');
window.location.href = $page.url.href;
}
</script>

<svelte:head>
Expand Down
6 changes: 6 additions & 0 deletions frontend/src/lib/components/SideBar/SideBarFooter.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,12 @@
event.preventDefault();
value = event?.target?.value;
setLanguageTag(value);
fetch('/api/user-preferences', {
method: 'PATCH',
body: JSON.stringify({
lang: value
})
});
// sessionStorage.setItem('lang', value);
setCookie('ciso_lang', value);
window.location.reload();
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/lib/utils/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ export function formatScoreValue(value: number, max_score: number, fullDonut = f
}

export function getSecureRedirect(url: any): string {
const SECURE_REDIRECT_URL_REGEX = /^\/\w+/;
const SECURE_REDIRECT_URL_REGEX = /^\/\w*/;
return typeof url === 'string' && SECURE_REDIRECT_URL_REGEX.test(url) ? url : '';
}

Expand Down
2 changes: 1 addition & 1 deletion frontend/src/routes/(app)/+page.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@ import { redirect } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';

export const load: PageServerLoad = async () => {
redirect(301, '/analytics');
redirect(301, '/analytics?refresh=1');
};
20 changes: 17 additions & 3 deletions frontend/src/routes/(authentication)/login/+page.server.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
import { getSecureRedirect } from '$lib/utils/helpers';

import { ALLAUTH_API_URL, BASE_API_URL } from '$lib/utils/constants';
import { csrfToken } from '$lib/utils/csrf';
import { loginSchema } from '$lib/utils/schemas';
import type { LoginRequestBody } from '$lib/utils/types';
import { fail, redirect, type Actions } from '@sveltejs/kit';
import { setError, superValidate } from 'sveltekit-superforms';
import { zod } from 'sveltekit-superforms/adapters';
import type { PageServerLoad } from './$types';
import { mfaAuthenticateSchema } from './mfa/utils/schemas';
import { setFlash } from 'sveltekit-flash-message/server';

interface AuthenticationFlow {
id:
Expand Down Expand Up @@ -117,8 +115,24 @@ export const actions: Actions = {
secure: true
});

const preferencesRes = await fetch(`${BASE_API_URL}/user-preferences/`);
const preferences = await preferencesRes.json();

const currentLang = cookies.get('ciso_lang') || 'en';
const preferedLang = preferences.lang;

if (preferedLang && currentLang !== preferedLang) {
cookies.set('ciso_lang', preferedLang, {
httpOnly: false,
sameSite: 'lax',
path: '/',
secure: true
});
}

const next = url.searchParams.get('next') || '/';
redirect(302, getSecureRedirect(next));
const redirectURL = getSecureRedirect(next) + '?refresh=1';
redirect(302, redirectURL);
},
mfaAuthenticate: async (event) => {
const formData = await event.request.formData();
Expand Down
7 changes: 6 additions & 1 deletion frontend/src/routes/+layout.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// Most of your app wide CSS should be put in this file
import '../app.postcss';
import '@fortawesome/fontawesome-free/css/all.min.css';
import ParaglideSvelte from './ParaglideJsProvider.svelte';
import { browser } from '$app/environment';

import { computePosition, autoUpdate, offset, shift, flip, arrow } from '@floating-ui/dom';

Expand Down Expand Up @@ -77,6 +77,11 @@
createModal: { ref: CreateModal },
deleteConfirmModal: { ref: DeleteConfirmModal }
};

$: if (browser && $page.url.searchParams.has('refresh')) {
$page.url.searchParams.delete('refresh');
window.location.href = $page.url.href;
}
</script>

<svelte:head><link rel="icon" href="/favicon.ico" /></svelte:head>
Expand Down
36 changes: 36 additions & 0 deletions frontend/src/routes/api/user-preferences/+server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { BASE_API_URL } from '$lib/utils/constants';
import type { RequestHandler } from './$types';

export const GET: RequestHandler = async ({ fetch, request }) => {
const endpoint = `${BASE_API_URL}/user-preferences/`;
const req = await fetch(endpoint);
const status = await req.status;
const responseData = await req.json();

return new Response(JSON.stringify(responseData), {
status: status,
headers: {
'Content-Type': 'application/json'
}
});
};

export const PATCH: RequestHandler = async ({ fetch, request }) => {
const newPreferences = await request.json();
const requestInitOptions: RequestInit = {
method: 'PATCH',
body: JSON.stringify(newPreferences)
};

const endpoint = `${BASE_API_URL}/user-preferences/`;
const req = await fetch(endpoint, requestInitOptions);
const status = await req.status;
const responseData = await req.text();

return new Response(responseData, {
status: status,
headers: {
'Content-Type': 'application/json'
}
});
};
4 changes: 2 additions & 2 deletions frontend/tests/functional/startup.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ test('startup tests', async ({ loginPage, analyticsPage, page }) => {
await page.goto('/');
await loginPage.hasUrl(1);
await loginPage.login();
await analyticsPage.hasUrl();
await analyticsPage.hasUrl(false);
});

await test.step('proper redirection to the analytics page after login', async () => {
await analyticsPage.hasUrl();
await analyticsPage.hasUrl(false);
await analyticsPage.hasTitle();
});
});
23 changes: 21 additions & 2 deletions frontend/tests/utils/base-page.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
import { expect, type Locator, type Page } from './test-utils.js';

/**
* Escape the characters of `string` to safely insert it in a regex.
*
* @param {string} string - The string to escape.
* @returns {string} The escaped string.
*/
function escapeRegex(string: string): string {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

export abstract class BasePage {
readonly url: string;
readonly name: string | RegExp;
Expand All @@ -20,7 +30,7 @@
}

async goto() {
await this.page.goto(this.url);

Check failure on line 33 in frontend/tests/utils/base-page.ts

View workflow job for this annotation

GitHub Actions / functional-tests (3.11, chromium)

[chromium] › functional/detailed/common.test.ts:72:4 › Tests on domains item › Tests on domains item details › Domains item details are showing properly

1) [chromium] › functional/detailed/common.test.ts:72:4 › Tests on domains item › Tests on domains item details › Domains item details are showing properly Error: page.goto: net::ERR_ABORTED at http://localhost:4173/folders Call log: - navigating to "http://localhost:4173/folders", waiting until "load" at utils/base-page.ts:33 31 | 32 | async goto() { > 33 | await this.page.goto(this.url); | ^ 34 | await this.page.waitForURL(this.url); 35 | } 36 | at PageContent.goto (/home/runner/work/ciso-assistant-community/ciso-assistant-community/frontend/tests/utils/base-page.ts:33:19) at /home/runner/work/ciso-assistant-community/ciso-assistant-community/frontend/tests/functional/detailed/common.test.ts:35:22

Check failure on line 33 in frontend/tests/utils/base-page.ts

View workflow job for this annotation

GitHub Actions / functional-tests (3.11, chromium)

[chromium] › functional/detailed/common.test.ts:72:4 › Tests on domains item › Tests on domains item details › Domains item details are showing properly

1) [chromium] › functional/detailed/common.test.ts:72:4 › Tests on domains item › Tests on domains item details › Domains item details are showing properly Retry #1 ─────────────────────────────────────────────────────────────────────────────────────── Error: page.goto: net::ERR_ABORTED at http://localhost:4173/folders Call log: - navigating to "http://localhost:4173/folders", waiting until "load" at utils/base-page.ts:33 31 | 32 | async goto() { > 33 | await this.page.goto(this.url); | ^ 34 | await this.page.waitForURL(this.url); 35 | } 36 | at PageContent.goto (/home/runner/work/ciso-assistant-community/ciso-assistant-community/frontend/tests/utils/base-page.ts:33:19) at /home/runner/work/ciso-assistant-community/ciso-assistant-community/frontend/tests/functional/detailed/common.test.ts:35:22

Check failure on line 33 in frontend/tests/utils/base-page.ts

View workflow job for this annotation

GitHub Actions / functional-tests (3.11, chromium)

[chromium] › functional/detailed/compliance-assessments.test.ts:8:1 › compliance assessments scoring is working properly

2) [chromium] › functional/detailed/compliance-assessments.test.ts:8:1 › compliance assessments scoring is working properly Error: page.goto: net::ERR_ABORTED at http://localhost:4173/folders Call log: - navigating to "http://localhost:4173/folders", waiting until "load" at utils/base-page.ts:33 31 | 32 | async goto() { > 33 | await this.page.goto(this.url); | ^ 34 | await this.page.waitForURL(this.url); 35 | } 36 | at PageContent.goto (/home/runner/work/ciso-assistant-community/ciso-assistant-community/frontend/tests/utils/base-page.ts:33:19) at /home/runner/work/ciso-assistant-community/ciso-assistant-community/frontend/tests/functional/detailed/compliance-assessments.test.ts:40:22

Check failure on line 33 in frontend/tests/utils/base-page.ts

View workflow job for this annotation

GitHub Actions / functional-tests (3.11, chromium)

[chromium] › functional/detailed/compliance-assessments.test.ts:8:1 › compliance assessments scoring is working properly

2) [chromium] › functional/detailed/compliance-assessments.test.ts:8:1 › compliance assessments scoring is working properly Error: page.goto: net::ERR_ABORTED at http://localhost:4173/folders Call log: - navigating to "http://localhost:4173/folders", waiting until "load" at utils/base-page.ts:33 31 | 32 | async goto() { > 33 | await this.page.goto(this.url); | ^ 34 | await this.page.waitForURL(this.url); 35 | } 36 | at PageContent.goto (/home/runner/work/ciso-assistant-community/ciso-assistant-community/frontend/tests/utils/base-page.ts:33:19) at /home/runner/work/ciso-assistant-community/ciso-assistant-community/frontend/tests/functional/detailed/compliance-assessments.test.ts:210:20

Check failure on line 33 in frontend/tests/utils/base-page.ts

View workflow job for this annotation

GitHub Actions / functional-tests (3.11, chromium)

[chromium] › functional/detailed/compliance-assessments.test.ts:8:1 › compliance assessments scoring is working properly

2) [chromium] › functional/detailed/compliance-assessments.test.ts:8:1 › compliance assessments scoring is working properly Retry #1 ─────────────────────────────────────────────────────────────────────────────────────── Error: page.goto: net::ERR_ABORTED at http://localhost:4173/folders Call log: - navigating to "http://localhost:4173/folders", waiting until "load" at utils/base-page.ts:33 31 | 32 | async goto() { > 33 | await this.page.goto(this.url); | ^ 34 | await this.page.waitForURL(this.url); 35 | } 36 | at PageContent.goto (/home/runner/work/ciso-assistant-community/ciso-assistant-community/frontend/tests/utils/base-page.ts:33:19) at /home/runner/work/ciso-assistant-community/ciso-assistant-community/frontend/tests/functional/detailed/compliance-assessments.test.ts:40:22

Check failure on line 33 in frontend/tests/utils/base-page.ts

View workflow job for this annotation

GitHub Actions / functional-tests (3.11, chromium)

[chromium] › functional/detailed/compliance-assessments.test.ts:8:1 › compliance assessments scoring is working properly

2) [chromium] › functional/detailed/compliance-assessments.test.ts:8:1 › compliance assessments scoring is working properly Retry #1 ─────────────────────────────────────────────────────────────────────────────────────── Error: page.goto: net::ERR_ABORTED at http://localhost:4173/folders Call log: - navigating to "http://localhost:4173/folders", waiting until "load" at utils/base-page.ts:33 31 | 32 | async goto() { > 33 | await this.page.goto(this.url); | ^ 34 | await this.page.waitForURL(this.url); 35 | } 36 | at PageContent.goto (/home/runner/work/ciso-assistant-community/ciso-assistant-community/frontend/tests/utils/base-page.ts:33:19) at /home/runner/work/ciso-assistant-community/ciso-assistant-community/frontend/tests/functional/detailed/compliance-assessments.test.ts:210:20

Check failure on line 33 in frontend/tests/utils/base-page.ts

View workflow job for this annotation

GitHub Actions / functional-tests (3.11, chromium)

[chromium] › functional/detailed/libraries.test.ts:4:1 › every library can be loaded

3) [chromium] › functional/detailed/libraries.test.ts:4:1 › every library can be loaded ────────── Error: page.goto: net::ERR_ABORTED at http://localhost:4173/libraries Call log: - navigating to "http://localhost:4173/libraries", waiting until "load" at utils/base-page.ts:33 31 | 32 | async goto() { > 33 | await this.page.goto(this.url); | ^ 34 | await this.page.waitForURL(this.url); 35 | } 36 | at PageContent.goto (/home/runner/work/ciso-assistant-community/ciso-assistant-community/frontend/tests/utils/base-page.ts:33:19) at /home/runner/work/ciso-assistant-community/ciso-assistant-community/frontend/tests/functional/detailed/libraries.test.ts:7:22

Check failure on line 33 in frontend/tests/utils/base-page.ts

View workflow job for this annotation

GitHub Actions / functional-tests (3.11, chromium)

[chromium] › functional/detailed/libraries.test.ts:4:1 › every library can be loaded

3) [chromium] › functional/detailed/libraries.test.ts:4:1 › every library can be loaded ────────── Retry #1 ─────────────────────────────────────────────────────────────────────────────────────── Error: page.goto: net::ERR_ABORTED at http://localhost:4173/libraries Call log: - navigating to "http://localhost:4173/libraries", waiting until "load" at utils/base-page.ts:33 31 | 32 | async goto() { > 33 | await this.page.goto(this.url); | ^ 34 | await this.page.waitForURL(this.url); 35 | } 36 | at PageContent.goto (/home/runner/work/ciso-assistant-community/ciso-assistant-community/frontend/tests/utils/base-page.ts:33:19) at /home/runner/work/ciso-assistant-community/ciso-assistant-community/frontend/tests/functional/detailed/libraries.test.ts:7:22
await this.page.waitForURL(this.url);
}

Expand All @@ -28,8 +38,17 @@
await expect.soft(this.pageTitle).toHaveText(title);
}

async hasUrl() {
await expect(this.page).toHaveURL(this.url);
/**
* Check whether the browser's URL match the `this.url` value.
*
* @param {boolean} [strict=true] - Determines the URL matching mode.
* If `strict` is `true`, the function checks if `this.url` is strictly equal to the browser's URL.
* Otherwise, it checks if the browser's URL starts with `this.url`.
* @returns {void}
*/
async hasUrl(strict: boolean = true) {
const URLPattern = strict ? this.url : new RegExp(escapeRegex(this.url) + '.*');
await expect(this.page).toHaveURL(URLPattern);
}

async hasBreadcrumbPath(paths: (string | RegExp)[], fullPath = true, origin = 'Home') {
Expand Down
Loading