user.component.ts 17.6 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
83
    hasGroup: boolean = false;
    userGroupsClone: any;

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

98
    async ngOnInit(): Promise<void> {
99
        this.route.params.subscribe(async (params: any) => {
100
            if (params['id'] === undefined) {
101
                await this.isCreationMode();
102
            } else {
103
104
                this.isUpdateMode(params['id']);
                this.loading = false;
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
    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
                        } });
                    }
                },
            });
    }

151
    canValidate() {
152
153
154
        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 === '') {
155
156
157
158
159
160
161
            return false;
        } else {
            return true;
        }
    }

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

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

193
194
195
196
197
198
199
200
201
202
203
204
205
    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);
            });
    }

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

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

        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');
                        },
                    });
            }
        });
    }
246
247

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

    getPassRules(ev: any) {
252
        if (ev.detail.checked) {
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
            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 = '';
        }
    }
336
337
338

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

    initTab(val: any) {
        this.currentTool = val;
    }
350
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

    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();
    }
382

383
384
385
386
    getManageableGroups() {
        return new Promise((resolve) => {
            this.http.get('../rest/manageablegroups').pipe(
                tap((data: any) => {
387
388
389
390
391
392
                    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));
                    }
393
394
                    resolve(true);
                }),
395
                finalize(() => this.loading = false),
396
397
398
399
400
401
402
                catchError((err: any) => {
                    this.notificationService.handleErrors(err);
                    return of(false);
                })
            ).subscribe();
        });
    }
403

404
    async unlinkGroup(group: any) {
405
406
407
408
409
410
411
412
413
414
415
416
        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: () => {
417
                        this.http.delete(`../rest/groups/${group.id}/users/${this.user.id}`, {})
418
                            .pipe(
419
420
421
422
                                tap(() => {
                                    this.isUpdateMode(this.user.id);
                                    this.userGroupsClone.push(group);
                                }),
423
424
425
426
                                finalize(() => this.loading = false)
                            )
                            .subscribe({
                                next: data => {
427
                                    const indexToDelete = this.user['groups'].findIndex((item: any) => item.id === group.id);
428
429
430
431
432
433
434
435
436
437
438
439
440
                                    this.user['groups'].splice(indexToDelete, 1);
                                    this.notificationService.success('lang.groupDeleted');
                                },
                                error: err => {
                                    this.notificationService.handleErrors(err);
                                }
                            });
                    }
                }
            ]
        });
        await alert.present();
    }
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461

    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();
        }
    }
462
}