blob: 3498f1f3bfc01628e31ef2f9764a6a9289f08f3b [file] [log] [blame]
kumaran.m3b4814a2020-05-01 19:48:54 +05301/*
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 */
21import { HttpHeaders } from '@angular/common/http';
22import { Injectable, Injector } from '@angular/core';
23import { Router } from '@angular/router';
24import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
25import { Idle } from '@ng-idle/core';
26import { APIURLHEADER, ERRORDATA } from 'CommonModel';
27import { environment } from 'environment';
28import { BehaviorSubject, Observable } from 'rxjs';
29import { map } from 'rxjs/operators';
30import { isNullOrUndefined } from 'util';
31import { ProjectModel } from '../models/VNFDModel';
32import { 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()
39export 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);
SANDHYA.JSa055cd92023-05-10 18:23:06 +0530101 if (sessionStorage.getItem('id_token') !== null) {
kumaran.m3b4814a2020-05-01 19:48:54 +0530102 this.loggedIn.next(true);
103 } else {
104 this.loggedIn.next(false);
105 }
SANDHYA.JSa055cd92023-05-10 18:23:06 +0530106 this.userName.next(sessionStorage.getItem('username'));
kumaran.m3b4814a2020-05-01 19:48:54 +0530107 }
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 {
SANDHYA.JSa055cd92023-05-10 18:23:06 +0530153 sessionStorage.setItem('id_token', data.id);
154 sessionStorage.setItem('expires', data.expires.toString());
155 sessionStorage.setItem('username', data.username);
156 sessionStorage.setItem('isAdmin', (data.admin) ? 'true' : 'false');
157 sessionStorage.setItem('project_id', data.project_id);
158 sessionStorage.setItem('project', data.project_name);
159 sessionStorage.setItem('token_state', data.id);
kumaran.m3b4814a2020-05-01 19:48:54 +0530160 this.projectName$.next(data.project_name);
161 }
162 /** Destory tokens API response handling @public */
163 public logoutResponse(): void {
164 this.loggedIn.next(false);
SANDHYA.JSa055cd92023-05-10 18:23:06 +0530165 const langCode: string = sessionStorage.getItem('languageCode');
166 const redirecturl: string = isNullOrUndefined(sessionStorage.getItem('returnUrl')) ? '/' : sessionStorage.getItem('returnUrl');
167 const osmVersion: string = isNullOrUndefined(sessionStorage.getItem('osmVersion')) ? '' : sessionStorage.getItem('osmVersion');
168 sessionStorage.clear();
169 sessionStorage.setItem('languageCode', langCode);
170 sessionStorage.setItem('returnUrl', redirecturl);
171 sessionStorage.setItem('token_state', null);
172 sessionStorage.setItem('osmVersion', osmVersion);
kumaran.m3b4814a2020-05-01 19:48:54 +0530173 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;
SANDHYA.JSa055cd92023-05-10 18:23:06 +0530181 sessionStorage.setItem('returnUrl', this.returnUrl);
kumaran.m3b4814a2020-05-01 19:48:54 +0530182 this.modalService.dismissAll();
183 this.destoryToken();
184 }
185 /** Destory tokens on logout @private */
186 private destoryToken(): void {
SANDHYA.JSa055cd92023-05-10 18:23:06 +0530187 const tokenID: string = sessionStorage.getItem('id_token');
kumaran.m3b4814a2020-05-01 19:48:54 +0530188 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}