2 Copyright 2020 TATA ELXSI
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
8 http://www.apache.org/licenses/LICENSE-2.0
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.
16 Author: KUMARAN M (kumaran.m@tataelxsi.co.in), RAJESH S (rajesh.s@tataelxsi.co.in), BARATH KUMAR R (barath.r@tataelxsi.co.in)
21 import { HttpHeaders } from '@angular/common/http';
22 import { Injectable, Injector } from '@angular/core';
23 import { Router } from '@angular/router';
24 import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
25 import { Idle } from '@ng-idle/core';
26 import { APIURLHEADER, ERRORDATA } from 'CommonModel';
27 import { environment } from 'environment';
28 import { BehaviorSubject, Observable } from 'rxjs';
29 import { map } from 'rxjs/operators';
30 import { isNullOrUndefined } from 'SharedService';
31 import { SharedService } from 'SharedService';
32 import { ProjectModel } from '../models/VNFDModel';
33 import { RestService } from './RestService';
36 * An Injectable is a class adorned with the @Injectable decorator function.
37 * @Injectable takes a metadata object that tells Angular how to compile and run module code
40 export class AuthenticationService {
41 /** To inject services @public */
42 public injector: Injector;
44 /** Instance for modal service @public */
45 public modalService: NgbModal;
47 /** Handle 401 response for multiple API calls */
48 public handle401: boolean = true;
50 /** contains return URL link @public */
51 public returnUrl: string;
53 /** Holds the username in condition of type BehaviorSubject<string> @public */
54 public userName: BehaviorSubject<string> = new BehaviorSubject<string>('');
56 /** Holds the projectname in condition of type BehaviorSubject<string> @public */
57 public projectName$: BehaviorSubject<string> = new BehaviorSubject<string>('');
59 /** Holds the instance of router class @private */
60 private router: Router;
62 /** Holds the logged in condition of type BehaviorSubject<boolean> @private */
63 private loggedIn: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
65 /** Holds the change password in condition of type BehaviorSubject<boolean> @private */
66 private changePassword: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
68 /** Holds the forgotpassword in condition of type BehaviorSubject<string> @public */
69 public forgotPassword: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
71 /** Hold Rest Service Objects */
72 private restService: RestService;
74 /** Holds auth payloads @private */
77 /** Holds header options for auth service @private */
78 private httpOptions: HttpHeaders;
80 /** handle idle time out service @private */
83 /** Contains all methods related to shared @private */
84 private sharedService: SharedService;
86 /** create the instance of the component */
87 constructor(injector: Injector) {
88 this.injector = injector;
89 this.router = this.injector.get(Router);
90 this.restService = this.injector.get(RestService);
91 this.modalService = this.injector.get(NgbModal);
92 this.idle = this.injector.get(Idle);
93 this.sharedService = this.injector.get(SharedService);
94 if (sessionStorage.getItem('username') !== null) {
95 this.loggedIn.next(true);
96 this.changePassword.next(false);
97 } else if (sessionStorage.getItem('firstLogin') !== null) {
98 this.changePassword.next(true);
99 this.loggedIn.next(false);
101 this.loggedIn.next(false);
103 this.userName.next(sessionStorage.getItem('username'));
104 this.redirectToPage();
108 * Get method for Observable loggedIn
110 get isLoggedIn(): Observable<boolean> {
111 return this.loggedIn.asObservable();
115 * Get method for Observable changepassword
117 get isChangePassword(): Observable<boolean> {
118 return this.changePassword.asObservable();
122 * Get method for Observable forgotssword
124 get isForgotPassword(): Observable<boolean> {
125 return this.forgotPassword.asObservable();
129 * Get method for Observable Username
131 get username(): Observable<string> {
132 return this.userName.asObservable();
135 /** Get method for project name */
136 get ProjectName(): Observable<string> {
137 return this.projectName$.asObservable();
141 * Send request and authenticate the user
142 * @param user of type User
144 public login(username: string, password: string): Observable<{}> {
146 this.setPayLoad(username, password);
147 const apiURLHeader: APIURLHEADER = {
148 url: environment.GENERATETOKEN_URL,
149 httpOptions: { headers: this.httpOptions }
151 return this.restService.postResource(apiURLHeader, this.payLoad)
152 .pipe(map((data: ProjectModel): BehaviorSubject<boolean> => {
153 if (data.message === 'change_password') {
154 sessionStorage.setItem('firstLogin', 'true');
155 sessionStorage.setItem('id_token', data.id);
156 sessionStorage.setItem('user_id', data.user_id);
157 this.idle.watch(true);
158 this.changePassword.next(true);
159 this.loggedIn.next(false);
160 return this.changePassword;
162 this.setLocalStorage(data);
163 this.idle.watch(true);
164 this.loggedIn.next(true);
165 this.handle401 = true;
166 this.userName.next(data.username);
167 return this.loggedIn;
169 }, (error: ERRORDATA): void => { this.restService.handleError(error, 'post'); }
173 /** Set headers for auth session @public */
174 public setHeader(): void {
175 this.httpOptions = new HttpHeaders({
176 'Content-Type': 'application/json; charset=UTF-8',
177 Accept: 'application/json',
178 'Cache-Control': 'no-cache, no-store, must-revalidate, max-age=0'
182 /** Set payloads for auth session @public */
183 public setPayLoad(username: string, password: string): void {
184 this.payLoad = JSON.stringify({
190 /** set local storage on auth process @public */
191 public setLocalStorage(data: ProjectModel): void {
192 if (!isNullOrUndefined(data.timeout)) {
193 sessionStorage.setItem('timeout', data.timeout);
195 sessionStorage.setItem('id_token', data.id);
196 sessionStorage.setItem('expires', data.expires.toString());
197 sessionStorage.setItem('username', data.username);
198 sessionStorage.setItem('isAdmin', (data.admin) ? 'true' : 'false');
199 sessionStorage.setItem('project_id', data.project_id);
200 sessionStorage.setItem('project', data.project_name);
201 sessionStorage.setItem('token_state', data.id);
202 sessionStorage.setItem('user_id', data.user_id);
203 sessionStorage.setItem('user_show', String(data.user_show));
204 sessionStorage.setItem('admin_show', String(data.admin_show));
205 sessionStorage.setItem('last_login', this.sharedService.convertEpochTime(!isNullOrUndefined(data.last_login) ? data.last_login : null));
206 sessionStorage.setItem('failed_count', data.login_count);
207 this.projectName$.next(data.project_name);
209 /** Destory tokens API response handling @public */
210 public logoutResponse(): void {
211 this.loggedIn.next(false);
212 this.changePassword.next(false);
213 const langCode: string = sessionStorage.getItem('languageCode');
214 const redirecturl: string = isNullOrUndefined(sessionStorage.getItem('returnUrl')) ? '/' : sessionStorage.getItem('returnUrl');
215 const osmVersion: string = isNullOrUndefined(sessionStorage.getItem('osmVersion')) ? '' : sessionStorage.getItem('osmVersion');
216 const timeOut: string = isNullOrUndefined(sessionStorage.getItem('timeout')) ? '1200' : sessionStorage.getItem('timeout');
217 sessionStorage.clear();
218 sessionStorage.setItem('languageCode', langCode);
219 sessionStorage.setItem('returnUrl', redirecturl);
220 sessionStorage.setItem('token_state', null);
221 sessionStorage.setItem('osmVersion', osmVersion);
222 sessionStorage.setItem('timeout', timeOut);
224 this.router.navigate(['login']).catch((): void => {
225 // Catch Navigation Error
229 * Logout the user & clearing the token.
231 public logout(): void {
232 this.returnUrl = this.router.url;
233 sessionStorage.setItem('returnUrl', this.returnUrl);
234 this.modalService.dismissAll();
237 /** Destory tokens on logout @public */
238 public destoryToken(): void {
239 const tokenID: string = sessionStorage.getItem('id_token');
240 if (tokenID !== null) {
241 const deletingURl: string = environment.GENERATETOKEN_URL + '/' + tokenID;
242 this.restService.deleteResource(deletingURl).subscribe((res: {}): void => {
243 this.logoutResponse();
244 }, (error: ERRORDATA): void => {
245 this.restService.handleError(error, 'delete');
250 /** Return to previous page deny access to changepassword */
251 public redirectToPage(): void {
252 if (window.location.pathname === '/changepassword' && sessionStorage.getItem('username') !== null) {
253 window.history.back();
254 } else if (window.location.pathname === '/' && sessionStorage.getItem('firstLogin') === 'true') {
255 this.router.navigate(['/login']).catch((): void => {
256 // Catch Navigation Error