admin-dashboard-web/src/Pages/AllUsers/CreateUserModal.js

130 lines
3.7 KiB
JavaScript

import { Form, Input, Select } from "antd";
import Modal from "antd/es/modal/Modal";
import {
Constants,
EncodeStringToBase64,
SentMessagesCommands,
WebSocketContext,
isEmailValid,
} from "../../utils";
import { useContext, useState } from "react";
export default function CreateUserModal({ isModalOpen, setIsModalOpen }) {
const webSocketContext = useContext(WebSocketContext);
const [username, setUsername] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [selectedRoleId, setSelectedRoleId] = useState();
const isCreateUserPossible = () => {
if (
username.length < Constants.GLOBALS.MIN_USERNAME_LENGTH ||
username.length > Constants.GLOBALS.MAX_USERNAME_LENGTH ||
!isEmailValid(email) ||
password.length < Constants.GLOBALS.MIN_PASSWORD_LENGTH ||
password.length > Constants.GLOBALS.MAX_PASSWORD_LENGTH ||
selectedRoleId === "" ||
selectedRoleId === undefined
) {
return false;
}
return true;
};
const onConfirmUserCreation = () => {
if (!isCreateUserPossible()) return;
webSocketContext.SendSocketMessage(
SentMessagesCommands.AllUsersCreateNewUser,
{
Username: username,
Email: email,
Password: EncodeStringToBase64(password),
RoleId: selectedRoleId,
}
);
setUsername("");
setEmail("");
setPassword("");
setSelectedRoleId();
setIsModalOpen(false);
};
return (
<Modal
title="Create a new user"
open={isModalOpen}
centered
maskClosable={false}
okText="Create user"
okButtonProps={{ disabled: !isCreateUserPossible() }}
onCancel={() => setIsModalOpen(false)}
onOk={() => onConfirmUserCreation()}
>
<Form layout="vertical">
<Form.Item
label="Username"
hasFeedback
validateStatus={
username.length !== 0 &&
username.length < Constants.GLOBALS.MIN_USERNAME_LENGTH &&
"error"
}
>
<Input
placeholder="Username"
value={username}
onChange={(e) => setUsername(e.target.value)}
minLength={Constants.GLOBALS.MIN_USERNAME_LENGTH}
maxLength={Constants.GLOBALS.MAX_USERNAME_LENGTH}
/>
</Form.Item>
<Form.Item
label="E-Mail"
hasFeedback
validateStatus={email.length !== 0 && !isEmailValid(email) && "error"}
>
<Input
placeholder="E-Mail"
value={email}
onChange={(e) => setEmail(e.target.value)}
type="email"
/>
</Form.Item>
<Form.Item
label="Password"
hasFeedback
validateStatus={
password.length !== 0 &&
password.length < Constants.GLOBALS.MIN_PASSWORD_LENGTH &&
"error"
}
>
<Input.Password
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
minLength={Constants.GLOBALS.MIN_PASSWORD_LENGTH}
maxLength={Constants.GLOBALS.MAX_PASSWORD_LENGTH}
/>
</Form.Item>
<Form.Item label="Role">
<Select
getPopupContainer={(node) => node.parentNode}
value={selectedRoleId}
onChange={(e) => setSelectedRoleId(e)}
placeholder="Select a role"
>
{webSocketContext.AllRoles.map((role) => (
<Select.Option key={role.Id}>{role.DisplayName}</Select.Option>
))}
</Select>
</Form.Item>
</Form>
</Modal>
);
}