blob: 9b0f5259775fe03818ce95e757ed582eb5593600 [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';
SANDHYA.JSc84f1122024-06-04 21:50:03 +053030import { isNullOrUndefined } from 'SharedService';
SANDHYA.JS1b17c432023-04-26 17:54:57 +053031import { SharedService } from 'SharedService';
kumaran.m3b4814a2020-05-01 19:48:54 +053032import { ProjectModel } from '../models/VNFDModel';
33import { RestService } from './RestService';
34
35/**
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
38 */
39@Injectable()
40export class AuthenticationService {
kumaran.m3b4814a2020-05-01 19:48:54 +053041 /** To inject services @public */
42 public injector: Injector;
43
44 /** Instance for modal service @public */
45 public modalService: NgbModal;
46
47 /** Handle 401 response for multiple API calls */
48 public handle401: boolean = true;
49
50 /** contains return URL link @public */
51 public returnUrl: string;
52
53 /** Holds the username in condition of type BehaviorSubject<string> @public */
54 public userName: BehaviorSubject<string> = new BehaviorSubject<string>('');
55
56 /** Holds the projectname in condition of type BehaviorSubject<string> @public */
57 public projectName$: BehaviorSubject<string> = new BehaviorSubject<string>('');
58
59 /** Holds the instance of router class @private */
60 private router: Router;
61
62 /** Holds the logged in condition of type BehaviorSubject<boolean> @private */
63 private loggedIn: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
64
SANDHYA.JSa9816552022-04-12 09:07:08 +053065 /** Holds the change password in condition of type BehaviorSubject<boolean> @private */
66 private changePassword: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
67
SANDHYA.JS6c686082024-06-10 21:39:41 +053068 /** Holds the forgotpassword in condition of type BehaviorSubject<string> @public */
69 public forgotPassword: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
70
kumaran.m3b4814a2020-05-01 19:48:54 +053071 /** Hold Rest Service Objects */
72 private restService: RestService;
73
74 /** Holds auth payloads @private */
75 private payLoad: {};
76
77 /** Holds header options for auth service @private */
78 private httpOptions: HttpHeaders;
79
80 /** handle idle time out service @private */
81 private idle: Idle;
82
SANDHYA.JS1b17c432023-04-26 17:54:57 +053083 /** Contains all methods related to shared @private */
84 private sharedService: SharedService;
85
kumaran.m3b4814a2020-05-01 19:48:54 +053086 /** 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);
SANDHYA.JS1b17c432023-04-26 17:54:57 +053093 this.sharedService = this.injector.get(SharedService);
SANDHYA.JS5b35bcd2023-04-27 15:11:06 +053094 if (sessionStorage.getItem('username') !== null) {
kumaran.m3b4814a2020-05-01 19:48:54 +053095 this.loggedIn.next(true);
SANDHYA.JSa9816552022-04-12 09:07:08 +053096 this.changePassword.next(false);
SANDHYA.JS5b35bcd2023-04-27 15:11:06 +053097 } else if (sessionStorage.getItem('firstLogin') !== null) {
SANDHYA.JSa9816552022-04-12 09:07:08 +053098 this.changePassword.next(true);
99 this.loggedIn.next(false);
kumaran.m3b4814a2020-05-01 19:48:54 +0530100 } else {
101 this.loggedIn.next(false);
102 }
SANDHYA.JS5b35bcd2023-04-27 15:11:06 +0530103 this.userName.next(sessionStorage.getItem('username'));
SANDHYA.JSa9816552022-04-12 09:07:08 +0530104 this.redirectToPage();
105 }
106
107 /**
108 * Get method for Observable loggedIn
109 */
110 get isLoggedIn(): Observable<boolean> {
111 return this.loggedIn.asObservable();
112 }
113
114 /**
115 * Get method for Observable changepassword
116 */
117 get isChangePassword(): Observable<boolean> {
118 return this.changePassword.asObservable();
119 }
120
121 /**
SANDHYA.JS6c686082024-06-10 21:39:41 +0530122 * Get method for Observable forgotssword
123 */
124 get isForgotPassword(): Observable<boolean> {
125 return this.forgotPassword.asObservable();
126 }
127
128 /**
SANDHYA.JSa9816552022-04-12 09:07:08 +0530129 * Get method for Observable Username
130 */
131 get username(): Observable<string> {
132 return this.userName.asObservable();
133 }
134
135 /** Get method for project name */
136 get ProjectName(): Observable<string> {
137 return this.projectName$.asObservable();
kumaran.m3b4814a2020-05-01 19:48:54 +0530138 }
139
140 /**
141 * Send request and authenticate the user
142 * @param user of type User
143 */
144 public login(username: string, password: string): Observable<{}> {
145 this.setHeader();
146 this.setPayLoad(username, password);
147 const apiURLHeader: APIURLHEADER = {
148 url: environment.GENERATETOKEN_URL,
149 httpOptions: { headers: this.httpOptions }
150 };
151 return this.restService.postResource(apiURLHeader, this.payLoad)
SANDHYA.JSa9816552022-04-12 09:07:08 +0530152 .pipe(map((data: ProjectModel): BehaviorSubject<boolean> => {
153 if (data.message === 'change_password') {
SANDHYA.JS5b35bcd2023-04-27 15:11:06 +0530154 sessionStorage.setItem('firstLogin', 'true');
155 sessionStorage.setItem('id_token', data.id);
156 sessionStorage.setItem('user_id', data.user_id);
SANDHYA.JSa9816552022-04-12 09:07:08 +0530157 this.idle.watch(true);
158 this.changePassword.next(true);
159 this.loggedIn.next(false);
160 return this.changePassword;
161 } else {
kumaran.m3b4814a2020-05-01 19:48:54 +0530162 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;
168 }
SANDHYA.JSa9816552022-04-12 09:07:08 +0530169 }, (error: ERRORDATA): void => { this.restService.handleError(error, 'post'); }
kumaran.m3b4814a2020-05-01 19:48:54 +0530170 ));
171 }
172
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'
179 });
180 }
181
182 /** Set payloads for auth session @public */
183 public setPayLoad(username: string, password: string): void {
184 this.payLoad = JSON.stringify({
185 username,
186 password
187 });
188 }
189
190 /** set local storage on auth process @public */
191 public setLocalStorage(data: ProjectModel): void {
SANDHYA.JS52474e72024-06-10 21:47:25 +0530192 if (!isNullOrUndefined(data.timeout)) {
193 sessionStorage.setItem('timeout', data.timeout);
194 }
SANDHYA.JS5b35bcd2023-04-27 15:11:06 +0530195 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);
kumaran.m3b4814a2020-05-01 19:48:54 +0530207 this.projectName$.next(data.project_name);
208 }
209 /** Destory tokens API response handling @public */
210 public logoutResponse(): void {
211 this.loggedIn.next(false);
SANDHYA.JSa9816552022-04-12 09:07:08 +0530212 this.changePassword.next(false);
SANDHYA.JS5b35bcd2023-04-27 15:11:06 +0530213 const langCode: string = sessionStorage.getItem('languageCode');
214 const redirecturl: string = isNullOrUndefined(sessionStorage.getItem('returnUrl')) ? '/' : sessionStorage.getItem('returnUrl');
SANDHYA.JS52474e72024-06-10 21:47:25 +0530215 const osmVersion: string = isNullOrUndefined(sessionStorage.getItem('osmVersion')) ? '' : sessionStorage.getItem('osmVersion');
216 const timeOut: string = isNullOrUndefined(sessionStorage.getItem('timeout')) ? '1200' : sessionStorage.getItem('timeout');
SANDHYA.JS5b35bcd2023-04-27 15:11:06 +0530217 sessionStorage.clear();
218 sessionStorage.setItem('languageCode', langCode);
219 sessionStorage.setItem('returnUrl', redirecturl);
220 sessionStorage.setItem('token_state', null);
221 sessionStorage.setItem('osmVersion', osmVersion);
SANDHYA.JS52474e72024-06-10 21:47:25 +0530222 sessionStorage.setItem('timeout', timeOut);
kumaran.m3b4814a2020-05-01 19:48:54 +0530223 this.idle.stop();
SANDHYA.JS0a34dfa2023-04-25 23:59:41 +0530224 this.router.navigate(['login']).catch((): void => {
225 // Catch Navigation Error
226 });
kumaran.m3b4814a2020-05-01 19:48:54 +0530227 }
228 /**
229 * Logout the user & clearing the token.
230 */
231 public logout(): void {
232 this.returnUrl = this.router.url;
SANDHYA.JS5b35bcd2023-04-27 15:11:06 +0530233 sessionStorage.setItem('returnUrl', this.returnUrl);
kumaran.m3b4814a2020-05-01 19:48:54 +0530234 this.modalService.dismissAll();
235 this.destoryToken();
236 }
SANDHYA.JSa9816552022-04-12 09:07:08 +0530237 /** Destory tokens on logout @public */
238 public destoryToken(): void {
SANDHYA.JS5b35bcd2023-04-27 15:11:06 +0530239 const tokenID: string = sessionStorage.getItem('id_token');
kumaran.m3b4814a2020-05-01 19:48:54 +0530240 if (tokenID !== null) {
241 const deletingURl: string = environment.GENERATETOKEN_URL + '/' + tokenID;
SANDHYA.JSa9816552022-04-12 09:07:08 +0530242 this.restService.deleteResource(deletingURl).subscribe((res: {}): void => {
kumaran.m3b4814a2020-05-01 19:48:54 +0530243 this.logoutResponse();
SANDHYA.JSa9816552022-04-12 09:07:08 +0530244 }, (error: ERRORDATA): void => {
kumaran.m3b4814a2020-05-01 19:48:54 +0530245 this.restService.handleError(error, 'delete');
246 });
247 }
248 }
SANDHYA.JSa9816552022-04-12 09:07:08 +0530249
250 /** Return to previous page deny access to changepassword */
251 public redirectToPage(): void {
SANDHYA.JS5b35bcd2023-04-27 15:11:06 +0530252 if (window.location.pathname === '/changepassword' && sessionStorage.getItem('username') !== null) {
SANDHYA.JSa9816552022-04-12 09:07:08 +0530253 window.history.back();
SANDHYA.JS5b35bcd2023-04-27 15:11:06 +0530254 } else if (window.location.pathname === '/' && sessionStorage.getItem('firstLogin') === 'true') {
SANDHYA.JS0a34dfa2023-04-25 23:59:41 +0530255 this.router.navigate(['/login']).catch((): void => {
256 // Catch Navigation Error
257 });
SANDHYA.JSa9816552022-04-12 09:07:08 +0530258 }
259 }
kumaran.m3b4814a2020-05-01 19:48:54 +0530260}