Fix Bug 2293: Password Expiry and Account Expiry Time Issue for today & tomorrow...
[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     /** Utilizes auth service for any auth operations @private */
130     private authService: AuthenticationService;
131
132     /** contians form builder module @private */
133     private formBuilder: FormBuilder;
134
135     /** Holds teh instance of AuthService class of type AuthService @private */
136     private router: Router;
137
138     /** Contains tranlsate instance @private */
139     private translateService: TranslateService;
140
141     /** Contains toaster instance @private */
142     private toaster: ToastrService;
143
144     /** express number for expire days @private */
145     // eslint-disable-next-line @typescript-eslint/no-magic-numbers
146     private expireDays: number = 5;
147
148     /** express number for time manupulation 1000 */
149     // eslint-disable-next-line @typescript-eslint/no-magic-numbers
150     private epochTime1000: number = 1000;
151
152     /** contains toaster settings */
153     private toasterSettings: {} = {
154         enableHtml: true,
155         closeButton: true,
156         timeOut: 2000
157     };
158
159     // creates instance of login component
160     constructor(injector: Injector) {
161         this.injector = injector;
162         this.restService = this.injector.get(RestService);
163         this.authService = this.injector.get(AuthenticationService);
164         this.formBuilder = this.injector.get(FormBuilder);
165         this.router = this.injector.get(Router);
166         this.sharedService = this.injector.get(SharedService);
167         this.translateService = this.injector.get(TranslateService);
168         this.toaster = this.injector.get(ToastrService);
169     }
170
171     /**
172      * Lifecyle Hooks the trigger before component is instantiate
173      */
174     public ngOnInit(): void {
175         this.isLoggedIn$ = this.authService.isLoggedIn;
176         this.isLoggedIn$.subscribe((res: boolean): void => {
177             this.loggedIn = res;
178         });
179         if (this.loggedIn === true) {
180             this.router.navigate(['/']).catch((): void => {
181                 // Catch Navigation Error
182             });
183         }
184         this.isChangePassword$ = this.authService.isChangePassword;
185         this.isChangePassword$.subscribe((res: boolean): void => {
186             this.changePassword = res;
187         });
188         if (this.changePassword === true) {
189             this.router.navigate(['changepassword']).catch((): void => {
190                 // Catch Navigation Error
191             });
192         }
193
194         this.loginForm = this.formBuilder.group({
195             userName: ['', [Validators.required]],
196             password: ['', [Validators.required]]
197         });
198         this.returnUrl = isNullOrUndefined(sessionStorage.getItem('returnUrl')) ? '/' : sessionStorage.getItem('returnUrl');
199     }
200
201     /**
202      * called on form submit @private onSubmit
203      */
204     public onSubmit(): void {
205         this.submitted = true;
206         if (this.loginForm.invalid) {
207             return;
208         }
209         this.isLoadingResults = true;
210         this.sharedService.cleanForm(this.loginForm);
211         this.isLoadingResults = false;
212         if (!this.loginForm.invalid) {
213             this.loginUser();
214         }
215     }
216
217     /** Login User @public */
218     public loginUser(): void {
219         this.authService.login(this.loginForm.value.userName, this.loginForm.value.password).subscribe(
220             (data: {}): void => {
221                 this.isLoadingResults = false;
222                 if (this.changePassword === true && this.loggedIn === false) {
223                     this.router.navigate(['/changepassword']).catch((): void => {
224                         // Catch Navigation Error
225                     });
226                 } else {
227                     this.router.navigate([this.returnUrl]).catch((): void => {
228                         // Catch Navigation Error
229                     });
230                     this.isAdminShow = sessionStorage.getItem('admin_show') === 'true' ? true : false;
231                     this.isUserShow = sessionStorage.getItem('user_show') === 'true' ? true : false;
232                     setTimeout((): void => {
233                         if (this.isAdminShow === true || this.isUserShow === true) {
234                             this.generateData();
235                         }
236                     }, this.epochTime1000);
237                 }
238                 sessionStorage.removeItem('returnUrl');
239             }, (err: HttpErrorResponse): void => {
240                 this.isLoadingResults = false;
241                 this.restService.handleError(err, 'post');
242             });
243     }
244
245     /** Fetching the data from server to load it in toaster @public */
246     public generateData(): void {
247         const userID: string = sessionStorage.getItem('user_id');
248         if (userID !== '') {
249             this.isLoadingResults = true;
250             this.restService.getResource(environment.USERS_URL + '/' + userID).subscribe((userDetails: UserDetail): void => {
251                 this.userDetails = userDetails;
252                 if (!isNullOrUndefined(userDetails)) {
253                     const account: string = this.sharedService.convertEpochTime(!isNullOrUndefined(userDetails._admin) ?
254                         userDetails._admin.account_expire_time : null);
255                     const password: string = this.sharedService.convertEpochTime(!isNullOrUndefined(userDetails._admin) ?
256                         userDetails._admin.password_expire_time : null);
257                     const accountExpire: number = this.sharedService.converEpochToDays(account);
258                     const passwordExpire: number = this.sharedService.converEpochToDays(password);
259                     if (accountExpire >= 0 && accountExpire <= this.expireDays) {
260                         this.accountNoOfDays = String(accountExpire);
261                     }
262                     if (passwordExpire >= 0 && passwordExpire <= this.expireDays) {
263                         this.passwordNoOfDays = String(passwordExpire);
264                     }
265                     this.lastLoginMessage = this.translateService.instant('PAGE.LOGIN.LASTACCESS');
266                     this.failedAttemptsMessage = this.translateService.instant('PAGE.LOGIN.FAILED');
267                     this.accountExpireMessage = this.translateService.instant('PAGE.LOGIN.ACCOUNTEXPIRE');
268                     this.passwordExpireMessage = this.translateService.instant('PAGE.LOGIN.PASSWORDEXPIRE');
269                     this.daysMessage = this.translateService.instant('PAGE.LOGIN.DAYS');
270                     this.lastLogin = sessionStorage.getItem('last_login');
271                     this.failedAttempts = sessionStorage.getItem('failed_count');
272                     if (this.accountNoOfDays !== '0' && this.passwordNoOfDays !== '0' &&
273                         this.accountNoOfDays !== '1' && this.passwordNoOfDays !== '1') {
274                         this.showToaster();
275                     }
276                     this.passwordExpiryToaster();
277                     this.accountExpiryToaster();
278                 }
279                 this.isLoadingResults = false;
280             }, (error: ERRORDATA): void => {
281                 this.isLoadingResults = false;
282                 this.restService.handleError(error, 'get');
283             });
284         }
285     }
286
287     /** To display password expiry Toaster with required data @public */
288     public passwordExpiryToaster(): void {
289         if ((this.accountNoOfDays === '1' && this.passwordNoOfDays === '1') ||
290             (this.accountNoOfDays === '0' && this.passwordNoOfDays === '0')) {
291             this.passwordExpireMessage = this.translateService.instant('PAGE.LOGIN.PASSWORDEXPIRETODAY');
292             this.accountExpireMessage = this.translateService.instant('PAGE.LOGIN.ACCOUNTEXPIRETODAY');
293             if (this.accountNoOfDays === '1') {
294                 this.passwordExpireMessage = this.translateService.instant('PAGE.LOGIN.PASSWORDEXPIRETOMORROW');
295                 this.accountExpireMessage = this.translateService.instant('PAGE.LOGIN.ACCOUNTEXPIRETOMORROW');
296             }
297             this.passwordMessage = '';
298             this.accountMessage = '';
299             this.accountNoOfDays = '';
300             this.passwordNoOfDays = '';
301             this.sharedService.showToaster(this.lastLogin, this.failedAttempts, this.passwordNoOfDays, this.accountNoOfDays,
302                 this.passwordExpireMessage, this.accountExpireMessage, this.passwordMessage, this.accountMessage);
303         } else if (!isNullOrUndefined(this.passwordNoOfDays)) {
304             if ((this.passwordNoOfDays === '0') || this.passwordNoOfDays === '1' ||
305                 (this.passwordNoOfDays === '0' && (isNullOrUndefined(this.accountNoOfDays) || !isNullOrUndefined(this.accountNoOfDays))) ||
306                 (this.passwordNoOfDays === '1' && (isNullOrUndefined(this.accountNoOfDays) || !isNullOrUndefined(this.accountNoOfDays)))
307             ) {
308                 if (this.passwordNoOfDays === '1') {
309                     this.passwordExpireMessage = this.translateService.instant('PAGE.LOGIN.PASSWORDEXPIRETOMORROW');
310                     this.passwordMessage = '';
311                     this.passwordNoOfDays = '';
312                 } else if (this.passwordNoOfDays === '0') {
313                     this.passwordExpireMessage = this.translateService.instant('PAGE.LOGIN.PASSWORDEXPIRETODAY');
314                     this.passwordMessage = '';
315                     this.passwordNoOfDays = '';
316                 }
317                 if (isNullOrUndefined(this.accountNoOfDays)) {
318                     this.sharedService.passwordToaster(this.lastLogin, this.failedAttempts, this.passwordNoOfDays,
319                         this.passwordExpireMessage, this.passwordMessage);
320                 } else {
321                     this.accountDaysCheck();
322                 }
323             }
324         }
325     }
326     /** To check account no.of days with 0 & 1 @public */
327     public accountDaysCheck(): void {
328         if (this.accountNoOfDays === '1') {
329             this.accountExpireMessage = this.translateService.instant('PAGE.LOGIN.ACCOUNTEXPIRETOMORROW');
330             this.accountMessage = '';
331             this.accountNoOfDays = '';
332         } else if (this.accountNoOfDays === '0') {
333             this.accountExpireMessage = this.translateService.instant('PAGE.LOGIN.ACCOUNTEXPIRETODAY');
334             this.accountMessage = '';
335             this.accountNoOfDays = '';
336         } else {
337             this.accountExpireMessage = this.accountExpireMessage = this.translateService.instant('PAGE.LOGIN.ACCOUNTEXPIRE');
338             this.accountMessage = this.translateService.instant('PAGE.LOGIN.DAYS');
339         }
340         this.sharedService.showToaster(this.lastLogin, this.failedAttempts, this.passwordNoOfDays, this.accountNoOfDays,
341             this.passwordExpireMessage, this.accountExpireMessage, this.passwordMessage, this.accountMessage);
342     }
343     /** To display account expiry Toaster with required data @public */
344     public accountExpiryToaster(): void {
345         if (!isNullOrUndefined(this.accountNoOfDays)) {
346             if ((this.accountNoOfDays === '0') || (this.accountNoOfDays === '1') || ((this.accountNoOfDays === '0') &&
347                 (isNullOrUndefined(this.passwordNoOfDays) || !isNullOrUndefined(this.passwordNoOfDays))) ||
348                 ((this.accountNoOfDays === '1') && (isNullOrUndefined(this.passwordNoOfDays) || !isNullOrUndefined(this.passwordNoOfDays)))
349                 && this.passwordNoOfDays !== '0' && this.passwordNoOfDays !== '1') {
350                 if (this.accountNoOfDays === '1') {
351                     this.accountExpireMessage = this.translateService.instant('PAGE.LOGIN.ACCOUNTEXPIRETOMORROW');
352                     this.accountMessage = '';
353                     this.accountNoOfDays = '';
354                 } else if (this.accountNoOfDays === '0') {
355                     this.accountExpireMessage = this.translateService.instant('PAGE.LOGIN.ACCOUNTEXPIRETODAY');
356                     this.accountMessage = '';
357                     this.accountNoOfDays = '';
358                 }
359                 if (isNullOrUndefined(this.passwordNoOfDays)) {
360                     this.sharedService.accountToaster(this.lastLogin, this.failedAttempts,
361                         this.accountNoOfDays, this.accountExpireMessage, this.accountMessage);
362                 } else {
363                     this.passwordDaysCheck();
364                 }
365             }
366         }
367     }
368     /** To check password no.of days with 0 & 1 @public */
369     public passwordDaysCheck(): void {
370         if (this.passwordNoOfDays === '1') {
371             this.passwordExpireMessage = this.translateService.instant('PAGE.LOGIN.PASSWORDEXPIRETOMORROW');
372             this.passwordMessage = '';
373             this.passwordNoOfDays = '';
374         } else if (this.passwordNoOfDays === '0') {
375             this.passwordExpireMessage = this.translateService.instant('PAGE.LOGIN.PASSWORDEXPIRETODAY');
376             this.passwordMessage = '';
377             this.passwordNoOfDays = '';
378         } else {
379             this.passwordExpireMessage = this.translateService.instant('PAGE.LOGIN.PASSWORDEXPIRE');
380             this.passwordMessage = this.translateService.instant('PAGE.LOGIN.DAYS');
381         }
382         this.sharedService.showToaster(this.lastLogin, this.failedAttempts, this.passwordNoOfDays, this.accountNoOfDays,
383             this.passwordExpireMessage, this.accountExpireMessage, this.passwordMessage, this.accountMessage);
384     }
385     /** To display password & account expiry Toaster with required data @public */
386     public showToaster(): void {
387         if (!isNullOrUndefined(this.accountNoOfDays) && !isNullOrUndefined(this.passwordNoOfDays)) {
388             this.toaster.info(this.lastLoginMessage + ':' + '&nbsp' + this.lastLogin +
389                 '</br>' + this.failedAttemptsMessage + ':' + '&nbsp' + this.failedAttempts +
390                 '</br>' + this.passwordExpireMessage + '&nbsp' + this.passwordNoOfDays + '&nbsp' + this.daysMessage +
391                 '</br>' + this.accountExpireMessage + '&nbsp' + this.accountNoOfDays + '&nbsp' + this.daysMessage,
392                 this.translateService.instant('PAGE.LOGIN.LOGINHISTORY'), this.toasterSettings);
393         } else if (!isNullOrUndefined(this.accountNoOfDays) || !isNullOrUndefined(this.passwordNoOfDays)) {
394             if (!isNullOrUndefined(this.passwordNoOfDays)) {
395                 this.toaster.info(this.lastLoginMessage + ':' + '&nbsp' + this.lastLogin +
396                     '</br>' + this.failedAttemptsMessage + ':' + '&nbsp' + this.failedAttempts +
397                     '</br>' + this.passwordExpireMessage + '&nbsp' + this.passwordNoOfDays + '&nbsp' + this.daysMessage,
398                     this.translateService.instant('PAGE.LOGIN.LOGINHISTORY'), this.toasterSettings);
399             } else if (!isNullOrUndefined(this.accountNoOfDays)) {
400                 this.toaster.info(
401                     this.lastLoginMessage + ':' + '&nbsp' + this.lastLogin +
402                     '</br>' + this.failedAttemptsMessage + ':' + '&nbsp' + this.failedAttempts +
403                     '</br>' + this.accountExpireMessage + '&nbsp' + this.accountNoOfDays + '&nbsp' + this.daysMessage,
404                     this.translateService.instant('PAGE.LOGIN.LOGINHISTORY'), this.toasterSettings);
405             }
406         } else {
407             this.toaster.info(this.lastLoginMessage + ':' + '&nbsp' + this.lastLogin +
408                 '</br>' + this.failedAttemptsMessage + ':' + '&nbsp' + this.failedAttempts,
409                 this.translateService.instant('PAGE.LOGIN.LOGINHISTORY'), this.toasterSettings);
410         }
411     }
412 }