Skip to content

Commit

Permalink
feat: add likelihood endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
Mohamed-Hacene committed Dec 6, 2024
1 parent ddc753f commit 0b7112b
Show file tree
Hide file tree
Showing 6 changed files with 67 additions and 16 deletions.
13 changes: 13 additions & 0 deletions backend/ebios_rm/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,10 @@ class Meta:
verbose_name_plural = _("Ebios RM Studies")
ordering = ["created_at"]

@property
def parsed_matrix(self):
return self.risk_matrix.parse_json_translated()


class FearedEvent(NameDescriptionMixin, FolderMixin):
ebios_rm_study = models.ForeignKey(
Expand Down Expand Up @@ -210,6 +214,7 @@ class Meta:
verbose_name = _("RO/TO couple")
verbose_name_plural = _("RO/TO couples")
ordering = ["created_at"]


def save(self, *args, **kwargs):
self.folder = self.ebios_rm_study.folder
Expand Down Expand Up @@ -396,3 +401,11 @@ class Meta:
def save(self, *args, **kwargs):
self.folder = self.ebios_rm_study.folder
super().save(*args, **kwargs)

@property
def risk_matrix(self):
return self.ebios_rm_study.risk_matrix

@property
def parsed_matrix(self):
return self.risk_matrix.parse_json_translated()
34 changes: 34 additions & 0 deletions backend/ebios_rm/views.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from core.views import BaseModelViewSet as AbstractBaseModelViewSet
from core.serializers import RiskMatrixReadSerializer
from .models import (
EbiosRMStudy,
FearedEvent,
Expand Down Expand Up @@ -31,6 +32,20 @@ class EbiosRMStudyViewSet(BaseModelViewSet):
def status(self, request):
return Response(dict(EbiosRMStudy.Status.choices))

@method_decorator(cache_page(60 * LONG_CACHE_TTL))
@action(detail=True, name="Get likelihood choices")
def likelihood(self, request, pk):
ebios_rm_study: EbiosRMStudy = self.get_object()
undefined = dict([(-1, "--")])
_choices = dict(
zip(
list(range(0, 64)),
[x["name"] for x in ebios_rm_study.parsed_matrix["probability"]],
)
)
choices = undefined | _choices
return Response(choices)


class FearedEventViewSet(BaseModelViewSet):
model = FearedEvent
Expand Down Expand Up @@ -82,3 +97,22 @@ class OperationalScenarioViewSet(BaseModelViewSet):
filterset_fields = [
"ebios_rm_study",
]

@action(detail=True, name="Get risk matrix", url_path="risk-matrix")
def risk_matrix(self, request, pk=None):
attack_path = self.get_object()
return Response(RiskMatrixReadSerializer(attack_path.risk_matrix).data)

@method_decorator(cache_page(60 * LONG_CACHE_TTL))
@action(detail=True, name="Get likelihood choices")
def likelihood(self, request, pk):
attack_path: AttackPath = self.get_object()
undefined = dict([(-1, "--")])
_choices = dict(
zip(
list(range(0, 64)),
[x["name"] for x in attack_path.parsed_matrix["probability"]],
)
)
choices = undefined | _choices
return Response(choices)
5 changes: 3 additions & 2 deletions frontend/messages/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -384,7 +384,7 @@
"exportDatabase": "Export database",
"upload": "Upload",
"add": "Add",
"undefined": "undefined",
"undefined": "--",
"production": "Production",
"design": "Design",
"development": "Development",
Expand Down Expand Up @@ -937,5 +937,6 @@
"resources": "Resources",
"pertinence": "Pertinence",
"isSelected": "Is selected",
"attackPaths": "Attack paths"
"attackPaths": "Attack paths",
"likelihood": "Likelihood"
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import * as m from '$paraglide/messages.js';
import { getOptions } from '$lib/utils/crud';
import TextArea from '../TextArea.svelte';
import Select from '../Select.svelte';
export let form: SuperValidated<any>;
export let model: ModelInfo;
Expand Down Expand Up @@ -46,13 +47,14 @@
field="attack_paths"
label={m.attackPaths()}
/>
<!-- <Select
{form}
options={data.impactChoices}
color_map={impactColorMap}
field="residual_impact"
label={m.residualImpact()}
/> -->
<Select
{form}
options={model.selectOptions['likelihood']}
field="likelihood"
label={m.likelihood()}
cacheLock={cacheLocks['likelihood']}
bind:cachedValue={formDataCache['likelihood']}
/>
<Checkbox {form} field="is_selected" label={m.isSelected()} />
<TextArea
{form}
Expand Down
3 changes: 3 additions & 0 deletions frontend/src/lib/utils/crud.ts
Original file line number Diff line number Diff line change
Expand Up @@ -659,6 +659,9 @@ export const URL_MODEL_MAP: ModelMap = {
{ field: 'ebios_rm_study', urlModel: 'ebios-rm' },
{ field: 'threats', urlModel: 'threats' },
{ field: 'attack_paths', urlModel: 'attack_paths' }
],
selectFields: [
{ field: 'likelihood' }
]
}
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ export const load: PageServerLoad = async ({ params, fetch }) => {

const foreignKeys: Record<string, any> = {};

const endpoint = `${BASE_API_URL}/${model.endpointUrl}?ebios_rm_study=${params.id}`;
const res = await fetch(endpoint);
const data = await res.json().then((res) => res.results);

for (const keyField of foreignKeyFields) {
const keyModel = getModelInfo(keyField.urlModel);
const queryParams = keyField.urlParams ? `?${keyField.urlParams}` : '';
Expand All @@ -50,9 +54,7 @@ export const load: PageServerLoad = async ({ params, fetch }) => {

for (const selectField of selectFields) {
if (selectField.detail) continue;
const url = model.endpointUrl
? `${BASE_API_URL}/${model.endpointUrl}/${selectField.field}/`
: `${BASE_API_URL}/${model.urlModel}/${selectField.field}/`;
const url = `${BASE_API_URL}/ebios-rm/studies/${params.id}/${selectField.field}/`
const response = await fetch(url);
if (response.ok) {
selectOptions[selectField.field] = await response.json().then((data) =>
Expand All @@ -68,10 +70,6 @@ export const load: PageServerLoad = async ({ params, fetch }) => {

model['selectOptions'] = selectOptions;

const endpoint = `${BASE_API_URL}/${model.endpointUrl}?ebios_rm_study=${params.id}`;
const res = await fetch(endpoint);
const data = await res.json().then((res) => res.results);

const bodyData = tableSourceMapper(data, listViewFields[URLModel as urlModel].body);

const headData: Record<string, string> = listViewFields[URLModel as urlModel].body.reduce(
Expand Down

0 comments on commit 0b7112b

Please sign in to comment.