-
Notifications
You must be signed in to change notification settings - Fork 6
/
user-form.component.ts
373 lines (338 loc) · 11.5 KB
/
user-form.component.ts
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
EventEmitter,
Input,
OnChanges,
OnInit,
Output,
} from '@angular/core';
import { UntypedFormBuilder, UntypedFormControl, UntypedFormGroup, Validators } from '@angular/forms';
import { Constants, ReadUser, StringLiteral, UpdateUserRequest, User } from '@dasch-swiss/dsp-js';
import { UserApiService } from '@dasch-swiss/vre/shared/app-api';
import { ProjectService } from '@dasch-swiss/vre/shared/app-helper-services';
import { NotificationService } from '@dasch-swiss/vre/shared/app-notification';
import {
AddUserToProjectMembershipAction,
CreateUserAction,
ProjectsSelectors,
SetUserAction,
UserSelectors,
} from '@dasch-swiss/vre/shared/app-state';
import { Actions, Select, Store, ofActionSuccessful } from '@ngxs/store';
import { Observable, combineLatest } from 'rxjs';
import { take, tap } from 'rxjs/operators';
import { AppGlobal } from '../../app-global';
import { existingNamesValidator } from '../../main/directive/existing-name/existing-names.validator';
import { CustomRegex } from '../../workspace/resource/values/custom-regex';
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
selector: 'app-user-form',
templateUrl: './user-form.component.html',
styleUrls: ['./user-form.component.scss'],
})
export class UserFormComponent implements OnInit, OnChanges {
// the user form can be used in several cases:
// a) guest --> register: create new user
// b) system admin or project admin --> add: create new user
// c) system admin or project admin --> edit: edit (not own) user
// d) logged-in user --> edit: edit own user data
// => so, this component has to know who is who and who is doing what;
// the form needs then some permission checks
/**
* if the form was built to add new user to project,
* we get a project uuid and a name (e-mail or username)
* from the "add-user-autocomplete" input
*/
@Input() projectUuid?: string;
@Input() user?: ReadUser;
@Input() name?: string;
/**
* send user data to parent component;
* in case of dialog box?
*/
@Output() closeDialog: EventEmitter<any> = new EventEmitter<ReadUser>();
/**
* status for the progress indicator
*/
loading = false;
loadingData = true;
title: string;
subtitle: string;
/**
* define, if the user has system administration permission
*/
sysAdminPermission = false;
/**
* username should be unique
*/
existingUsernames: [RegExp] = [new RegExp('anEmptyRegularExpressionWasntPossible')];
usernameMinLength = 4;
/**
* email should be unique
*/
existingEmails: [RegExp] = [new RegExp('anEmptyRegularExpressionWasntPossible')];
/**
* form group for the form controller
*/
userForm: UntypedFormGroup;
/**
* error checking on the following fields
*/
formErrors = {
givenName: '',
familyName: '',
email: '',
username: '',
};
/**
* error hints
*/
validationMessages = {
givenName: {
required: 'First name is required.',
},
familyName: {
required: 'Last name is required.',
},
email: {
required: 'Email address is required.',
pattern: "This doesn't appear to be a valid email address.",
existingName: 'This user exists already. If you want to edit it, ask a system administrator.',
member: 'This user is already a member of the project.',
},
username: {
required: 'Username is required.',
pattern: 'Spaces and special characters are not allowed in username',
minlength: `Username must be at least ${this.usernameMinLength} characters long.`,
existingName: 'This user exists already. If you want to edit it, ask a system administrator.',
member: 'This user is already a member of the project.',
},
};
/**
* success of sending data
*/
success = false;
/**
* message after successful post
*/
successMessage: any = {
status: 200,
statusText: "You have successfully updated user's profile data.",
};
/**
* selector to set default language
*/
languagesList: StringLiteral[] = AppGlobal.languagesList;
@Select(UserSelectors.allUsers) allUsers$: Observable<ReadUser[]>;
@Select(UserSelectors.isSysAdmin) isSysAdmin$: Observable<boolean>;
@Select(ProjectsSelectors.hasLoadingErrors)
hasLoadingErrors$: Observable<boolean>;
constructor(
private _userApiService: UserApiService,
private _formBuilder: UntypedFormBuilder,
private _notification: NotificationService,
private _projectService: ProjectService,
private _store: Store,
private _actions$: Actions,
private _cd: ChangeDetectorRef
) {}
ngOnInit() {
this.loadingData = true;
if (this.user) {
this.title = this.user.username;
this.subtitle = "'appLabels.form.user.title.edit' | translate";
this.loadingData = !this.buildForm(this.user);
} else {
/**
* create mode: empty form for new user
*/
// get existing users to avoid same usernames and email addresses
this.allUsers$.pipe(take(1)).subscribe(allUsers => {
for (const user of allUsers) {
// email address of the user should be unique.
// therefore we create a list of existing email addresses to avoid multiple use of user names
this.existingEmails.push(new RegExp(`(?:^|W)${user.email.toLowerCase()}(?:$|W)`));
// username should also be unique.
// therefore we create a list of existingUsernames to avoid multiple use of user names
this.existingUsernames.push(new RegExp(`(?:^|W)${user.username.toLowerCase()}(?:$|W)`));
}
const newUser: ReadUser = new ReadUser();
if (CustomRegex.EMAIL_REGEX.test(this.name)) {
newUser.email = this.name;
} else {
newUser.username = this.name;
}
// build the form
this.loadingData = !this.buildForm(newUser);
this._cd.markForCheck();
});
}
}
ngOnChanges() {
if (this.user) {
this.buildForm(this.user);
}
}
/**
* build the whole form
*
*/
buildForm(user: ReadUser): boolean {
// get info about system admin permission
if (user.id && user.permissions.groupsPerProject[Constants.SystemProjectIRI]) {
// this user is member of the system project. does he has admin rights?
this.sysAdminPermission = user.permissions.groupsPerProject[Constants.SystemProjectIRI].includes(
Constants.SystemAdminGroupIRI
);
}
// if user is defined, we're in the edit mode
// otherwise "create new user" mode is active
const editMode = !!user.id;
this.userForm = this._formBuilder.group({
givenName: new UntypedFormControl(
{
value: user.givenName,
disabled: false,
},
[Validators.required]
),
familyName: new UntypedFormControl(
{
value: user.familyName,
disabled: false,
},
[Validators.required]
),
email: new UntypedFormControl(
{
value: user.email,
disabled: editMode,
},
[Validators.required, Validators.pattern(CustomRegex.EMAIL_REGEX), existingNamesValidator(this.existingEmails)]
),
username: new UntypedFormControl(
{
value: user.username,
disabled: editMode,
},
[
Validators.required,
Validators.minLength(4),
Validators.pattern(CustomRegex.USERNAME_REGEX),
existingNamesValidator(this.existingUsernames),
]
),
password: new UntypedFormControl({
value: '',
disabled: editMode,
}),
lang: new UntypedFormControl({
value: user.lang ? user.lang : 'en',
disabled: false,
}),
status: new UntypedFormControl({
value: user.status ? user.status : true,
disabled: editMode,
}),
systemAdmin: new UntypedFormControl({
value: this.sysAdminPermission,
disabled: editMode,
}),
// 'systemAdmin': this.sysAdminPermission,
// 'group': null
});
this.userForm.valueChanges.subscribe(() => this.onValueChanged());
return true;
}
onValueChanged() {
if (!this.userForm) {
return;
}
const form = this.userForm;
Object.keys(this.formErrors).forEach(field => {
this.formErrors[field] = '';
const control = form.get(field);
if (control && control.dirty && !control.valid) {
const messages = this.validationMessages[field];
Object.keys(control.errors).forEach(key => {
this.formErrors[field] += `${messages[key]} `;
});
}
});
}
// get password from password form and send it to user form
getPassword(pw: string) {
this.userForm.controls.password.setValue(pw);
}
submitData(): void {
this.loading = true;
if (this.user) {
// edit mode: update user data
// username doesn't seem to be optional in @dasch-swiss/dsp-js usersEndpoint type UpdateUserRequest.
// but a user can't change the username, the field is disabled, so it's not a value in this form.
// we have to make a small hack here.
const userData: UpdateUserRequest = new UpdateUserRequest();
// userData.username = this.userForm.value.username;
userData.familyName = this.userForm.value.familyName;
userData.givenName = this.userForm.value.givenName;
// userData.email = this.userForm.value.email;
userData.lang = this.userForm.value.lang;
this._userApiService
.updateBasicInformation(this.user.id, userData)
.pipe(
tap({
error: () => {
this.loading = false;
},
})
)
.subscribe(response => {
this.user = response.user;
this.buildForm(this.user);
const user = this._store.selectSnapshot(UserSelectors.user) as ReadUser;
// update application state
if (user.username === this.user.username) {
// update logged in user session
this.user.lang = this.userForm.controls['lang'].value;
}
this._store.dispatch(new SetUserAction(this.user));
this._notification.openSnackBar("You have successfully updated the user's profile data.");
this.closeDialog.emit();
this.loading = false;
});
} else {
this.createNewUser(this.userForm.value);
}
}
private createNewUser(userForm: any): void {
const userData: User = new User();
userData.username = userForm.username;
userData.familyName = userForm.familyName;
userData.givenName = userForm.givenName;
userData.email = userForm.email;
userData.password = userForm.password;
userData.systemAdmin = userForm.systemAdmin;
userData.status = userForm.status;
userData.lang = userForm.lang;
this._store.dispatch(new CreateUserAction(userData));
combineLatest([this._actions$.pipe(ofActionSuccessful(CreateUserAction)), this.allUsers$])
.pipe(take(1))
.subscribe(([loadUsersAction, allUsers]) => {
this.user = allUsers.find(
user =>
user.familyName === loadUsersAction.userData.familyName &&
user.givenName === loadUsersAction.userData.givenName
);
this.buildForm(this.user);
if (this.projectUuid) {
// if a projectUuid exists, add the user to the project
const projectIri = this._projectService.uuidToIri(this.projectUuid);
this._store.dispatch(new AddUserToProjectMembershipAction(this.user.id, projectIri));
}
this.closeDialog.emit(this.user);
this.loading = false;
});
}
}