ChangePasswordForm.tsx 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import { css } from '@emotion/css';
  2. import React, { FC } from 'react';
  3. import { Button, Field, Form, HorizontalGroup, LinkButton } from '@grafana/ui';
  4. import config from 'app/core/config';
  5. import { UserDTO } from 'app/types';
  6. import { PasswordField } from '../../core/components/PasswordField/PasswordField';
  7. import { ChangePasswordFields } from './types';
  8. export interface Props {
  9. user: UserDTO;
  10. isSaving: boolean;
  11. onChangePassword: (payload: ChangePasswordFields) => void;
  12. }
  13. export const ChangePasswordForm: FC<Props> = ({ user, onChangePassword, isSaving }) => {
  14. const { ldapEnabled, authProxyEnabled, disableLoginForm } = config;
  15. const authSource = user.authLabels?.length && user.authLabels[0];
  16. if (ldapEnabled || authProxyEnabled) {
  17. return <p>You cannot change password when LDAP or auth proxy authentication is enabled.</p>;
  18. }
  19. if (authSource && disableLoginForm) {
  20. return <p>Password cannot be changed here.</p>;
  21. }
  22. return (
  23. <div
  24. className={css`
  25. max-width: 400px;
  26. `}
  27. >
  28. <Form onSubmit={onChangePassword}>
  29. {({ register, errors, getValues }) => {
  30. return (
  31. <>
  32. <Field label="Old password" invalid={!!errors.oldPassword} error={errors?.oldPassword?.message}>
  33. <PasswordField
  34. id="current-password"
  35. autoComplete="current-password"
  36. {...register('oldPassword', { required: 'Old password is required' })}
  37. />
  38. </Field>
  39. <Field label="New password" invalid={!!errors.newPassword} error={errors?.newPassword?.message}>
  40. <PasswordField
  41. id="new-password"
  42. autoComplete="new-password"
  43. {...register('newPassword', {
  44. required: 'New password is required',
  45. validate: {
  46. confirm: (v) => v === getValues().confirmNew || 'Passwords must match',
  47. old: (v) => v !== getValues().oldPassword || `New password can't be the same as the old one.`,
  48. },
  49. })}
  50. />
  51. </Field>
  52. <Field label="Confirm password" invalid={!!errors.confirmNew} error={errors?.confirmNew?.message}>
  53. <PasswordField
  54. id="confirm-new-password"
  55. autoComplete="new-password"
  56. {...register('confirmNew', {
  57. required: 'New password confirmation is required',
  58. validate: (v) => v === getValues().newPassword || 'Passwords must match',
  59. })}
  60. />
  61. </Field>
  62. <HorizontalGroup>
  63. <Button variant="primary" disabled={isSaving} type="submit">
  64. Change Password
  65. </Button>
  66. <LinkButton variant="secondary" href={`${config.appSubUrl}/profile`} fill="outline">
  67. Cancel
  68. </LinkButton>
  69. </HorizontalGroup>
  70. </>
  71. );
  72. }}
  73. </Form>
  74. </div>
  75. );
  76. };