Feature 10914: Enforce Password change on First login
[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 } from 'SharedService';
32 import { isNullOrUndefined } from 'util';
33
34 /**
35  * Creating component
36  * @Component takes AddEditUserComponent.html as template url
37  */
38 @Component({
39     selector: 'app-add-edit-user',
40     templateUrl: './AddEditUserComponent.html',
41     styleUrls: ['./AddEditUserComponent.scss']
42 })
43 /** Exporting a class @exports AddEditUserComponent */
44 export class AddEditUserComponent implements OnInit {
45     /** To inject services @public */
46     public injector: Injector;
47
48     /** Instance for active modal service @public */
49     public activeModal: NgbActiveModal;
50
51     /** FormGroup user Edit Account added to the form @ html @public */
52     public userForm: FormGroup;
53
54     /** Form submission Add */
55     public submitted: boolean = false;
56
57     /** Input contains Modal dialog component Instance @public */
58     @Input() public userTitle: string;
59
60     /** Input contains Modal dialog component Instance @public */
61     @Input() public userType: string;
62
63     /** Input contains Modal dialog component Instance @public */
64     @Input() public userID: string;
65
66     /** Input contains Modal dialog component Instance @public */
67     @Input() public userName: string;
68
69     /** Check the loading results for loader status @public */
70     public isLoadingResults: boolean = false;
71
72     /** Give the message for the loading @public */
73     public message: string = 'PLEASEWAIT';
74
75     /** Holds list of domains @public */
76     public domains: TYPESECTION[] = [];
77
78     /** Variable contains type is changepassword or not @public */
79     public isPassword: boolean;
80
81     /** Variable holds value for first login user @public */
82     public isFirstLogin: boolean = Boolean(localStorage.getItem('firstLogin') === 'true');
83
84     /** Instance of the rest service @private */
85     private restService: RestService;
86
87     /** FormBuilder instance added to the formBuilder @private */
88     private formBuilder: FormBuilder;
89
90     /** Controls the header form @private */
91     private headers: HttpHeaders;
92
93     /** Notifier service to popup notification @private */
94     private notifierService: NotifierService;
95
96     /** Contains tranlsate instance @private */
97     private translateService: TranslateService;
98
99     /** Contains all methods related to shared @private */
100     private sharedService: SharedService;
101
102     /** ModalData instance of modal @private  */
103     private modalData: MODALCLOSERESPONSEDATA;
104
105     /** Utilizes auth service for any auth operations @private */
106     private authService: AuthenticationService;
107
108     constructor(injector: Injector) {
109         this.injector = injector;
110         this.formBuilder = this.injector.get(FormBuilder);
111         this.restService = this.injector.get(RestService);
112         this.activeModal = this.injector.get(NgbActiveModal);
113         this.notifierService = this.injector.get(NotifierService);
114         this.translateService = this.injector.get(TranslateService);
115         this.sharedService = this.injector.get(SharedService);
116         this.authService = this.injector.get(AuthenticationService);
117
118         /** Initializing Form Action */
119         this.userForm = this.formBuilder.group({
120             userName: ['', Validators.required],
121             password: [null, [Validators.required, Validators.pattern(this.sharedService.REGX_PASSWORD_PATTERN)]],
122             password2: [null, Validators.required],
123             old_password: [null, Validators.required],
124             domain_name: [null]
125         });
126     }
127
128     /** convenience getter for easy access to form fields */
129     get f(): FormGroup['controls'] { return this.userForm.controls; }
130
131     /** Lifecyle Hooks the trigger before component is instantiate @public */
132     public ngOnInit(): void {
133         this.headers = new HttpHeaders({
134             'Content-Type': 'application/json',
135             Accept: 'application/json',
136             'Cache-Control': 'no-cache, no-store, must-revalidate, max-age=0'
137         });
138         if (this.userType === 'add') {
139             this.getDomainList();
140         } else if (this.userType === 'editUserName') {
141             this.userForm.patchValue({ userName: this.userName });
142         } else if (this.isFirstLogin) {
143             this.isPassword = true;
144         }
145     }
146
147     /** On modal submit users acction will called @public */
148     public userAction(userType: string): void {
149         if (userType === 'editPassword') {
150             this.getFormControl('userName').setValidators([]);
151             this.getFormControl('userName').updateValueAndValidity();
152             this.getFormControl('old_password').setValidators([]);
153             this.getFormControl('old_password').updateValueAndValidity();
154         } else if (userType === 'editUserName') {
155             this.getFormControl('password').setValidators([]);
156             this.getFormControl('password').updateValueAndValidity();
157             this.getFormControl('password2').setValidators([]);
158             this.getFormControl('password2').updateValueAndValidity();
159             this.getFormControl('old_password').setValidators([]);
160             this.getFormControl('old_password').updateValueAndValidity();
161         } else if (userType === 'changePassword') {
162             this.getFormControl('userName').setValidators([]);
163             this.getFormControl('userName').updateValueAndValidity();
164         } else if (userType === 'add') {
165             this.getFormControl('old_password').setValidators([]);
166             this.getFormControl('old_password').updateValueAndValidity();
167         }
168         this.submitted = true;
169         this.modalData = {
170             message: 'Done'
171         };
172         this.sharedService.cleanForm(this.userForm);
173         if (!this.userForm.invalid) {
174             if (this.userForm.value.password !== this.userForm.value.password2) {
175                 this.notifierService.notify('error', this.translateService.instant('PAGE.USERS.PASSWORDCONFLICT'));
176                 return;
177             }
178             if (userType === 'add') {
179                 this.addUser();
180             } else {
181                 this.editUser();
182             }
183         }
184     }
185
186     /** Add user @public */
187     public addUser(): void {
188         this.isLoadingResults = true;
189         const payLoad: {} = JSON.stringify({
190             username: (this.userForm.value.userName).toLowerCase(),
191             password: (this.userForm.value.password),
192             domain_name: !isNullOrUndefined(this.userForm.value.domain_name) ? this.userForm.value.domain_name : undefined
193         });
194         const apiURLHeader: APIURLHEADER = {
195             url: environment.USERS_URL,
196             httpOptions: { headers: this.headers }
197         };
198         this.restService.postResource(apiURLHeader, payLoad).subscribe((result: {}): void => {
199             this.activeModal.close(this.modalData);
200             this.isLoadingResults = false;
201             this.notifierService.notify('success', this.translateService.instant('PAGE.USERS.CREATEDSUCCESSFULLY'));
202         }, (error: ERRORDATA): void => {
203             this.restService.handleError(error, 'post');
204             this.isLoadingResults = false;
205         });
206     }
207
208     /** Edit user @public */
209     public editUser(): void {
210         this.isLoadingResults = true;
211         const payLoad: LOGINPARAMS = {};
212         if (this.userType === 'editPassword') {
213             payLoad.password = (this.userForm.value.password);
214         } else if (this.userType === 'changePassword') {
215             payLoad.password = (this.userForm.value.password);
216             payLoad.old_password = (this.userForm.value.old_password);
217         } else {
218             payLoad.username = this.userForm.value.userName.toLowerCase();
219         }
220         const apiURLHeader: APIURLHEADER = {
221             url: environment.USERS_URL + '/' + this.userID,
222             httpOptions: { headers: this.headers }
223         };
224         this.restService.patchResource(apiURLHeader, payLoad).subscribe((result: {}): void => {
225             this.checkUsername(payLoad);
226             this.activeModal.close(this.modalData);
227             if (this.isFirstLogin) {
228                 this.notifierService.notify('success', this.translateService.instant('PAGE.USERS.CHANGEPASSWORD'));
229                 this.authService.destoryToken();
230             } else {
231                 this.notifierService.notify('success', this.translateService.instant('PAGE.USERS.EDITEDSUCCESSFULLY'));
232             }
233             this.isLoadingResults = false;
234         }, (error: ERRORDATA): void => {
235             if (this.isFirstLogin) {
236                 this.notifierService.notify('error', error.error.detail);
237                 this.activeModal.close(this.modalData);
238                 this.authService.destoryToken();
239             } else {
240                 this.restService.handleError(error, 'put');
241             }
242             this.isLoadingResults = false;
243         });
244     }
245     /** Close the modal and destroy subscribe @public */
246     public close(): void {
247         if (this.isFirstLogin) {
248             this.activeModal.close(this.modalData);
249             this.authService.destoryToken();
250         } else {
251             this.activeModal.close(this.modalData);
252         }
253     }
254     /** Get domain name list @private */
255     private getDomainList(): void {
256         this.isLoadingResults = true;
257         this.sharedService.getDomainName().subscribe((domainList: TYPESECTION[]): void => {
258             this.domains = domainList;
259             this.isLoadingResults = false;
260         }, (error: ERRORDATA): void => {
261             this.isLoadingResults = false;
262             this.restService.handleError(error, 'get');
263         });
264     }
265
266     /** Used to get the AbstractControl of controlName passed @private */
267     private getFormControl(controlName: string): AbstractControl {
268         return this.userForm.controls[controlName];
269     }
270
271     /** Method to check loggedin username and update  @private */
272     private checkUsername(payLoad: LOGINPARAMS): void {
273         const logUsername: string = localStorage.getItem('username');
274         if (this.userType === 'editUserName' && logUsername === this.userName) {
275             this.authService.userName.next(payLoad.username);
276             localStorage.setItem('username', payLoad.username);
277         }
278     }
279 }