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 'util';
31 import { ProjectModel } from '../models/VNFDModel';
32 import { RestService } from './RestService';
35 * An Injectable is a class adorned with the @Injectable decorator function.
36 * @Injectable takes a metadata object that tells Angular how to compile and run module code
39 export class AuthenticationService {
41 * Get method for Observable loggedIn
43 get isLoggedIn(): Observable<boolean> {
44 return this.loggedIn.asObservable();
48 * Get method for Observable Username
50 get username(): Observable<string> {
51 return this.userName.asObservable();
54 /** Get method for project name */
55 get ProjectName(): Observable<string> {
56 return this.projectName$.asObservable();
58 /** To inject services @public */
59 public injector: Injector;
61 /** Instance for modal service @public */
62 public modalService: NgbModal;
64 /** Handle 401 response for multiple API calls */
65 public handle401: boolean = true;
67 /** contains return URL link @public */
68 public returnUrl: string;
70 /** Holds the username in condition of type BehaviorSubject<string> @public */
71 public userName: BehaviorSubject<string> = new BehaviorSubject<string>('');
73 /** Holds the projectname in condition of type BehaviorSubject<string> @public */
74 public projectName$: BehaviorSubject<string> = new BehaviorSubject<string>('');
76 /** Holds the instance of router class @private */
77 private router: Router;
79 /** Holds the logged in condition of type BehaviorSubject<boolean> @private */
80 private loggedIn: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
82 /** Hold Rest Service Objects */
83 private restService: RestService;
85 /** Holds auth payloads @private */
88 /** Holds header options for auth service @private */
89 private httpOptions: HttpHeaders;
91 /** handle idle time out service @private */
94 /** create the instance of the component */
95 constructor(injector: Injector) {
96 this.injector = injector;
97 this.router = this.injector.get(Router);
98 this.restService = this.injector.get(RestService);
99 this.modalService = this.injector.get(NgbModal);
100 this.idle = this.injector.get(Idle);
101 if (localStorage.getItem('id_token') !== null) {
102 this.loggedIn.next(true);
104 this.loggedIn.next(false);
106 this.userName.next(localStorage.getItem('username'));
110 * Send request and authenticate the user
111 * @param user of type User
113 public login(username: string, password: string): Observable<{}> {
115 this.setPayLoad(username, password);
116 const apiURLHeader: APIURLHEADER = {
117 url: environment.GENERATETOKEN_URL,
118 httpOptions: { headers: this.httpOptions }
120 return this.restService.postResource(apiURLHeader, this.payLoad)
121 .pipe(map((data: ProjectModel) => {
123 this.setLocalStorage(data);
124 this.idle.watch(true);
125 this.loggedIn.next(true);
126 this.handle401 = true;
127 this.userName.next(data.username);
128 return this.loggedIn;
130 }, (error: ERRORDATA) => { this.restService.handleError(error, 'post'); }
134 /** Set headers for auth session @public */
135 public setHeader(): void {
136 this.httpOptions = new HttpHeaders({
137 'Content-Type': 'application/json; charset=UTF-8',
138 Accept: 'application/json',
139 'Cache-Control': 'no-cache, no-store, must-revalidate, max-age=0'
143 /** Set payloads for auth session @public */
144 public setPayLoad(username: string, password: string): void {
145 this.payLoad = JSON.stringify({
151 /** set local storage on auth process @public */
152 public setLocalStorage(data: ProjectModel): void {
153 localStorage.setItem('id_token', data.id);
154 localStorage.setItem('expires', data.expires.toString());
155 localStorage.setItem('username', data.username);
156 localStorage.setItem('isAdmin', (data.admin) ? 'true' : 'false');
157 localStorage.setItem('project_id', data.project_id);
158 localStorage.setItem('project', data.project_name);
159 localStorage.setItem('token_state', data.id);
160 this.projectName$.next(data.project_name);
162 /** Destory tokens API response handling @public */
163 public logoutResponse(): void {
164 this.loggedIn.next(false);
165 const langCode: string = localStorage.getItem('languageCode');
166 const redirecturl: string = isNullOrUndefined(localStorage.getItem('returnUrl')) ? '/' : localStorage.getItem('returnUrl');
167 localStorage.clear();
168 localStorage.setItem('languageCode', langCode);
169 localStorage.setItem('returnUrl', redirecturl);
170 localStorage.setItem('token_state', null);
172 this.router.navigate(['login']).catch();
175 * Logout the user & clearing the token.
177 public logout(): void {
178 this.returnUrl = this.router.url;
179 localStorage.setItem('returnUrl', this.returnUrl);
180 this.modalService.dismissAll();
183 /** Destory tokens on logout @private */
184 private destoryToken(): void {
185 const tokenID: string = localStorage.getItem('id_token');
186 if (tokenID !== null) {
187 const deletingURl: string = environment.GENERATETOKEN_URL + '/' + tokenID;
188 this.restService.deleteResource(deletingURl).subscribe((res: {}) => {
189 this.logoutResponse();
190 }, (error: ERRORDATA) => {
191 this.restService.handleError(error, 'delete');