Skip to content

Commit

Permalink
[backend/frontend] prevent_default_groups in user input
Browse files Browse the repository at this point in the history
  • Loading branch information
Archidoit committed Jan 23, 2025
1 parent e1f5d63 commit 148633f
Show file tree
Hide file tree
Showing 12 changed files with 61 additions and 34 deletions.
3 changes: 2 additions & 1 deletion opencti-platform/opencti-front/lang/front/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -2670,6 +2670,7 @@
"The CSV file has been generated with the parameters of the view and is ready for download.": "Die CSV-Datei wurde mit den Parametern der Ansicht erstellt und steht zum Download bereit.",
"The dashboard has been duplicated. You can manage it": "Das Dashboard wurde dupliziert. Sie können es verwalten",
"the dedicated page": "der entsprechenden Seite",
"The default groups are:": "Die Standardgruppen sind:",
"The following groups require your attention:": "Die folgenden Gruppen erfordern Ihre Aufmerksamkeit:",
"The importation of the file has been started": "Das Importieren der Datei wurde gestartet",
"The main object and the ... relationships/references linked to it will be deleted permanently.": "Das Hauptobjekt und die mit ihm verknüpften {count} Beziehungen/Referenzen werden dauerhaft gelöscht.",
Expand Down Expand Up @@ -2867,7 +2868,7 @@
"Unit System": "Einheitensystem",
"Unknown": "Unbekannt",
"Unknown configuration error in the platform.": "Unbekannter Konfigurationsfehler in der Plattform.",
"Unless specific groups are selected, user will be created with default groups only.": "Wenn keine spezifischen Gruppen ausgewählt werden, wird der Benutzer nur mit den Standardgruppen erstellt.",
"Unless you prevent the default groups assignation, the user will be created with the specified groups and the default groups.": "Wenn Sie die Zuweisung der Standardgruppen nicht verhindern, wird der Benutzer mit den angegebenen Gruppen und den Standardgruppen erstellt.",
"Unlink": "Unlink",
"unpredictable": "Unvorhersehbar/Unbekannt",
"Unshare": "Freigabe aufheben",
Expand Down
3 changes: 2 additions & 1 deletion opencti-platform/opencti-front/lang/front/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -2670,6 +2670,7 @@
"The CSV file has been generated with the parameters of the view and is ready for download.": "The CSV file has been generated with the parameters of the view and is ready for download.",
"The dashboard has been duplicated. You can manage it": "The dashboard has been duplicated. You can manage it",
"the dedicated page": "the dedicated page",
"The default groups are:": "The default groups are:",
"The following groups require your attention:": "The following groups require your attention:",
"The importation of the file has been started": "The importation of the file has been started",
"The main object and the ... relationships/references linked to it will be deleted permanently.": "The main object and the {count} relationships/references linked to it will be deleted permanently.",
Expand Down Expand Up @@ -2867,7 +2868,7 @@
"Unit System": "Unit System",
"Unknown": "Unknown",
"Unknown configuration error in the platform.": "Unknown configuration error in the platform.",
"Unless specific groups are selected, user will be created with default groups only.": "Unless specific groups are selected, user will be created with default groups only.",
"Unless you prevent the default groups assignation, the user will be created with the specified groups and the default groups.": "Unless you prevent the default groups assignation, the user will be created with the specified groups and the default groups.",
"Unlink": "Unlink",
"unpredictable": "Unpredictable/Unknown",
"Unshare": "Unshare",
Expand Down
3 changes: 2 additions & 1 deletion opencti-platform/opencti-front/lang/front/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -2670,6 +2670,7 @@
"The CSV file has been generated with the parameters of the view and is ready for download.": "El fichero CSV se ha generado con los parámetros de la vista y está preparado para ser descargado.",
"The dashboard has been duplicated. You can manage it": "El tablero ha sido duplicado. puedes gestionarlo",
"the dedicated page": "la página dedicada",
"The default groups are:": "Los grupos por defecto son:",
"The following groups require your attention:": "Los siguientes grupos requieren su atención:",
"The importation of the file has been started": "La importación del fichero se ha iniciado",
"The main object and the ... relationships/references linked to it will be deleted permanently.": "El objeto principal además de sus {count} relaciones/referencias serán eliminados definitivamente.",
Expand Down Expand Up @@ -2867,7 +2868,7 @@
"Unit System": "Sistema de unidades",
"Unknown": "Desconocida",
"Unknown configuration error in the platform.": "Error de configuración desconocido en la plataforma.",
"Unless specific groups are selected, user will be created with default groups only.": "A menos que se seleccionen grupos específicos, el usuario se creará sólo con los grupos por defecto.",
"Unless you prevent the default groups assignation, the user will be created with the specified groups and the default groups.": "A menos que impida la asignación de grupos por defecto, el usuario se creará con los grupos especificados y los grupos por defecto.",
"Unlink": "Desconectar",
"unpredictable": "Impredecible o desconocida",
"Unshare": "Descompartir",
Expand Down
3 changes: 2 additions & 1 deletion opencti-platform/opencti-front/lang/front/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -2670,6 +2670,7 @@
"The CSV file has been generated with the parameters of the view and is ready for download.": "Le fichier CSV a été généré avec les paramètres de la vue et est prêt pour être téléchargé.",
"The dashboard has been duplicated. You can manage it": "Le tableau de bord a été dupliqué. Vous pouvez l'administrer",
"the dedicated page": "la page dédiée",
"The default groups are:": "Les groupes par défaut sont les suivants",
"The following groups require your attention:": "Les groupes suivants requièrent votre attention :",
"The importation of the file has been started": "L'importation du fichier a été lancée",
"The main object and the ... relationships/references linked to it will be deleted permanently.": "L'objet principal ainsi que les {count} relations/références qui lui sont liées seront définitivement supprimés.",
Expand Down Expand Up @@ -2867,7 +2868,7 @@
"Unit System": "Système d'unités",
"Unknown": "inconnu",
"Unknown configuration error in the platform.": "Erreur de configuration inconnue dans la plate-forme.",
"Unless specific groups are selected, user will be created with default groups only.": "À moins que des groupes spécifiques ne soient sélectionnés, l'utilisateur sera créé avec les groupes par défaut uniquement.",
"Unless you prevent the default groups assignation, the user will be created with the specified groups and the default groups.": "A moins que vous n'empêchiez l'assignation des groupes par défaut, l'utilisateur sera créé avec les groupes spécifiés et les groupes par défaut.",
"Unlink": "Dissocier",
"unpredictable": "Imprédictible/Inconnu",
"Unshare": "Annuler le partage",
Expand Down
3 changes: 2 additions & 1 deletion opencti-platform/opencti-front/lang/front/ja.json
Original file line number Diff line number Diff line change
Expand Up @@ -2670,6 +2670,7 @@
"The CSV file has been generated with the parameters of the view and is ready for download.": "指定されたパラメータでCSVが生成され、ダウンロードできるようになりました。",
"The dashboard has been duplicated. You can manage it": "ダッシュボードが複製されました。管理できるよ",
"the dedicated page": "専用ページ",
"The default groups are:": "デフォルトのグループは以下の通り:",
"The following groups require your attention:": "以下のグループに注目してほしい:",
"The importation of the file has been started": "ファイルのインポートが開始されました",
"The main object and the ... relationships/references linked to it will be deleted permanently.": "メインオブジェクトとそれにリンクされた {count} リレーションシップ/参照は永久に削除されます。",
Expand Down Expand Up @@ -2867,7 +2868,7 @@
"Unit System": "ユニットシステム",
"Unknown": "不明",
"Unknown configuration error in the platform.": "プラットフォームで不明な構成エラーが発生しました。",
"Unless specific groups are selected, user will be created with default groups only.": "特定のグループを選択しない限り、ユーザーはデフォルトのグループのみで作成されます",
"Unless you prevent the default groups assignation, the user will be created with the specified groups and the default groups.": "デフォルトグループの割り当てを禁止しない限り、ユーザは指定されたグループとデフォルトグループで作成されます",
"Unlink": "リンクを解除する",
"unpredictable": "予測不能/不明",
"Unshare": "共有解除",
Expand Down
3 changes: 2 additions & 1 deletion opencti-platform/opencti-front/lang/front/ko.json
Original file line number Diff line number Diff line change
Expand Up @@ -2670,6 +2670,7 @@
"The CSV file has been generated with the parameters of the view and is ready for download.": "CSV 파일이 뷰의 매개변수로 생성되었으며 다운로드할 준비가 되었습니다.",
"The dashboard has been duplicated. You can manage it": "대시보드가 복제되었습니다. 관리할 수 있습니다",
"the dedicated page": "전용 페이지",
"The default groups are:": "기본 그룹은 다음과 같습니다:",
"The following groups require your attention:": "다음 그룹에 주의가 필요합니다:",
"The importation of the file has been started": "파일 가져오기가 시작되었습니다",
"The main object and the ... relationships/references linked to it will be deleted permanently.": "주 객체와 해당 객체와 연결된 {count} 관계/참조가 영구적으로 삭제됩니다.",
Expand Down Expand Up @@ -2867,7 +2868,7 @@
"Unit System": "단위 시스템",
"Unknown": "알 수 없음",
"Unknown configuration error in the platform.": "플랫폼의 알 수 없는 구성 오류입니다.",
"Unless specific groups are selected, user will be created with default groups only.": "특정 그룹이 선택되지 않으면 사용자는 기본 그룹만으로 생성됩니다.",
"Unless you prevent the default groups assignation, the user will be created with the specified groups and the default groups.": "기본 그룹 할당을 방지하지 않는 한 사용자는 지정된 그룹과 기본 그룹으로 만들어집니다.",
"Unlink": "연결 해제",
"unpredictable": "예측 불가",
"Unshare": "공유 해제",
Expand Down
3 changes: 2 additions & 1 deletion opencti-platform/opencti-front/lang/front/zh.json
Original file line number Diff line number Diff line change
Expand Up @@ -2670,6 +2670,7 @@
"The CSV file has been generated with the parameters of the view and is ready for download.": "CSV文件已使用视图的参数生成,并已准备好下载。",
"The dashboard has been duplicated. You can manage it": "仪表板已被复制。你可以管理它",
"the dedicated page": "专用页面",
"The default groups are:": "默认组别为",
"The following groups require your attention:": "请您关注以下群体:",
"The importation of the file has been started": "已开始导入文件",
"The main object and the ... relationships/references linked to it will be deleted permanently.": "将永久删除主对象及其链接的 {count} 关系/引用。",
Expand Down Expand Up @@ -2867,7 +2868,7 @@
"Unit System": "单位系统",
"Unknown": "未知",
"Unknown configuration error in the platform.": "平台中存在未知配置错误。",
"Unless specific groups are selected, user will be created with default groups only.": "除非选择了特定组,否则创建的用户将只包含默认组",
"Unless you prevent the default groups assignation, the user will be created with the specified groups and the default groups.": "除非阻止分配默认组,否则创建的用户将包含指定组和默认组",
"Unlink": "取消链接",
"unpredictable": "无法预知",
"Unshare": "取消共享",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@ import React from 'react';
import { Field, Form, Formik } from 'formik';
import Button from '@mui/material/Button';
import * as Yup from 'yup';
import { makeStyles } from '@mui/styles';
import { useTheme } from '@mui/styles';
import { graphql, usePreloadedQuery } from 'react-relay';
import Alert from '@mui/material/Alert';
import MenuItem from '@mui/material/MenuItem';
import { InformationOutline } from 'mdi-material-ui';
import Tooltip from '@mui/material/Tooltip';
import GroupField, { groupsQuery } from '../../common/form/GroupField';
import UserConfidenceLevelField from './edition/UserConfidenceLevelField';
import Drawer, { DrawerVariant } from '../../common/drawer/Drawer';
Expand All @@ -21,18 +23,7 @@ import { fieldSpacingContainerStyle } from '../../../../utils/field';
import useAuth from '../../../../utils/hooks/useAuth';
import { insertNode } from '../../../../utils/store';
import useGranted, { SETTINGS_SETACCESSES } from '../../../../utils/hooks/useGranted';

// Deprecated - https://mui.com/system/styles/basics/
// Do not use it for new code.
const useStyles = makeStyles((theme) => ({
buttons: {
marginTop: 20,
textAlign: 'right',
},
button: {
marginLeft: theme.spacing(2),
},
}));
import SwitchField from '../../../../components/fields/SwitchField';

const userMutation = graphql`
mutation UserCreationMutation($input: UserAddInput!) {
Expand Down Expand Up @@ -63,12 +54,13 @@ const userValidation = (t) => Yup.object().shape({
then: (schema) => schema.required(t('This field is required')).nullable(),
otherwise: (schema) => schema.nullable(),
}),
prevent_default_groups: Yup.boolean(),
});

const UserCreation = ({ paginationOptions, defaultGroupsQueryRef }) => {
const { settings } = useAuth();
const theme = useTheme();
const { t_i18n } = useFormatter();
const classes = useStyles();
const hasSetAccess = useGranted([SETTINGS_SETACCESSES]);

const { groups: defaultGroups } = usePreloadedQuery(groupsQuery, defaultGroupsQueryRef);
Expand Down Expand Up @@ -112,7 +104,7 @@ const UserCreation = ({ paginationOptions, defaultGroupsQueryRef }) => {
{({ onClose }) => (
<>
<Alert severity="info">
{t_i18n('Unless specific groups are selected, user will be created with default groups only.')}
{t_i18n('Unless you prevent the default groups assignation, the user will be created with the specified groups and the default groups.')}
</Alert>
<br />
<Formik
Expand All @@ -125,10 +117,11 @@ const UserCreation = ({ paginationOptions, defaultGroupsQueryRef }) => {
password: '',
confirmation: '',
objectOrganization: [],
groups: defaultGroups.edges.map((g) => ({ value: g.node.id, label: g.node.name })),
groups: [],
account_status: 'Active',
account_lock_after_date: null,
user_confidence_level: null,
prevent_default_groups: false,
}}
validationSchema={userValidation(t_i18n)}
onSubmit={onSubmit}
Expand Down Expand Up @@ -206,6 +199,20 @@ const UserCreation = ({ paginationOptions, defaultGroupsQueryRef }) => {
style={fieldSpacingContainerStyle}
showConfidence={true}
/>
<Field
component={SwitchField}
type="checkbox"
name="prevent_default_groups"
label={<div style={{ display: 'flex' }}>
<>{t_i18n('Don\'t add the user to the default groups')}</>
<Tooltip
title={`${t_i18n('The default groups are:')} ${defaultGroups.edges.map((g) => g.node.name)}`}
>
<InformationOutline style={{ marginLeft: 8 }} fontSize="small" color="primary" />
</Tooltip>
</div>}
containerstyle={{ marginTop: 20 }}
/>
<Field
component={SelectField}
variant="standard"
Expand Down Expand Up @@ -238,12 +245,16 @@ const UserCreation = ({ paginationOptions, defaultGroupsQueryRef }) => {
label={t_i18n('Max Confidence Level')}
/>
)}
<div className={classes.buttons}>
<div style={{
marginTop: 20,
textAlign: 'right',
}}
>
<Button
variant="contained"
onClick={handleReset}
disabled={isSubmitting}
classes={{ root: classes.button }}
style={{ marginLeft: theme.spacing(2) }}
>
{t_i18n('Cancel')}
</Button>
Expand All @@ -252,7 +263,7 @@ const UserCreation = ({ paginationOptions, defaultGroupsQueryRef }) => {
color="secondary"
onClick={submitForm}
disabled={isSubmitting}
classes={{ root: classes.button }}
style={{ marginLeft: theme.spacing(2) }}
>
{t_i18n('Create')}
</Button>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1743,6 +1743,7 @@ input UserAddInput {
monochrome_labels: Boolean
groups: [ID!]
user_confidence_level: ConfidenceLevelInput
prevent_default_groups: Boolean
}

input ConfidenceLevelInput {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1667,6 +1667,7 @@ input UserAddInput {
monochrome_labels: Boolean
groups: [ID!]
user_confidence_level: ConfidenceLevelInput
prevent_default_groups: Boolean
}

input ConfidenceLevelInput {
Expand Down
22 changes: 14 additions & 8 deletions opencti-platform/opencti-graphql/src/domain/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -581,7 +581,8 @@ export const addUser = async (context, user, newUser) => {
R.assoc('user_confidence_level', newUser.user_confidence_level ?? null), // can be null
R.assoc('personal_notifiers', [STATIC_NOTIFIER_UI, STATIC_NOTIFIER_EMAIL]),
R.dissoc('roles'),
R.dissoc('groups')
R.dissoc('groups'),
R.dissoc('prevent_default_groups')
)(newUser);
const { element, isCreation } = await createEntity(context, user, userToCreate, ENTITY_TYPE_USER, { complete: true });
// Link to organizations
Expand All @@ -592,26 +593,31 @@ export const addUser = async (context, user, newUser) => {
relationship_type: RELATION_PARTICIPATE_TO,
}));
await Promise.all(relationOrganizations.map((relation) => createRelation(context, user, relation)));
// Either use the provided groups or Assign the default groups to user (SSO)
// Add the provided groups
let relationGroups = [];
if ((newUser.groups ?? []).length > 0) {
relationGroups = (newUser.groups ?? []).map((group) => ({
fromId: element.id,
toId: group,
relationship_type: RELATION_MEMBER_OF,
}));
} else { // if no provided groups, assign the user to the default groups
}
// if prevent_default_groups is not true, assign the default groups to the user
if (newUser.prevent_default_groups !== true) {
const defaultAssignationFilter = {
mode: 'and',
filters: [{ key: 'default_assignation', values: [true] }],
filterGroups: [],
};
const defaultGroups = await findGroups(context, user, { filters: defaultAssignationFilter });
relationGroups = defaultGroups.edges.map((e) => ({
fromId: element.id,
toId: e.node.internal_id,
relationship_type: RELATION_MEMBER_OF,
}));
const relationDefaultGroups = defaultGroups.edges
.filter((e) => !(newUser.groups ?? []).includes(e.node.internal_id)) // remove groups already in new user group input
.map((e) => ({
fromId: element.id,
toId: e.node.internal_id,
relationship_type: RELATION_MEMBER_OF,
}));
relationGroups = [...relationGroups, ...relationDefaultGroups];
}
await Promise.all(relationGroups.map((relation) => createRelation(context, user, relation)));
// Audit log
Expand Down
1 change: 1 addition & 0 deletions opencti-platform/opencti-graphql/src/generated/graphql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29107,6 +29107,7 @@ export type UserAddInput = {
name: Scalars['String']['input'];
objectOrganization?: InputMaybe<Array<Scalars['ID']['input']>>;
password: Scalars['String']['input'];
prevent_default_groups?: InputMaybe<Scalars['Boolean']['input']>;
submenu_auto_collapse?: InputMaybe<Scalars['Boolean']['input']>;
submenu_show_icons?: InputMaybe<Scalars['Boolean']['input']>;
theme?: InputMaybe<Scalars['String']['input']>;
Expand Down

0 comments on commit 148633f

Please sign in to comment.