Bug 1383 Error when consulting NS instance's topology
[osm/NG-UI.git] / src / services / AuthenticationService.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 Auth service
20  */
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';
33
34 /**
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
37  */
38 @Injectable()
39 export class AuthenticationService {
40     /**
41      * Get method for  Observable loggedIn
42      */
43     get isLoggedIn(): Observable<boolean> {
44         return this.loggedIn.asObservable();
45     }
46
47     /**
48      * Get method for Observable Username
49      */
50     get username(): Observable<string> {
51         return this.userName.asObservable();
52     }
53
54     /** Get method for project name */
55     get ProjectName(): Observable<string> {
56         return this.projectName$.asObservable();
57     }
58     /** To inject services @public */
59     public injector: Injector;
60
61     /** Instance for modal service @public */
62     public modalService: NgbModal;
63
64     /** Handle 401 response for multiple API calls */
65     public handle401: boolean = true;
66
67     /** contains return URL link @public */
68     public returnUrl: string;
69
70     /** Holds the username in condition of type BehaviorSubject<string> @public */
71     public userName: BehaviorSubject<string> = new BehaviorSubject<string>('');
72
73     /** Holds the projectname in condition of type BehaviorSubject<string> @public */
74     public projectName$: BehaviorSubject<string> = new BehaviorSubject<string>('');
75
76     /** Holds the instance of router class @private */
77     private router: Router;
78
79     /** Holds the logged in condition of type BehaviorSubject<boolean> @private */
80     private loggedIn: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
81
82     /** Hold Rest Service Objects */
83     private restService: RestService;
84
85     /** Holds auth payloads @private */
86     private payLoad: {};
87
88     /** Holds header options for auth service @private */
89     private httpOptions: HttpHeaders;
90
91     /** handle idle time out service @private */
92     private idle: Idle;
93
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);
103         } else {
104             this.loggedIn.next(false);
105         }
106         this.userName.next(localStorage.getItem('username'));
107     }
108
109     /**
110      * Send request and authenticate the user
111      * @param user of type User
112      */
113     public login(username: string, password: string): Observable<{}> {
114         this.setHeader();
115         this.setPayLoad(username, password);
116         const apiURLHeader: APIURLHEADER = {
117             url: environment.GENERATETOKEN_URL,
118             httpOptions: { headers: this.httpOptions }
119         };
120         return this.restService.postResource(apiURLHeader, this.payLoad)
121             .pipe(map((data: ProjectModel) => {
122                 if (data) {
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;
129                 }
130             }, (error: ERRORDATA) => { this.restService.handleError(error, 'post'); }
131             ));
132     }
133
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'
140         });
141     }
142
143     /** Set payloads for auth session @public  */
144     public setPayLoad(username: string, password: string): void {
145         this.payLoad = JSON.stringify({
146             username,
147             password
148         });
149     }
150
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);
161     }
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         const osmVersion: string = isNullOrUndefined(localStorage.getItem('osmVersion')) ? '' : localStorage.getItem('osmVersion');
168         localStorage.clear();
169         localStorage.setItem('languageCode', langCode);
170         localStorage.setItem('returnUrl', redirecturl);
171         localStorage.setItem('token_state', null);
172         localStorage.setItem('osmVersion', osmVersion);
173         this.idle.stop();
174         this.router.navigate(['login']).catch();
175     }
176     /**
177      * Logout the user & clearing the token.
178      */
179     public logout(): void {
180         this.returnUrl = this.router.url;
181         localStorage.setItem('returnUrl', this.returnUrl);
182         this.modalService.dismissAll();
183         this.destoryToken();
184     }
185     /** Destory tokens on logout @private */
186     private destoryToken(): void {
187         const tokenID: string = localStorage.getItem('id_token');
188         if (tokenID !== null) {
189             const deletingURl: string = environment.GENERATETOKEN_URL + '/' + tokenID;
190             this.restService.deleteResource(deletingURl).subscribe((res: {}) => {
191                 this.logoutResponse();
192             }, (error: ERRORDATA) => {
193                 this.restService.handleError(error, 'delete');
194             });
195         }
196     }
197 }