Fix Bug 2295: No eye-icon in NG-UI
[osm/NG-UI.git] / src / app / login / LoginComponent.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 /**
20  * @file Page for Login component
21  */
22 import { isNullOrUndefined } from 'util';
23 import { HttpErrorResponse } from '@angular/common/http';
24 import { Component, Injector, OnInit } from '@angular/core';
25 import { FormBuilder, FormGroup, Validators } from '@angular/forms';
26 import { Router } from '@angular/router';
27 import { TranslateService } from '@ngx-translate/core';
28 import { AuthenticationService } from 'AuthenticationService';
29 import { ERRORDATA } from 'CommonModel';
30 import { environment } from 'environment';
31 import { ToastrService } from 'ngx-toastr';
32 import { RestService } from 'RestService';
33 import { Observable } from 'rxjs';
34 import { SharedService } from 'SharedService';
35 import { UserDetail } from 'UserModel';
36
37 /**
38  * Creating component
39  * @Component takes LoginComponent.html as template url
40  */
41 @Component({
42     selector: 'app-login',
43     templateUrl: './LoginComponent.html',
44     styleUrls: ['./LoginComponent.scss']
45 })
46 /** Exporting a class @exports LoginComponent */
47 export class LoginComponent implements OnInit {
48     /** Invoke service injectors @public */
49     public injector: Injector;
50
51     /** contains loginform group information @public */
52     public loginForm: FormGroup;
53
54     /** submitted set to boolean state @public */
55     public submitted: boolean = false;
56
57     /** contains return URL link @public */
58     public returnUrl: string;
59
60     /** Observable Hold the value of subscription  @public */
61     public isLoggedIn$: Observable<boolean>;
62
63     /** Observable Hold the value of subscription  @public */
64     public isChangePassword$: Observable<boolean>;
65
66     /** contains access token information @public */
67     public accessToken: string;
68
69     /** Utilizes rest service for any CRUD operations @public */
70     public restService: RestService;
71
72     /** Check the loading results @public */
73     public isLoadingResults: boolean = false;
74
75     /** Give the message for the loading @public */
76     public message: string = 'PLEASEWAIT';
77
78     /** Contains all methods related to shared @public */
79     public sharedService: SharedService;
80
81     /** contains the loggedIn observable value @public */
82     public loggedIn: boolean;
83
84     /** Contains Last Login information @public */
85     public lastLogin: string;
86
87     /** Holds Last Login Toaster Message @public */
88     public lastLoginMessage: string;
89
90     /** Holds Failed Attempts Toaster Message @public */
91     public failedAttemptsMessage: string;
92
93     /** Holds Password Expire Toaster Message @public */
94     public passwordExpireMessage: string;
95
96     /** Holds Account Expire Toaster Message @public */
97     public accountExpireMessage: string;
98
99     /** Holds password & account Toaster Message @public */
100     public daysMessage: string;
101
102     /** Holds account Days Toaster Message @public */
103     public accountMessage: string;
104
105     /** Holds password Days Toaster Message @public */
106     public passwordMessage: string;
107
108     /** Contains user details information @public */
109     public userDetails: UserDetail;
110
111     /** contains No of failed attempts values @public */
112     public failedAttempts: string;
113
114     /** contains No of days to expire account @public */
115     public accountNoOfDays: string;
116
117     /**  contains No of days to expire password @public */
118     public passwordNoOfDays: string;
119
120     /** User Visibility Check  @public */
121     public isUserShow: boolean;
122
123     /** Admin Visibility Check  @public */
124     public isAdminShow: boolean;
125
126     /** contains the passwordIn observable value @public */
127     public changePassword: boolean;
128
129     /** To show the visiblity of password @public */
130     public visiblePassword: boolean;
131
132     /** Utilizes auth service for any auth operations @private */
133     private authService: AuthenticationService;
134
135     /** contians form builder module @private */
136     private formBuilder: FormBuilder;
137
138     /** Holds teh instance of AuthService class of type AuthService @private */
139     private router: Router;
140
141     /** Contains tranlsate instance @private */
142     private translateService: TranslateService;
143
144     /** Contains toaster instance @private */
145     private toaster: ToastrService;
146
147     /** express number for expire days @private */
148     // eslint-disable-next-line @typescript-eslint/no-magic-numbers
149     private expireDays: number = 5;
150
151     /** express number for time manupulation 1000 */
152     // eslint-disable-next-line @typescript-eslint/no-magic-numbers
153     private epochTime1000: number = 1000;
154
155     /** contains toaster settings */
156     private toasterSettings: {} = {
157         enableHtml: true,
158         closeButton: true,
159         timeOut: 2000
160     };
161
162     // creates instance of login component
163     constructor(injector: Injector) {
164         this.injector = injector;
165         this.restService = this.injector.get(RestService);
166         this.authService = this.injector.get(AuthenticationService);
167         this.formBuilder = this.injector.get(FormBuilder);
168         this.router = this.injector.get(Router);
169         this.sharedService = this.injector.get(SharedService);
170         this.translateService = this.injector.get(TranslateService);
171         this.toaster = this.injector.get(ToastrService);
172     }
173
174     /**
175      * Lifecyle Hooks the trigger before component is instantiate
176      */
177     public ngOnInit(): void {
178         this.isLoggedIn$ = this.authService.isLoggedIn;
179         this.isLoggedIn$.subscribe((res: boolean): void => {
180             this.loggedIn = res;
181         });
182         if (this.loggedIn === true) {
183             this.router.navigate(['/']).catch((): void => {
184                 // Catch Navigation Error
185             });
186         }
187         this.isChangePassword$ = this.authService.isChangePassword;
188         this.isChangePassword$.subscribe((res: boolean): void => {
189             this.changePassword = res;
190         });
191         if (this.changePassword === true) {
192             this.router.navigate(['changepassword']).catch((): void => {
193                 // Catch Navigation Error
194             });
195         }
196
197         this.loginForm = this.formBuilder.group({
198             userName: ['', [Validators.required]],
199             password: ['', [Validators.required]]
200         });
201         this.returnUrl = isNullOrUndefined(sessionStorage.getItem('returnUrl')) ? '/' : sessionStorage.getItem('returnUrl');
202     }
203
204     /**
205      * called on form submit @private onSubmit
206      */
207     public onSubmit(): void {
208         this.submitted = true;
209         if (this.loginForm.invalid) {
210             return;
211         }
212         this.isLoadingResults = true;
213         this.sharedService.cleanForm(this.loginForm);
214         this.isLoadingResults = false;
215         if (!this.loginForm.invalid) {
216             this.loginUser();
217         }
218     }
219
220     /** Login User @public */
221     public loginUser(): void {
222         this.authService.login(this.loginForm.value.userName, this.loginForm.value.password).subscribe(
223             (data: {}): void => {
224                 this.isLoadingResults = false;
225                 if (this.changePassword === true && this.loggedIn === false) {
226                     this.router.navigate(['/changepassword']).catch((): void => {
227                         // Catch Navigation Error
228                     });
229                 } else {
230                     this.router.navigate([this.returnUrl]).catch((): void => {
231                         // Catch Navigation Error
232                     });
233                     this.isAdminShow = sessionStorage.getItem('admin_show') === 'true' ? true : false;
234                     this.isUserShow = sessionStorage.getItem('user_show') === 'true' ? true : false;
235                     setTimeout((): void => {
236                         if (this.isAdminShow === true || this.isUserShow === true) {
237                             this.generateData();
238                         }
239                     }, this.epochTime1000);
240                 }
241                 sessionStorage.removeItem('returnUrl');
242             }, (err: HttpErrorResponse): void => {
243                 this.isLoadingResults = false;
244                 this.restService.handleError(err, 'post');
245             });
246     }
247
248     /** Fetching the data from server to load it in toaster @public */
249     public generateData(): void {
250         const userID: string = sessionStorage.getItem('user_id');
251         if (userID !== '') {
252             this.isLoadingResults = true;
253             this.restService.getResource(environment.USERS_URL + '/' + userID).subscribe((userDetails: UserDetail): void => {
254                 this.userDetails = userDetails;
255                 if (!isNullOrUndefined(userDetails)) {
256                     const account: string = this.sharedService.convertEpochTime(!isNullOrUndefined(userDetails._admin) ?
257                         userDetails._admin.account_expire_time : null);
258                     const password: string = this.sharedService.convertEpochTime(!isNullOrUndefined(userDetails._admin) ?
259                         userDetails._admin.password_expire_time : null);
260                     const accountExpire: number = this.sharedService.converEpochToDays(account);
261                     const passwordExpire: number = this.sharedService.converEpochToDays(password);
262                     if (accountExpire >= 0 && accountExpire <= this.expireDays) {
263                         this.accountNoOfDays = String(accountExpire);
264                     }
265                     if (passwordExpire >= 0 && passwordExpire <= this.expireDays) {
266                         this.passwordNoOfDays = String(passwordExpire);
267                     }
268                     this.lastLoginMessage = this.translateService.instant('PAGE.LOGIN.LASTACCESS');
269                     this.failedAttemptsMessage = this.translateService.instant('PAGE.LOGIN.FAILED');
270                     this.accountExpireMessage = this.translateService.instant('PAGE.LOGIN.ACCOUNTEXPIRE');
271                     this.passwordExpireMessage = this.translateService.instant('PAGE.LOGIN.PASSWORDEXPIRE');
272                     this.daysMessage = this.translateService.instant('PAGE.LOGIN.DAYS');
273                     this.lastLogin = sessionStorage.getItem('last_login');
274                     this.failedAttempts = sessionStorage.getItem('failed_count');
275                     if (this.accountNoOfDays !== '0' && this.passwordNoOfDays !== '0' &&
276                         this.accountNoOfDays !== '1' && this.passwordNoOfDays !== '1') {
277                         this.showToaster();
278                     }
279                     this.passwordExpiryToaster();
280                     this.accountExpiryToaster();
281                 }
282                 this.isLoadingResults = false;
283             }, (error: ERRORDATA): void => {
284                 this.isLoadingResults = false;
285                 this.restService.handleError(error, 'get');
286             });
287         }
288     }
289
290     /** To Show or Hide the Password @public */
291     public onShowPassword(): void {
292         this.visiblePassword = !this.visiblePassword;
293     }
294
295     /** To display password expiry Toaster with required data @public */
296     public passwordExpiryToaster(): void {
297         if ((this.accountNoOfDays === '1' && this.passwordNoOfDays === '1') ||
298             (this.accountNoOfDays === '0' && this.passwordNoOfDays === '0')) {
299             this.passwordExpireMessage = this.translateService.instant('PAGE.LOGIN.PASSWORDEXPIRETODAY');
300             this.accountExpireMessage = this.translateService.instant('PAGE.LOGIN.ACCOUNTEXPIRETODAY');
301             if (this.accountNoOfDays === '1') {
302                 this.passwordExpireMessage = this.translateService.instant('PAGE.LOGIN.PASSWORDEXPIRETOMORROW');
303                 this.accountExpireMessage = this.translateService.instant('PAGE.LOGIN.ACCOUNTEXPIRETOMORROW');
304             }
305             this.passwordMessage = '';
306             this.accountMessage = '';
307             this.accountNoOfDays = '';
308             this.passwordNoOfDays = '';
309             this.sharedService.showToaster(this.lastLogin, this.failedAttempts, this.passwordNoOfDays, this.accountNoOfDays,
310                 this.passwordExpireMessage, this.accountExpireMessage, this.passwordMessage, this.accountMessage);
311         } else if (!isNullOrUndefined(this.passwordNoOfDays)) {
312             if ((this.passwordNoOfDays === '0') || this.passwordNoOfDays === '1' ||
313                 (this.passwordNoOfDays === '0' && (isNullOrUndefined(this.accountNoOfDays) || !isNullOrUndefined(this.accountNoOfDays))) ||
314                 (this.passwordNoOfDays === '1' && (isNullOrUndefined(this.accountNoOfDays) || !isNullOrUndefined(this.accountNoOfDays)))
315             ) {
316                 if (this.passwordNoOfDays === '1') {
317                     this.passwordExpireMessage = this.translateService.instant('PAGE.LOGIN.PASSWORDEXPIRETOMORROW');
318                     this.passwordMessage = '';
319                     this.passwordNoOfDays = '';
320                 } else if (this.passwordNoOfDays === '0') {
321                     this.passwordExpireMessage = this.translateService.instant('PAGE.LOGIN.PASSWORDEXPIRETODAY');
322                     this.passwordMessage = '';
323                     this.passwordNoOfDays = '';
324                 }
325                 if (isNullOrUndefined(this.accountNoOfDays)) {
326                     this.sharedService.passwordToaster(this.lastLogin, this.failedAttempts, this.passwordNoOfDays,
327                         this.passwordExpireMessage, this.passwordMessage);
328                 } else {
329                     this.accountDaysCheck();
330                 }
331             }
332         }
333     }
334     /** To check account no.of days with 0 & 1 @public */
335     public accountDaysCheck(): void {
336         if (this.accountNoOfDays === '1') {
337             this.accountExpireMessage = this.translateService.instant('PAGE.LOGIN.ACCOUNTEXPIRETOMORROW');
338             this.accountMessage = '';
339             this.accountNoOfDays = '';
340         } else if (this.accountNoOfDays === '0') {
341             this.accountExpireMessage = this.translateService.instant('PAGE.LOGIN.ACCOUNTEXPIRETODAY');
342             this.accountMessage = '';
343             this.accountNoOfDays = '';
344         } else {
345             this.accountExpireMessage = this.accountExpireMessage = this.translateService.instant('PAGE.LOGIN.ACCOUNTEXPIRE');
346             this.accountMessage = this.translateService.instant('PAGE.LOGIN.DAYS');
347         }
348         this.sharedService.showToaster(this.lastLogin, this.failedAttempts, this.passwordNoOfDays, this.accountNoOfDays,
349             this.passwordExpireMessage, this.accountExpireMessage, this.passwordMessage, this.accountMessage);
350     }
351     /** To display account expiry Toaster with required data @public */
352     public accountExpiryToaster(): void {
353         if (!isNullOrUndefined(this.accountNoOfDays)) {
354             if ((this.accountNoOfDays === '0') || (this.accountNoOfDays === '1') || ((this.accountNoOfDays === '0') &&
355                 (isNullOrUndefined(this.passwordNoOfDays) || !isNullOrUndefined(this.passwordNoOfDays))) ||
356                 ((this.accountNoOfDays === '1') && (isNullOrUndefined(this.passwordNoOfDays) || !isNullOrUndefined(this.passwordNoOfDays)))
357                 && this.passwordNoOfDays !== '0' && this.passwordNoOfDays !== '1') {
358                 if (this.accountNoOfDays === '1') {
359                     this.accountExpireMessage = this.translateService.instant('PAGE.LOGIN.ACCOUNTEXPIRETOMORROW');
360                     this.accountMessage = '';
361                     this.accountNoOfDays = '';
362                 } else if (this.accountNoOfDays === '0') {
363                     this.accountExpireMessage = this.translateService.instant('PAGE.LOGIN.ACCOUNTEXPIRETODAY');
364                     this.accountMessage = '';
365                     this.accountNoOfDays = '';
366                 }
367                 if (isNullOrUndefined(this.passwordNoOfDays)) {
368                     this.sharedService.accountToaster(this.lastLogin, this.failedAttempts,
369                         this.accountNoOfDays, this.accountExpireMessage, this.accountMessage);
370                 } else {
371                     this.passwordDaysCheck();
372                 }
373             }
374         }
375     }
376     /** To check password no.of days with 0 & 1 @public */
377     public passwordDaysCheck(): void {
378         if (this.passwordNoOfDays === '1') {
379             this.passwordExpireMessage = this.translateService.instant('PAGE.LOGIN.PASSWORDEXPIRETOMORROW');
380             this.passwordMessage = '';
381             this.passwordNoOfDays = '';
382         } else if (this.passwordNoOfDays === '0') {
383             this.passwordExpireMessage = this.translateService.instant('PAGE.LOGIN.PASSWORDEXPIRETODAY');
384             this.passwordMessage = '';
385             this.passwordNoOfDays = '';
386         } else {
387             this.passwordExpireMessage = this.translateService.instant('PAGE.LOGIN.PASSWORDEXPIRE');
388             this.passwordMessage = this.translateService.instant('PAGE.LOGIN.DAYS');
389         }
390         this.sharedService.showToaster(this.lastLogin, this.failedAttempts, this.passwordNoOfDays, this.accountNoOfDays,
391             this.passwordExpireMessage, this.accountExpireMessage, this.passwordMessage, this.accountMessage);
392     }
393     /** To display password & account expiry Toaster with required data @public */
394     public showToaster(): void {
395         if (!isNullOrUndefined(this.accountNoOfDays) && !isNullOrUndefined(this.passwordNoOfDays)) {
396             this.toaster.info(this.lastLoginMessage + ':' + '&nbsp' + this.lastLogin +
397                 '</br>' + this.failedAttemptsMessage + ':' + '&nbsp' + this.failedAttempts +
398                 '</br>' + this.passwordExpireMessage + '&nbsp' + this.passwordNoOfDays + '&nbsp' + this.daysMessage +
399                 '</br>' + this.accountExpireMessage + '&nbsp' + this.accountNoOfDays + '&nbsp' + this.daysMessage,
400                 this.translateService.instant('PAGE.LOGIN.LOGINHISTORY'), this.toasterSettings);
401         } else if (!isNullOrUndefined(this.accountNoOfDays) || !isNullOrUndefined(this.passwordNoOfDays)) {
402             if (!isNullOrUndefined(this.passwordNoOfDays)) {
403                 this.toaster.info(this.lastLoginMessage + ':' + '&nbsp' + this.lastLogin +
404                     '</br>' + this.failedAttemptsMessage + ':' + '&nbsp' + this.failedAttempts +
405                     '</br>' + this.passwordExpireMessage + '&nbsp' + this.passwordNoOfDays + '&nbsp' + this.daysMessage,
406                     this.translateService.instant('PAGE.LOGIN.LOGINHISTORY'), this.toasterSettings);
407             } else if (!isNullOrUndefined(this.accountNoOfDays)) {
408                 this.toaster.info(
409                     this.lastLoginMessage + ':' + '&nbsp' + this.lastLogin +
410                     '</br>' + this.failedAttemptsMessage + ':' + '&nbsp' + this.failedAttempts +
411                     '</br>' + this.accountExpireMessage + '&nbsp' + this.accountNoOfDays + '&nbsp' + this.daysMessage,
412                     this.translateService.instant('PAGE.LOGIN.LOGINHISTORY'), this.toasterSettings);
413             }
414         } else {
415             this.toaster.info(this.lastLoginMessage + ':' + '&nbsp' + this.lastLogin +
416                 '</br>' + this.failedAttemptsMessage + ':' + '&nbsp' + this.failedAttempts,
417                 this.translateService.instant('PAGE.LOGIN.LOGINHISTORY'), this.toasterSettings);
418         }
419     }
420 }