aboutsummaryrefslogtreecommitdiffstats
path: root/server/sonar-web/src/main/js/apps/users/components/UserForm.tsx
blob: a1a4c11d7d4f1208884c0b0cd1d2421ddc60f887 (plain)
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
/*
 * SonarQube
 * Copyright (C) 2009-2023 SonarSource SA
 * mailto:info AT sonarsource DOT com
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
import * as React from 'react';
import { useCreateUserMutation, useUpdateUserMutation } from '../../../api/queries/users';
import SimpleModal from '../../../components/controls/SimpleModal';
import { Button, ResetButtonLink, SubmitButton } from '../../../components/controls/buttons';
import { Alert } from '../../../components/ui/Alert';
import MandatoryFieldMarker from '../../../components/ui/MandatoryFieldMarker';
import MandatoryFieldsExplanation from '../../../components/ui/MandatoryFieldsExplanation';
import { throwGlobalError } from '../../../helpers/error';
import { translate, translateWithParameters } from '../../../helpers/l10n';
import { parseError } from '../../../helpers/request';
import { User } from '../../../types/users';
import UserScmAccountInput from './UserScmAccountInput';

export interface Props {
  onClose: () => void;
  user?: User;
}

export default function UserForm(props: Props) {
  const { user } = props;

  const { mutate: createUser } = useCreateUserMutation();
  const { mutate: updateUser } = useUpdateUserMutation();

  const [email, setEmail] = React.useState<string>(user?.email || '');
  const [login, setLogin] = React.useState<string>(user?.login || '');
  const [name, setName] = React.useState<string>(user?.name || '');
  const [password, setPassword] = React.useState<string>('');
  const [scmAccounts, setScmAccounts] = React.useState<string[]>(user?.scmAccounts || []);
  const [error, setError] = React.useState<string | undefined>(undefined);

  const handleError = (response: Response) => {
    if (![400, 500].includes(response.status)) {
      return throwGlobalError(response);
    }
    return parseError(response).then((errorMsg) => setError(errorMsg), throwGlobalError);
  };

  const handleCreateUser = () => {
    createUser(
      {
        email: email || undefined,
        login,
        name,
        password,
        scmAccount: scmAccounts,
      },
      { onSuccess: props.onClose, onError: handleError }
    );
  };

  const handleUpdateUser = () => {
    const { user } = props;

    updateUser(
      {
        email: user!.local ? email : undefined,
        login,
        name: user!.local ? name : undefined,
        scmAccount: scmAccounts,
      },
      { onSuccess: props.onClose, onError: handleError }
    );
  };

  const handleAddScmAccount = () => {
    setScmAccounts((scmAccounts) => scmAccounts.concat(''));
  };

  const handleUpdateScmAccount = (idx: number, scmAccount: string) => {
    setScmAccounts((scmAccounts) => {
      const newScmAccounts = scmAccounts.slice();
      newScmAccounts[idx] = scmAccount;
      return newScmAccounts;
    });
  };

  const handleRemoveScmAccount = (idx: number) => {
    setScmAccounts((scmAccounts) => scmAccounts.slice(0, idx).concat(scmAccounts.slice(idx + 1)));
  };

  const header = user ? translate('users.update_user') : translate('users.create_user');

  return (
    <SimpleModal
      header={header}
      onClose={props.onClose}
      onSubmit={user ? handleUpdateUser : handleCreateUser}
      size="small"
    >
      {({ onCloseClick, onFormSubmit, submitting }) => (
        <form autoComplete="off" id="user-form" onSubmit={onFormSubmit}>
          <header className="modal-head">
            <h2>{header}</h2>
          </header>

          <div className="modal-body modal-container">
            {error && <Alert variant="error">{error}</Alert>}

            {!error && user && !user.local && (
              <Alert variant="warning">{translate('users.cannot_update_delegated_user')}</Alert>
            )}

            <MandatoryFieldsExplanation className="modal-field" />

            {!user && (
              <div className="modal-field">
                <label htmlFor="create-user-login">
                  {translate('login')}
                  <MandatoryFieldMarker />
                </label>
                <input
                  autoComplete="off"
                  autoFocus
                  id="create-user-login"
                  maxLength={255}
                  minLength={3}
                  name="login"
                  onChange={(e) => setLogin(e.currentTarget.value)}
                  required
                  type="text"
                  value={login}
                />
                <p className="note">{translateWithParameters('users.minimum_x_characters', 3)}</p>
              </div>
            )}
            <div className="modal-field">
              <label htmlFor="create-user-name">
                {translate('name')}
                <MandatoryFieldMarker />
              </label>
              <input
                autoComplete="off"
                autoFocus={!!user}
                disabled={user && !user.local}
                id="create-user-name"
                maxLength={200}
                name="name"
                onChange={(e) => setName(e.currentTarget.value)}
                required
                type="text"
                value={name}
              />
            </div>
            <div className="modal-field">
              <label htmlFor="create-user-email">{translate('users.email')}</label>
              <input
                autoComplete="off"
                disabled={user && !user.local}
                id="create-user-email"
                maxLength={100}
                name="email"
                onChange={(e) => setEmail(e.currentTarget.value)}
                type="email"
                value={email}
              />
            </div>
            {!user && (
              <div className="modal-field">
                <label htmlFor="create-user-password">
                  {translate('password')}
                  <MandatoryFieldMarker />
                </label>
                <input
                  autoComplete="off"
                  id="create-user-password"
                  name="password"
                  onChange={(e) => setPassword(e.currentTarget.value)}
                  required
                  type="password"
                  value={password}
                />
              </div>
            )}
            <div className="modal-field">
              <fieldset>
                <legend>{translate('my_profile.scm_accounts')}</legend>
                {scmAccounts.map((scm, idx) => (
                  <UserScmAccountInput
                    idx={idx}
                    key={idx}
                    onChange={handleUpdateScmAccount}
                    onRemove={handleRemoveScmAccount}
                    scmAccount={scm}
                  />
                ))}
                <div className="spacer-bottom">
                  <Button className="js-scm-account-add" onClick={handleAddScmAccount}>
                    {translate('add_verb')}
                  </Button>
                </div>
              </fieldset>
              <p className="note">{translate('user.login_or_email_used_as_scm_account')}</p>
            </div>
          </div>

          <footer className="modal-foot">
            {submitting && <i className="spinner spacer-right" />}
            <SubmitButton disabled={submitting}>
              {user ? translate('update_verb') : translate('create')}
            </SubmitButton>
            <ResetButtonLink onClick={onCloseClick}>{translate('cancel')}</ResetButtonLink>
          </footer>
        </form>
      )}
    </SimpleModal>
  );
}