a816c624de3b92ab61907c69c8f441635f177311
[osm/NG-UI.git] / src / app / users / add-user / AddEditUserComponent.ts
1 /*
2  Copyright 2020 TATA ELXSI
3
4  Licensed under the Apache License, Version 2.0 (the 'License');
5  you may not use this file except in compliance with the License.
6  You may obtain a copy of the License at
7
8   http://www.apache.org/licenses/LICENSE-2.0
9
10  Unless required by applicable law or agreed to in writing, software
11  distributed under the License is distributed on an "AS IS" BASIS,
12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  See the License for the specific language governing permissions and
14  limitations under the License.
15
16  Author: KUMARAN M (kumaran.m@tataelxsi.co.in), RAJESH S (rajesh.s@tataelxsi.co.in), BARATH KUMAR R (barath.r@tataelxsi.co.in)
17 */
18 /**
19  * @file Add Edit Component.
20  */
21 import { HttpHeaders } from '@angular/common/http';
22 import { Component, Injector, Input, OnInit } from '@angular/core';
23 import { AbstractControl, FormBuilder, FormGroup, Validators } from '@angular/forms';
24 import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
25 import { TranslateService } from '@ngx-translate/core';
26 import { NotifierService } from 'angular-notifier';
27 import { AuthenticationService } from 'AuthenticationService';
28 import { APIURLHEADER, ERRORDATA, LOGINPARAMS, MODALCLOSERESPONSEDATA, TYPESECTION } from 'CommonModel';
29 import { environment } from 'environment';
30 import { RestService } from 'RestService';
31 import { SharedService, isNullOrUndefined } from 'SharedService';
32
33 /**
34  * Creating component
35  * @Component takes AddEditUserComponent.html as template url
36  */
37 @Component({
38     selector: 'app-add-edit-user',
39     templateUrl: './AddEditUserComponent.html',
40     styleUrls: ['./AddEditUserComponent.scss']
41 })
42 /** Exporting a class @exports AddEditUserComponent */
43 export class AddEditUserComponent implements OnInit {
44     /** To inject services @public */
45     public injector: Injector;
46
47     /** Instance for active modal service @public */
48     public activeModal: NgbActiveModal;
49
50     /** FormGroup user Edit Account added to the form @ html @public */
51     public userForm: FormGroup;
52
53     /** Form submission Add */
54     public submitted: boolean = false;
55
56     /** Input contains Modal dialog component Instance @public */
57     @Input() public userTitle: string;
58
59     /** Input contains Modal dialog component Instance @public */
60     @Input() public userType: string;
61
62     /** Input contains Modal dialog component Instance @public */
63     @Input() public userID: string;
64
65     /** Input contains Modal dialog component Instance @public */
66     @Input() public userName: string;
67
68     /** Check the loading results for loader status @public */
69     public isLoadingResults: boolean = false;
70
71     /** Give the message for the loading @public */
72     public message: string = 'PLEASEWAIT';
73
74     /** Holds list of domains @public */
75     public domains: TYPESECTION[] = [];
76
77     /** Variable contains type is changepassword or not @public */
78     public isPassword: boolean;
79
80     /** Variable holds value for first login user @public */
81     public isFirstLogin: boolean = Boolean(sessionStorage.getItem('firstLogin') === 'true');
82
83     /** Instance of the rest service @private */
84     private restService: RestService;
85
86     /** FormBuilder instance added to the formBuilder @private */
87     private formBuilder: FormBuilder;
88
89     /** Controls the header form @private */
90     private headers: HttpHeaders;
91
92     /** Notifier service to popup notification @private */
93     private notifierService: NotifierService;
94
95     /** Contains tranlsate instance @private */
96     private translateService: TranslateService;
97
98     /** Contains all methods related to shared @private */
99     private sharedService: SharedService;
100
101     /** ModalData instance of modal @private  */
102     private modalData: MODALCLOSERESPONSEDATA;
103
104     /** Utilizes auth service for any auth operations @private */
105     private authService: AuthenticationService;
106
107     constructor(injector: Injector) {
108         this.injector = injector;
109         this.formBuilder = this.injector.get(FormBuilder);
110         this.restService = this.injector.get(RestService);
111         this.activeModal = this.injector.get(NgbActiveModal);
112         this.notifierService = this.injector.get(NotifierService);
113         this.translateService = this.injector.get(TranslateService);
114         this.sharedService = this.injector.get(SharedService);
115         this.authService = this.injector.get(AuthenticationService);
116
117         /** Initializing Form Action */
118         this.userForm = this.formBuilder.group({
119             userName: ['', Validators.required],
120             password: [null, [Validators.required, Validators.pattern(this.sharedService.REGX_PASSWORD_PATTERN)]],
121             password2: [null, Validators.required],
122             old_password: [null, Validators.required],
123             domain_name: [null]
124         });
125     }
126
127     /** convenience getter for easy access to form fields */
128     get f(): FormGroup['controls'] { return this.userForm.controls; }
129
130     /** Lifecyle Hooks the trigger before component is instantiate @public */
131     public ngOnInit(): void {
132         this.headers = new HttpHeaders({
133             'Content-Type': 'application/json',
134             Accept: 'application/json',
135             'Cache-Control': 'no-cache, no-store, must-revalidate, max-age=0'
136         });
137         if (this.userType === 'add') {
138             this.getDomainList();
139         } else if (this.userType === 'editUserName') {
140             this.userForm.patchValue({ userName: this.userName });
141         } else if (this.isFirstLogin) {
142             this.isPassword = true;
143         }
144     }
145
146     /** On modal submit users acction will called @public */
147     public userAction(userType: string): void {
148         if (userType === 'editPassword') {
149             this.getFormControl('userName').setValidators([]);
150             this.getFormControl('userName').updateValueAndValidity();
151             this.getFormControl('old_password').setValidators([]);
152             this.getFormControl('old_password').updateValueAndValidity();
153         } else if (userType === 'editUserName') {
154             this.getFormControl('password').setValidators([]);
155             this.getFormControl('password').updateValueAndValidity();
156             this.getFormControl('password2').setValidators([]);
157             this.getFormControl('password2').updateValueAndValidity();
158             this.getFormControl('old_password').setValidators([]);
159             this.getFormControl('old_password').updateValueAndValidity();
160         } else if (userType === 'changePassword') {
161             this.getFormControl('userName').setValidators([]);
162             this.getFormControl('userName').updateValueAndValidity();
163         } else if (userType === 'add') {
164             this.getFormControl('old_password').setValidators([]);
165             this.getFormControl('old_password').updateValueAndValidity();
166         }
167         this.submitted = true;
168         this.modalData = {
169             message: 'Done'
170         };
171         this.sharedService.cleanForm(this.userForm);
172         if (!this.userForm.invalid) {
173             if (this.userForm.value.password !== this.userForm.value.password2) {
174                 this.notifierService.notify('error', this.translateService.instant('PAGE.USERS.PASSWORDCONFLICT'));
175                 return;
176             }
177             if (userType === 'add') {
178                 this.addUser();
179             } else {
180                 this.editUser();
181             }
182         }
183     }
184
185     /** Add user @public */
186     public addUser(): void {
187         this.isLoadingResults = true;
188         const payLoad: {} = JSON.stringify({
189             username: (this.userForm.value.userName).toLowerCase(),
190             password: (this.userForm.value.password),
191             domain_name: !isNullOrUndefined(this.userForm.value.domain_name) ? this.userForm.value.domain_name : undefined
192         });
193         const apiURLHeader: APIURLHEADER = {
194             url: environment.USERS_URL,
195             httpOptions: { headers: this.headers }
196         };
197         this.restService.postResource(apiURLHeader, payLoad).subscribe((result: {}): void => {
198             this.activeModal.close(this.modalData);
199             this.isLoadingResults = false;
200             this.notifierService.notify('success', this.translateService.instant('PAGE.USERS.CREATEDSUCCESSFULLY'));
201         }, (error: ERRORDATA): void => {
202             this.restService.handleError(error, 'post');
203             this.isLoadingResults = false;
204         });
205     }
206
207     /** Edit user @public */
208     public editUser(): void {
209         this.isLoadingResults = true;
210         const payLoad: LOGINPARAMS = {};
211         if (this.userType === 'editPassword') {
212             payLoad.password = (this.userForm.value.password);
213         } else if (this.userType === 'changePassword') {
214             payLoad.password = (this.userForm.value.password);
215             payLoad.old_password = (this.userForm.value.old_password);
216         } else {
217             payLoad.username = this.userForm.value.userName.toLowerCase();
218         }
219         const apiURLHeader: APIURLHEADER = {
220             url: environment.USERS_URL + '/' + this.userID,
221             httpOptions: { headers: this.headers }
222         };
223         this.restService.patchResource(apiURLHeader, payLoad).subscribe((result: {}): void => {
224             this.checkUsername(payLoad);
225             this.activeModal.close(this.modalData);
226             if (this.isFirstLogin) {
227                 this.notifierService.notify('success', this.translateService.instant('PAGE.USERS.CHANGEPASSWORD'));
228                 this.authService.destoryToken();
229             } else if (this.userType === 'changePassword' && (!this.isFirstLogin)) {
230                 this.notifierService.notify('success', this.translateService.instant('PAGE.USERS.CHANGEDSUCCESSFULLY'));
231             } else {
232                 this.notifierService.notify('success', this.translateService.instant('PAGE.USERS.EDITEDSUCCESSFULLY'));
233             }
234             this.isLoadingResults = false;
235         }, (error: ERRORDATA): void => {
236             if (this.isFirstLogin) {
237                 this.notifierService.notify('error', error.error.detail);
238                 this.activeModal.close(this.modalData);
239                 this.authService.destoryToken();
240             } else {
241                 this.restService.handleError(error, 'put');
242             }
243             this.isLoadingResults = false;
244         });
245     }
246     /** Close the modal and destroy subscribe @public */
247     public close(): void {
248         if (this.isFirstLogin) {
249             this.activeModal.close(this.modalData);
250             this.authService.destoryToken();
251         } else {
252             this.activeModal.close(this.modalData);
253         }
254     }
255     /** Get domain name list @private */
256     private getDomainList(): void {
257         this.isLoadingResults = true;
258         this.sharedService.getDomainName().subscribe((domainList: TYPESECTION[]): void => {
259             this.domains = domainList;
260             this.isLoadingResults = false;
261         }, (error: ERRORDATA): void => {
262             this.isLoadingResults = false;
263             this.restService.handleError(error, 'get');
264         });
265     }
266
267     /** Used to get the AbstractControl of controlName passed @private */
268     private getFormControl(controlName: string): AbstractControl {
269         // eslint-disable-next-line security/detect-object-injection
270         return this.userForm.controls[controlName];
271     }
272
273     /** Method to check loggedin username and update  @private */
274     private checkUsername(payLoad: LOGINPARAMS): void {
275         const logUsername: string = sessionStorage.getItem('username');
276         if (this.userType === 'editUserName' && logUsername === this.userName) {
277             this.authService.userName.next(payLoad.username);
278             sessionStorage.setItem('username', payLoad.username);
279         }
280     }
281 }