UserCreatePage.tsx 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import React, { useCallback } from 'react';
  2. import { connect } from 'react-redux';
  3. import { useHistory } from 'react-router-dom';
  4. import { NavModel } from '@grafana/data';
  5. import { getBackendSrv } from '@grafana/runtime';
  6. import { Form, Button, Input, Field } from '@grafana/ui';
  7. import Page from 'app/core/components/Page/Page';
  8. import { getNavModel } from '../../core/selectors/navModel';
  9. import { StoreState } from '../../types';
  10. interface UserCreatePageProps {
  11. navModel: NavModel;
  12. }
  13. interface UserDTO {
  14. name: string;
  15. password: string;
  16. email?: string;
  17. login?: string;
  18. }
  19. const createUser = async (user: UserDTO) => getBackendSrv().post('/api/admin/users', user);
  20. const UserCreatePage: React.FC<UserCreatePageProps> = ({ navModel }) => {
  21. const history = useHistory();
  22. const onSubmit = useCallback(
  23. async (data: UserDTO) => {
  24. await createUser(data);
  25. history.push('/admin/users');
  26. },
  27. [history]
  28. );
  29. return (
  30. <Page navModel={navModel}>
  31. <Page.Contents>
  32. <h1>Add new user</h1>
  33. <Form onSubmit={onSubmit} validateOn="onBlur">
  34. {({ register, errors }) => {
  35. return (
  36. <>
  37. <Field
  38. label="Name"
  39. required
  40. invalid={!!errors.name}
  41. error={errors.name ? 'Name is required' : undefined}
  42. >
  43. <Input id="name-input" {...register('name', { required: true })} />
  44. </Field>
  45. <Field label="Email">
  46. <Input id="email-input" {...register('email')} />
  47. </Field>
  48. <Field label="Username">
  49. <Input id="username-input" {...register('login')} />
  50. </Field>
  51. <Field
  52. label="Password"
  53. required
  54. invalid={!!errors.password}
  55. error={errors.password ? 'Password is required and must contain at least 4 characters' : undefined}
  56. >
  57. <Input
  58. id="password-input"
  59. {...register('password', {
  60. validate: (value) => value.trim() !== '' && value.length >= 4,
  61. })}
  62. type="password"
  63. />
  64. </Field>
  65. <Button type="submit">Create user</Button>
  66. </>
  67. );
  68. }}
  69. </Form>
  70. </Page.Contents>
  71. </Page>
  72. );
  73. };
  74. const mapStateToProps = (state: StoreState) => ({
  75. navModel: getNavModel(state.navIndex, 'global-users'),
  76. });
  77. export default connect(mapStateToProps)(UserCreatePage);