user.component.ts 18.9 KB
Newer Older
1
import { Component, OnInit, ViewChild } from '@angular/core';
2
3
import { SignaturesContentService } from '../../service/signatures.service';
import { NotificationService } from '../../service/notification.service';
4
import { HttpClient, HttpHeaders } from '@angular/common/http';
5
import { MatDialog } from '@angular/material/dialog';
6
import {map, finalize, tap, catchError} from 'rxjs/operators';
7
8
import { ActivatedRoute, Router } from '@angular/router';
import { ConfirmComponent } from '../../plugins/confirm.component';
9
import { TranslateService } from '@ngx-translate/core';
10
import { AuthService } from '../../service/auth.service';
11
import { of } from 'rxjs';
12
13
import { AlertController, ModalController } from '@ionic/angular';
import { GroupModalComponent } from '../group/modal/group-modal.component';
14
15
16
17
18
19
20
21


export interface User {
    id: string;
    firstname: string;
    lastname: string;
    login: string;
    email: string;
22
    phone: string;
23
    picture: string;
24
    isRest: boolean;
25
    signatureModes: string[];
26
    canSendActivationNotification: boolean;
27
28
29
30
31
}

@Component({
    selector: 'app-administration-user',
    templateUrl: 'user.component.html',
Alex ORLUC's avatar
Alex ORLUC committed
32
    styleUrls: ['../administration.scss', 'user.component.scss'],
33
34
35
36
37
38
})

export class UserComponent implements OnInit {

    creationMode: boolean = true;
    loading: boolean = true;
39
40
41
42
43
44
    user: User = {
        id: '',
        firstname: '',
        lastname: '',
        login: '',
        email: '',
45
        phone: '',
46
        picture: '',
47
        isRest: false,
48
49
        signatureModes: ['stamp'],
        canSendActivationNotification: false
50
    };
51
    userClone: User;
52
    title: string = '';
53
54
55
    hideCurrentPassword: Boolean = true;
    hideNewPassword: Boolean = true;
    hideNewPasswordConfirm: Boolean = true;
56
    currentTool = 'info';
57

58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
    // HANDLE PASSWORD
    passwordRules: any = {
        minLength: { enabled: false, value: 0 },
        complexityUpper: { enabled: false, value: 0 },
        complexityNumber: { enabled: false, value: 0 },
        complexitySpecial: { enabled: false, value: 0 },
        renewal: { enabled: false, value: 0 },
        historyLastUse: { enabled: false, value: 0 },
    };
    passwordRest: any = {
        newPassword: '',
        passwordConfirmation: ''
    };

    ruleText = '';
    otherRuleText = '';

    showPassword = false;
    handlePassword: any = {
        error: false,
        errorMsg: ''
    };

81
82
    hasGroup: boolean = false;
    userGroupsClone: any;
83
    manageableGroups: any;
84

85
86
87
88
89
90
91
92
    constructor(
        public http: HttpClient,
        private translate: TranslateService,
        private route: ActivatedRoute,
        private router: Router,
        public signaturesService: SignaturesContentService,
        public notificationService: NotificationService,
        public dialog: MatDialog,
93
        public authService: AuthService,
94
95
        public alertController: AlertController,
        public modalController: ModalController,
96
    ) {
97
98
    }

99
    async ngOnInit(): Promise<void> {
100
        this.route.params.subscribe(async (params: any) => {
101
            if (params['id'] === undefined) {
102
                await this.isCreationMode();
103
            } else {
104
105
                this.isUpdateMode(params['id']);
                this.loading = false;
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
    async isCreationMode() {
        this.creationMode = true;
        this.title = this.translate.instant('lang.userCreation');
        this.user = {
            id: '',
            firstname: '',
            lastname: '',
            login: '',
            email: '',
            phone: '',
            picture: '',
            signatureModes: ['stamp'],
            isRest: false,
            canSendActivationNotification: false
        };
        await this.getManageableGroups();
        this.loading = false;
    }

    isUpdateMode(id: any) {
        this.creationMode = false;
        this.http.get(`../rest/users/${id}`)
            .pipe(
                map((data: any) => data.user)
            )
            .subscribe({
                next: async data => {
                    this.user = data;
                    this.hasGroup = data.groups.length > 0;
                    this.userGroupsClone = JSON.parse(JSON.stringify(data.groups));
                    await this.getManageableGroups();
                    this.userClone = JSON.parse(JSON.stringify(this.user));
                    this.title = this.user.firstname + ' ' + this.user.lastname;
                    if (this.user.isRest) {
                        this.getPassRules({ detail: {
                            checked: true
                        } });
                    }
                },
            });
    }

152
    canValidate() {
153
154
155
        if (this.user.isRest && this.passwordRest.newPassword !== '' && (this.handlePassword.error || this.passwordRest.passwordConfirmation !== this.passwordRest.newPassword)) {
            return false;
        } else if (JSON.stringify(this.user) === JSON.stringify(this.userClone) && this.passwordRest.newPassword === '') {
156
157
158
159
160
161
162
            return false;
        } else {
            return true;
        }
    }

    onSubmit() {
163
164
165
166
167
168
169
170
        if (this.creationMode) {
            this.createUser();
        } else {
            this.modifyUser();
        }
    }

    modifyUser() {
171
        this.loading = true;
172
173
        const objToSend = {...this.user, groups: this.user['groups'].map((group: any) => group.id)};
        this.http.put('../rest/users/' + this.user.id, objToSend)
174
            .pipe(
175
176
                finalize(() => this.loading = false),
                tap(() => {
177
                    if (this.authService.user.id === this.user.id) {
178
                        this.authService.updateUserInfoWithTokenRefresh();
179
                    }
180
181
182
                    if (this.passwordRest.newPassword !== '') {
                        this.updateRestUser();
                    }
183
                    this.router.navigate(['/administration/users/' + this.user.id]);
184
                    this.notificationService.success('lang.userUpdated');
185
186
187
188
189
190
191
                }),
                catchError((err: any) => {
                    this.notificationService.handleErrors(err);
                    return of(false);
                })
            )
            .subscribe();
192
193
    }

194
195
196
197
198
199
200
201
202
203
204
205
206
    updateRestUser() {
        const headers = new HttpHeaders({
            'Authorization': 'Bearer ' + this.authService.getToken()
        });
        this.http.put('../rest/users/' + this.user.id + '/password', this.passwordRest, { headers: headers })
            .subscribe(() => {
                this.passwordRest.newPassword = '';
                this.passwordRest.passwordConfirmation = '';
            }, (err) => {
                this.notificationService.handleErrors(err);
            });
    }

207
208
209
210
    createUser() {
        this.loading = true;
        this.http.post('../rest/users', this.user)
            .pipe(
211
212
                finalize(() => this.loading = false),
                tap((data: any) => {
213
214
215
216
                    if (this.user.isRest) {
                        this.user.id = data.id;
                        this.updateRestUser();
                    }
217
                    this.router.navigate([`/administration/users/${data.id}`]);
218
                    this.notificationService.success('lang.userAdded');
219
220
221
222
223
224
225
                }),
                catchError((err: any) => {
                    this.notificationService.handleErrors(err);
                    return of(false);
                })
            )
            .subscribe();
226
227
228
    }

    delete() {
229
        const dialogRef = this.dialog.open(ConfirmComponent, { autoFocus: false, data: { mode: '', title: 'lang.confirmMsg', msg: '' } });
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246

        dialogRef.afterClosed().subscribe(result => {
            if (result === 'yes') {
                this.loading = true;
                this.http.delete('../rest/users/' + this.user.id)
                    .pipe(
                        finalize(() => this.loading = false)
                    )
                    .subscribe({
                        next: () => {
                            this.router.navigate(['/administration/users']);
                            this.notificationService.success('lang.userDeleted');
                        },
                    });
            }
        });
    }
247
248

    cancel() {
Alex ORLUC's avatar
Alex ORLUC committed
249
        this.router.navigate(['/administration/users']);
250
    }
251
252

    getPassRules(ev: any) {
253
        if (ev.detail.checked) {
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
            this.handlePassword.error = false;
            this.handlePassword.errorMsg = '';

            this.http.get('../rest/passwordRules')
                .subscribe((data: any) => {
                    const ruleTextArr: String[] = [];
                    const otherRuleTextArr: String[] = [];

                    data.rules.forEach((rule: any) => {
                        if (rule.label === 'minLength') {
                            this.passwordRules.minLength.enabled = rule.enabled;
                            this.passwordRules.minLength.value = rule.value;
                            if (rule.enabled) {
                                this.translate.get('lang.minLengthChar', { charLength: rule.value }).subscribe((res: string) => {
                                    ruleTextArr.push(res);
                                });
                            }

                        } else if (rule.label === 'complexityUpper') {
                            this.passwordRules.complexityUpper.enabled = rule.enabled;
                            this.passwordRules.complexityUpper.value = rule.value;
                            if (rule.enabled) {
                                ruleTextArr.push('lang.upperRequired');
                            }

                        } else if (rule.label === 'complexityNumber') {
                            this.passwordRules.complexityNumber.enabled = rule.enabled;
                            this.passwordRules.complexityNumber.value = rule.value;
                            if (rule.enabled) {
                                ruleTextArr.push('lang.numberRequired');
                            }

                        } else if (rule.label === 'complexitySpecial') {
                            this.passwordRules.complexitySpecial.enabled = rule.enabled;
                            this.passwordRules.complexitySpecial.value = rule.value;
                            if (rule.enabled) {
                                ruleTextArr.push('lang.specialCharRequired');
                            }
                        } else if (rule.label === 'renewal') {
                            this.passwordRules.renewal.enabled = rule.enabled;
                            this.passwordRules.renewal.value = rule.value;
                            if (rule.enabled) {
                                this.translate.get('lang.renewalInfo', { time: rule.value }).subscribe((res: string) => {
                                    otherRuleTextArr.push(res);
                                });
                            }
                        } else if (rule.label === 'historyLastUse') {
                            this.passwordRules.historyLastUse.enabled = rule.enabled;
                            this.passwordRules.historyLastUse.value = rule.value;
                            if (rule.enabled) {
                                this.translate.get('lang.historyUseInfo', { countPwd: rule.value }).subscribe((res: string) => {
                                    otherRuleTextArr.push(res);
                                });
                            }
                        }

                    });
                    this.ruleText = ruleTextArr.join(', ');
                    this.otherRuleText = otherRuleTextArr.join('<br/>');
                }, (err) => {
                    this.notificationService.handleErrors(err);
                });
        }
    }

    checkPasswordValidity(password: string) {
        this.handlePassword.error = true;

        if (!password.match(/[A-Z]/g) && this.passwordRules.complexityUpper.enabled) {
            this.handlePassword.errorMsg = 'lang.upperRequired';
        } else if (!password.match(/[0-9]/g) && this.passwordRules.complexityNumber.enabled) {
            this.handlePassword.errorMsg = 'lang.numberRequired';
        } else if (!password.match(/[^A-Za-z0-9]/g) && this.passwordRules.complexitySpecial.enabled) {
            this.handlePassword.errorMsg = 'lang.specialCharRequired';
        } else if (password.length < this.passwordRules.minLength.value && this.passwordRules.minLength.enabled) {
            this.translate.get('lang.minLengthChar', { charLength: this.passwordRules.minLength.value }).subscribe((res: string) => {
                this.handlePassword.errorMsg = res;
            });
        } else {
            this.handlePassword.error = false;
            this.handlePassword.errorMsg = '';
        }
    }
337
338
339

    toggleSignMode(signMode: any, state: boolean) {
        if (state) {
340
341
342
            if (this.user.signatureModes.indexOf(signMode.id) === -1) {
                this.user.signatureModes.push(signMode.id);
            }
343
        } else {
344
            this.user.signatureModes = this.user.signatureModes.filter((item: any) => item !== signMode.id);
345
346
        }
    }
347
348
349
350

    initTab(val: any) {
        this.currentTool = val;
    }
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382

    async resendActivationNotification() {
        const alert = await this.alertController.create({
            header: this.translate.instant('lang.confirmMsg'),
            buttons: [
                {
                    text: this.translate.instant('lang.no'),
                    role: 'cancel',
                    cssClass: 'secondary',
                    handler: () => { }
                },
                {
                    text: this.translate.instant('lang.yes'),
                    handler: () => {
                        this.http.put('../rest/users/' + this.user.id + '/accountActivationNotification', {})
                            .pipe(
                                tap(() => {
                                    this.notificationService.success(this.translate.instant('lang.activationNotificationSend'));
                                }),
                                catchError((err: any) => {
                                    this.notificationService.handleErrors(err);
                                    return of(false);
                                })
                            )
                            .subscribe();
                    }
                }
            ]
        });

        await alert.present();
    }
383

384
385
    getManageableGroups() {
        return new Promise((resolve) => {
386
            this.http.get('../rest/manageableGroups').pipe(
387
                tap((data: any) => {
388
                    this.manageableGroups = JSON.parse(JSON.stringify(data.groups));
389
390
391
392
393
394
                    if (this.hasGroup) {
                        const groupIds: number[] = this.userGroupsClone.map((group: any) => group.id);
                        this.userGroupsClone = JSON.parse(JSON.stringify(data.groups.filter((group: any) => groupIds.indexOf(group.id) === -1)));
                    } else  {
                        this.userGroupsClone = JSON.parse(JSON.stringify(data.groups));
                    }
395
396
                    resolve(true);
                }),
397
                finalize(() => this.loading = false),
398
399
400
401
402
403
404
                catchError((err: any) => {
                    this.notificationService.handleErrors(err);
                    return of(false);
                })
            ).subscribe();
        });
    }
405

406
407
408
409
410
    isManageableGroup(groupId: any) {
        console.log(groupId, this.userGroupsClone);
        return this.manageableGroups.find((userGroup: any) => userGroup.id === groupId) !== undefined;
    }

411
    async unlinkGroup(group: any) {
412
        const cannotManage: boolean = this.user['groups'].length === 1 && this.user.id === this.authService.user.id && this.authService.user.administrativePrivileges.find((privilege: any) => privilege.id === 'manage_users') !== undefined;
413
414
        const alert = await this.alertController.create({
            header: this.translate.instant('lang.confirmMsg'),
415
            message: cannotManage ? this.translate.instant('lang.groupWarnMsg') : '',
416
417
418
419
420
421
422
423
424
425
            buttons: [
                {
                    text: this.translate.instant('lang.no'),
                    role: 'cancel',
                    cssClass: 'secondary',
                    handler: () => { }
                },
                {
                    text: this.translate.instant('lang.yes'),
                    handler: () => {
426
                        this.http.delete(`../rest/groups/${group.id}/users/${this.user.id}`, {})
427
                            .pipe(
428
429
430
431
                                tap(() => {
                                    this.isUpdateMode(this.user.id);
                                    this.userGroupsClone.push(group);
                                }),
432
433
434
435
                                finalize(() => this.loading = false)
                            )
                            .subscribe({
                                next: data => {
436
                                    const indexToDelete = this.user['groups'].findIndex((item: any) => item.id === group.id);
437
438
                                    this.user['groups'].splice(indexToDelete, 1);
                                    this.notificationService.success('lang.groupDeleted');
439
                                    this.authService.updateUserInfoWithTokenRefresh();
440
441
442
443
444
445
446
447
448
                                    this.http.get(`../rest/users/${this.user.id}`).pipe(
                                        tap(() => {}),
                                        catchError((err: any) => {
                                            if (err.error.errors === 'User out of perimeter') {
                                                this.router.navigate(['/administration/users']);
                                            }
                                            return of(false);
                                        })
                                    ).subscribe();
449
450
451
452
453
454
455
456
457
458
459
                                },
                                error: err => {
                                    this.notificationService.handleErrors(err);
                                }
                            });
                    }
                }
            ]
        });
        await alert.present();
    }
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480

    async openGroupsList() {
        const modal = await this.modalController.create({
            component: GroupModalComponent,
            componentProps: {
                groups: this.userGroupsClone,
                editUser: true
            }
        });
        await modal.present();
        const { data } = await modal.onWillDismiss();
        if (data !== undefined) {
            this.user['groups'] = this.user['groups'].concat(data.filter((group: any) => group.checked).map((item: any) => ({
                id: item.id,
                label: item.label
            })));
            const groupIds: number[] = this.user['groups'].map((group: any) => group.id);
            this.userGroupsClone = this.userGroupsClone.filter((group: any) => groupIds.indexOf(group.id) === -1);
            this.modifyUser();
        }
    }
481
}