-
Notifications
You must be signed in to change notification settings - Fork 1
/
AddUserModal.tsx
173 lines (158 loc) · 5.45 KB
/
AddUserModal.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
import { Box, Button, FormControl, InputLabel, MenuItem, Modal, ModalProps, Select, SelectChangeEvent, TextField, Typography } from "@mui/material"
import React, { ReactNode, useEffect, useState } from "react"
import "../../../styles/Modals.css"
import "../../../styles/UserManagementTab.css"
import vmd from "../../../virtualmodel/VMD"
import { Row } from "../../../virtualmodel/DataAccessor"
import MultiSelect from "../MultiSelect"
import { FunctionAccessor } from "../../../virtualmodel/FunctionAccessor"
import { Role } from "../../../redux/AuthSlice"
import { ErrMsg } from "../../../enums/ErrMsg"
import validator from "validator"
import { AxiosError } from "axios"
import { AuthState } from '../../../redux/AuthSlice';
import { RootState } from '../../../redux/Store';
import { useSelector } from 'react-redux';
import Audits from "../../../virtualmodel/Audits";
interface AddUserModalProps extends Omit<ModalProps, 'children'> {
setOpen: React.Dispatch<React.SetStateAction<boolean>>,
getUsers: () => Promise<void>
}
// Modal component allowing a user to be added to the database
const AddUserModal: React.FC<AddUserModalProps> = ({ setOpen, getUsers, ...props }) => {
// Input values of the modal
const defaultInputValues = { role: "user" };
const [inputValues, setInputValues] = useState<Row>(defaultInputValues)
const {user: loggedInUser }: AuthState = useSelector((state: RootState) => state.auth);
const [emailError, setEmailError] = useState<string>("");
// Role selection state
const [role, setRole] = useState("user");
// Schema Access List state
const [schemaAccessList, setSchemaAccessList] = useState<string[]>([]);
const schemaNames = vmd.getApplicationSchemas().map((schema) => schema.schema_name);
// const schemaNames = vmd.getSchemas().map((schema) => schema.schema_name);
// Handles updating the input values with the schemaAccessList
useEffect(() => {
const newInput = {
...inputValues,
schema_access: `{${schemaAccessList.join(', ')}}` // Formats the schema access list into the postgresql array format
}
setInputValues(newInput);
}, [schemaAccessList])
// Handles change in input field
function handleInputChange(e: React.ChangeEvent<HTMLInputElement>) {
const newInput = {
...inputValues,
[e.target.name]: e.target.value,
}
setInputValues(newInput);
};
function handleRoleChange(e: SelectChangeEvent<string>) {
setRole(e.target.value);
handleInputChange(e as React.ChangeEvent<HTMLInputElement>);
}
function resetModal() {
setInputValues(defaultInputValues);
setRole("user");
handleClose();
}
// Handles modal close
function handleClose() {
setOpen(false);
}
// Handles adding a user
function handleFormSubmit() {
if(!validateEmail()){
return;
}
// Function accessor
const functionAccessor: FunctionAccessor = vmd.getFunctionAccessor("meta", "create_user");
functionAccessor.setBody(inputValues);
functionAccessor.executeFunction()
.then((response) => {
console.log("User " + inputValues["email"] + " created successfully");
getUsers();
resetModal();
})
.catch((error: AxiosError) => {
console.log(error);
if(error.response?.status === 409){
setEmailError(ErrMsg.USER_ALREADY_EXISTS)
}
console.error("An error occured while creating user " + inputValues["email"]);
});
Audits.logAudits(
loggedInUser || "",
"Create New User",
"Create User " + inputValues["email"] + " with role " + inputValues["role"] + " and schema access " + inputValues["schema_access"],
"",
"")
}
function validateEmail(): boolean {
setEmailError("");
if (!inputValues.email || inputValues.email.trim() === '') {
setEmailError(ErrMsg.MISSING_FIELD);
return false;
}
else if (!validator.isEmail(inputValues.email)) {
setEmailError(ErrMsg.INVALID_EMAIL);
return false;
}
else {
return true;
}
}
// All the props from AddUserModal are directly passed down to the Modal component
return <Modal onClose={handleClose} {...props}>
<Box className='modal-container-center'>
<div className="modal-content">
<Typography variant="h5">Add new user</Typography>
<div className="form">
<TextField id="email-field"
label="Email"
variant="outlined"
onChange={handleInputChange}
name="email"
helperText={emailError}
error={emailError === "" ? false : true}
className="textField" />
<FormControl fullWidth>
<InputLabel id="role-label">Role</InputLabel>
<Select
labelId="role-label"
name="role"
value={role}
onChange={(event) => handleRoleChange(event)}
variant="outlined"
label="Role"
>
<MenuItem value={Role.USER}>User</MenuItem>
<MenuItem value={Role.CONFIG}>Configurator</MenuItem>
<MenuItem value={Role.ADMIN}>Admin</MenuItem>
</Select>
</FormControl>
<FormControl>
<InputLabel id='schema-access-label'>Schema Access</InputLabel>
<MultiSelect selectedList={schemaAccessList}
setSelectedList={setSchemaAccessList}
choiceList={schemaNames}
labelId='schema-access-label'
label="Schema Access" />
</FormControl>
</div>
<div className="button-container-wide">
<Button variant="contained" onClick={handleClose} sx={{ backgroundColor: "#404040" }}>
Cancel
</Button>
<Button
variant="contained"
onClick={handleFormSubmit}
sx={{ backgroundColor: "#404040" }}>
Add
</Button>
</div>
</div>
</Box>
</Modal>
}
export default AddUserModal;