From 5cc7b616960ab62d0bc31c707016ea59201e6c24 Mon Sep 17 00:00:00 2001 From: Abigail Cabascango Date: Wed, 25 Jan 2023 14:50:12 -0500 Subject: [PATCH] refactor: delete azure login and create a base logic to login auth --- .dev.env | Bin 607 -> 571 bytes src/app/modules/home/home.component.html | 2 - src/app/modules/home/home.component.scss | 0 src/app/modules/home/home.component.spec.ts | 58 ------ src/app/modules/home/home.component.ts | 26 --- src/app/modules/login/login.component.ts | 70 +------ .../services/azure.ad.b2c.service.spec.ts | 189 ------------------ .../login/services/azure.ad.b2c.service.ts | 89 --------- .../login/services/login.service.spec.ts | 167 ---------------- .../modules/login/services/login.service.ts | 104 ++-------- .../user/services/user-info.service.ts | 14 +- 11 files changed, 20 insertions(+), 699 deletions(-) delete mode 100644 src/app/modules/home/home.component.html delete mode 100644 src/app/modules/home/home.component.scss delete mode 100644 src/app/modules/home/home.component.spec.ts delete mode 100644 src/app/modules/home/home.component.ts delete mode 100644 src/app/modules/login/services/azure.ad.b2c.service.spec.ts delete mode 100644 src/app/modules/login/services/azure.ad.b2c.service.ts delete mode 100644 src/app/modules/login/services/login.service.spec.ts diff --git a/.dev.env b/.dev.env index 5db598c8d5fc1f09be3da5d92834511cff4108ad..f11f3b969bb5ff4ae46559dd0480a2d00fcdc10c 100644 GIT binary patch literal 571 zcmV-B0>u3QM@dveQdv+`0Ct7+z$#6VtPk(ANF9H%2+4RkQKAngTD=6mfLF>U7ec`~J3TZRFEy4NC9U z6$W}=eV6O(6YnsF*C6XYy)PG{GSNO7mC@7HrH4`bg_`K2(JII%E{1aX_z{>EKPff7q7aLJp!s;%6z!>Ae_T}h5^Wp59LXm%&ISCEd&79)&-jns7z|cH1w+yn8!z7U7~rP zV!;1*oJ)z}kh_@GJSRMCaUsJFiM&G2U~P0P#qS$>lBg8bdrdK?G>Q8^0TlDH0~>u8 z33(@cP*$PYnTxINFYPkQ{5oM zKJjPCa4_f>K~>-(OMC(Sxqk5z2tAZ67Dj2(&eoX-|FAq@V4n)!948n?>t18s)iC=| J{=-*d_0S0e8Xo`v literal 607 zcmV-l0-*f>M@dveQdv+`0H!&9AOfcH?Q=@FZP%E3cm18^r4p$3Fa6v>3=q{6PtZG_ z7OtGV)c8~IY?eDmRXU*f__2jx{=hQXxORwdY4EGcj^Rs}r9iXpH^d1@#F5}?j2LGR zh1DFCCc<`8SD7@lm1Yx5=&sA-c{DQs$#Qd44l^bBG*vSy#WX1(|9noVld!q=v~K~U zgPPGZ9q+e)xRQYwqx|Uf*Z8!5Ll5ySv`llf4|^#mwFw3EisnAT&|$eFEkw47MCyzU z{x8Y6%w``KeF?`Q`9?a56OOMV2k%WFG=H%5kEjWh+EK1&VSyh%P|3cJr|wGPN7kmp zj71$@tM^HXYI0&WapAimfYS=dwK|Gw*`8M zPOo-FDs`tkK9Wvh=pq7kX`G-+BLfsP!Qn*t@IO22J(eDAWMri9<0F+9-z7r0R}7k` t^RtsHZbmj - diff --git a/src/app/modules/home/home.component.scss b/src/app/modules/home/home.component.scss deleted file mode 100644 index e69de29bb..000000000 diff --git a/src/app/modules/home/home.component.spec.ts b/src/app/modules/home/home.component.spec.ts deleted file mode 100644 index af9af201c..000000000 --- a/src/app/modules/home/home.component.spec.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { waitForAsync, ComponentFixture, TestBed } from '@angular/core/testing'; -import { MockStore, provideMockStore } from '@ngrx/store/testing'; -import { AzureAdB2CService } from '../login/services/azure.ad.b2c.service'; -import { LoadUser } from '../user/store/user.actions'; -import { HomeComponent } from './home.component'; -import { LoginService } from '../login/services/login.service'; - -describe('HomeComponent', () => { - let component: HomeComponent; - let azureAdB2CService: AzureAdB2CService; - let store: MockStore; - let fixture: ComponentFixture; - const initialState = {}; - const azureB2CServiceStub = { - getUserId: () => 'user_id', - }; - const loginServiceStub = { - getUserId: () => 'user_id', - }; - - beforeEach( - waitForAsync(() => { - TestBed.configureTestingModule({ - declarations: [HomeComponent], - providers: [ - provideMockStore({ initialState }), - { provide: AzureAdB2CService, useValue: azureB2CServiceStub }, - { provide: LoginService, useValue: loginServiceStub }, - ], - }).compileComponents(); - }) - ); - - beforeEach(() => { - fixture = TestBed.createComponent(HomeComponent); - azureAdB2CService = TestBed.inject(AzureAdB2CService); - store = TestBed.inject(MockStore); - component = fixture.componentInstance; - fixture.detectChanges(); - store.setState(initialState); - }); - - it('should be created', () => { - expect(component).toBeTruthy(); - }); - - it('onInit, LoadUser action is dispatched', () => { - component.isProduction = true; - const userId = 'user_id'; - spyOn(azureAdB2CService, 'getUserId').and.returnValue(userId); - spyOn(store, 'dispatch'); - - component.ngOnInit(); - - expect(azureAdB2CService.getUserId).toHaveBeenCalled(); - expect(store.dispatch).toHaveBeenCalledWith(new LoadUser(userId)); - }); -}); diff --git a/src/app/modules/home/home.component.ts b/src/app/modules/home/home.component.ts deleted file mode 100644 index 74ef5a166..000000000 --- a/src/app/modules/home/home.component.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { Component, OnInit } from '@angular/core'; -import { Store } from '@ngrx/store'; -import { LoadUser } from 'src/app/modules/user/store/user.actions'; -import { environment } from 'src/environments/environment'; -import { EnvironmentType } from 'src/environments/enum'; -import { AzureAdB2CService } from '../login/services/azure.ad.b2c.service'; -import { LoginService } from '../login/services/login.service'; - -@Component({ - selector: 'app-home', - templateUrl: './home.component.html', - styleUrls: ['./home.component.scss'], -}) -export class HomeComponent implements OnInit { - isProduction = environment.production === EnvironmentType.TT_PROD_LEGACY; - constructor( - private azureAdB2CService: AzureAdB2CService, - private loginService: LoginService, - private store: Store - ) { } - - ngOnInit(): void { - const userId = this.isProduction ? this.azureAdB2CService.getUserId() : this.loginService.getUserId(); - this.store.dispatch(new LoadUser(userId)); - } -} diff --git a/src/app/modules/login/login.component.ts b/src/app/modules/login/login.component.ts index 91ad64a60..9b8d9ad3f 100644 --- a/src/app/modules/login/login.component.ts +++ b/src/app/modules/login/login.component.ts @@ -1,5 +1,4 @@ import { Component, OnInit, NgZone } from '@angular/core'; -import { AzureAdB2CService } from './services/azure.ad.b2c.service'; import { Router } from '@angular/router'; import { FeatureToggleCookiesService } from '../shared/feature-toggles/feature-toggle-cookies/feature-toggle-cookies.service'; @@ -20,13 +19,11 @@ declare global { styleUrls: ['./login.component.scss'], }) export class LoginComponent implements OnInit { - isProduction = environment.production === EnvironmentType.TT_PROD_LEGACY; cliendId = CLIENT_URL; auth2: any; constructor( - private azureAdB2CService: AzureAdB2CService, private router: Router, private featureToggleCookiesService: FeatureToggleCookiesService, private loginService?: LoginService, @@ -34,73 +31,8 @@ export class LoginComponent implements OnInit { private ngZone?: NgZone ) {} - - googleAuthSDK() { - const sdkLoaded = 'googleSDKLoaded'; - const gapi = 'gapi'; - - (window as any)[sdkLoaded] = () => { - (window as any)[gapi].load('auth2', () => { - this.auth2 = ( window as any)[gapi].auth2.init({ - client_id: this.cliendId, - plugin_name: 'login', - cookiepolicy: 'single_host_origin', - scope: 'profile email' - }); - }); - }; - - (async (d, s, id) => { - const keyGoogle = 'src'; - const gjs = d.getElementsByTagName(s)[1]; - let js = gjs; - if (d.getElementById(id)) { return; } - js = d.createElement(s); js.id = id; - js[keyGoogle] = 'https://accounts.google.com/gsi/client'; - gjs.parentNode.insertBefore(js, gjs); - })(document, 'script', 'async defer'); - } - ngOnInit() { - - this.googleAuthSDK(); - this.loginService.isLogin().subscribe(isLogin => { - if (isLogin) { - this.router.navigate(['']); - } - }); - - window.handleCredentialResponse = (response) => { - const {credential = ''} = response; - this.featureToggleCookiesService.setCookies(); - this.loginService.setLocalStorage('idToken', credential); - this.loginService.getUser(credential).subscribe((resp) => { - this.loginService.setCookies(); - const tokenObject = JSON.stringify(resp); - const tokenJson = JSON.parse(tokenObject); - this.loginService.setLocalStorage('user', tokenJson.token); - this.ngZone.run(() => this.router.navigate([''])); - }); - }; - } - - login(): void { - if (this.azureAdB2CService.isLogin()) { - this.router.navigate(['']); - } else { - this.azureAdB2CService.signIn().subscribe(() => { - this.featureToggleCookiesService.setCookies(); - this.azureAdB2CService.setCookies(); - const userId = this.azureAdB2CService.getUserId(); - this.userService.loadUser(userId).subscribe((user) => { - const userGroups = { - groups: user.groups - }; - this.loginService.setLocalStorage('user', JSON.stringify(userGroups)); - this.router.navigate(['']); - }); - }); - } + this.loginService.fetchAndCheckUserPermissions(); } } diff --git a/src/app/modules/login/services/azure.ad.b2c.service.spec.ts b/src/app/modules/login/services/azure.ad.b2c.service.spec.ts deleted file mode 100644 index baf6a364c..000000000 --- a/src/app/modules/login/services/azure.ad.b2c.service.spec.ts +++ /dev/null @@ -1,189 +0,0 @@ -import { inject, TestBed } from '@angular/core/testing'; -import { Account, UserAgentApplication } from 'msal'; -import { AzureAdB2CService } from './azure.ad.b2c.service'; -import { CookieService } from 'ngx-cookie-service'; - -describe('AzureAdB2CService', () => { - let service: AzureAdB2CService; - let cookieService: CookieService; - let account: Account; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [], - }); - service = TestBed.inject(AzureAdB2CService); - cookieService = TestBed.inject(CookieService); - account = { - accountIdentifier: 'abc', - homeAccountIdentifier: 'abc', - userName: 'abc', - name: 'abc', - idToken: { - iss: ' http://hostname.com/12345/v0/', - emails: 'abcd' - }, - idTokenClaims: {}, - sid: 'abc', - environment: 'abc', - }; - }); - - it('should be created', inject([AzureAdB2CService], (apiService: AzureAdB2CService) => { - expect(apiService).toBeTruthy(); - })); - - it('on signIn should call msal loginPopup', () => { - spyOn(UserAgentApplication.prototype, 'loginPopup').and.returnValue( - new Promise((resolve) => { - resolve(); - }) - ); - service.signIn(); - expect(UserAgentApplication.prototype.loginPopup).toHaveBeenCalled(); - }); - - it('on logout should call msal logout and verify if user localStorage is removed', () => { - spyOn(UserAgentApplication.prototype, 'logout').and.returnValue(); - spyOn(cookieService, 'deleteAll'); - spyOn(localStorage, 'removeItem').withArgs('user'); - - service.logout(); - - expect(cookieService.deleteAll).toHaveBeenCalled(); - expect(localStorage.removeItem).toHaveBeenCalledWith('user'); - expect(UserAgentApplication.prototype.logout).toHaveBeenCalled(); - }); - - it('should get Account name from UserAgentApplication', () => { - spyOn(UserAgentApplication.prototype, 'getAccount').and.returnValues(account); - - const name = service.getName(); - - expect(UserAgentApplication.prototype.getAccount).toHaveBeenCalled(); - expect(name).toEqual(account.name); - }); - - it('isAdmin false when extension_role !== time-tracker-admin', async () => { - spyOn(UserAgentApplication.prototype, 'getAccount').and.returnValue(account); - - const isAdmin = service.isAdmin(); - - expect(isAdmin).toEqual(false); - }); - - it('isAdmin when extension_role === time-tracker-admin', async () => { - const adminAccount = { ...account }; - adminAccount.idToken.extension_role = 'time-tracker-admin'; - - spyOn(UserAgentApplication.prototype, 'getAccount').and.returnValue(adminAccount); - - const isAdmin = service.isAdmin(); - - expect(isAdmin).toBeTruthy(); - }); - - it('isLogin returns true if UserAgentApplication has a defined Account and token cookie exist', () => { - spyOn(UserAgentApplication.prototype, 'getAccount').and.returnValue(account); - spyOn(cookieService, 'check').and.returnValue(true); - - const isLogin = service.isLogin(); - - expect(UserAgentApplication.prototype.getAccount).toHaveBeenCalled(); - expect(cookieService.check).toHaveBeenCalled(); - expect(isLogin).toEqual(true); - }); - - it('isLogin returns false if UserAgentApplication has a defined Account and token cookie does not exist', () => { - spyOn(UserAgentApplication.prototype, 'getAccount').and.returnValue(account); - spyOn(cookieService, 'check').and.returnValue(false); - - const isLogin = service.isLogin(); - - expect(UserAgentApplication.prototype.getAccount).toHaveBeenCalled(); - expect(cookieService.check).toHaveBeenCalled(); - expect(isLogin).toEqual(false); - }); - - it('isLogin returns false if UserAgentApplication has a null value for Account', () => { - spyOn(UserAgentApplication.prototype, 'getAccount').and.returnValue(null); - - const isLogin = service.isLogin(); - - expect(UserAgentApplication.prototype.getAccount).toHaveBeenCalled(); - expect(isLogin).toEqual(false); - }); - - it('setTenantId should save a tenantId in local storage', () => { - spyOn(UserAgentApplication.prototype, 'getAccount').and.returnValue(account); - spyOn(cookieService, 'check').and.returnValue(true); - spyOn(localStorage, 'setItem').withArgs('tenant_id', '12345'); - - const isLogin = service.isLogin(); - service.setTenantId(); - - expect(UserAgentApplication.prototype.getAccount).toHaveBeenCalled(); - expect(cookieService.check).toHaveBeenCalled(); - expect(isLogin).toEqual(true); - expect(localStorage.setItem).toHaveBeenCalledWith('tenant_id', '12345'); - }); - - it('setTenantId should not save tenantId if login is false ', () => { - spyOn(UserAgentApplication.prototype, 'getAccount').and.returnValue(null); - spyOn(localStorage, 'setItem'); - const isLogin = service.isLogin(); - expect(UserAgentApplication.prototype.getAccount).toHaveBeenCalled(); - expect(isLogin).toEqual(false); - expect(localStorage.setItem).not.toHaveBeenCalled(); - }); - - it('getTenantId should get the tenantId from local storage', () => { - const tenantId = '12345'; - spyOn(localStorage, 'getItem').and.returnValue(tenantId); - - const resp = service.getTenantId(); - - expect(localStorage.getItem).toHaveBeenCalled(); - expect(resp).toEqual(tenantId); - }); - - it('getBearerToken should get the bearer token from local storage', () => { - const token = '12345abc'; - spyOn(localStorage, 'getItem').and.returnValue(token); - - const resp = service.getBearerToken(); - - expect(localStorage.getItem).toHaveBeenCalled(); - expect(resp).toEqual(token); - }); - - it('should get email from UserAgentApplication', () => { - spyOn(UserAgentApplication.prototype, 'getAccount').and.returnValues(account); - - const name = service.getName(); - - expect(UserAgentApplication.prototype.getAccount).toHaveBeenCalled(); - }); - - it('should group from UserAgentApplication', () => { - spyOn(UserAgentApplication.prototype, 'getAccount').and.returnValues(account); - - const name = service.getUserGroup(); - - expect(UserAgentApplication.prototype.getAccount).toHaveBeenCalled(); - }); - - it('should get userId from UserAgentApplication', () => { - spyOn(UserAgentApplication.prototype, 'getAccount').and.returnValues(account); - - service.getUserId(); - - expect(UserAgentApplication.prototype.getAccount).toHaveBeenCalled(); - }); - - it('should get email', () => { - spyOn(UserAgentApplication.prototype, 'getAccount').and.returnValues(account); - const email = service.getUserEmail(); - expect(email).toEqual('a'); - }); -}); diff --git a/src/app/modules/login/services/azure.ad.b2c.service.ts b/src/app/modules/login/services/azure.ad.b2c.service.ts deleted file mode 100644 index c8a87ac31..000000000 --- a/src/app/modules/login/services/azure.ad.b2c.service.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { Injectable } from '@angular/core'; -import { UserAgentApplication } from 'msal'; -import { from, Observable } from 'rxjs'; -import { CookieService } from 'ngx-cookie-service'; -import { AUTHORITY, CLIENT_ID, SCOPES } from '../../../../environments/environment'; - -@Injectable({ - providedIn: 'root', -}) -export class AzureAdB2CService { - constructor(private cookieService?: CookieService) { } - - msalConfig: any = { - auth: { - clientId: CLIENT_ID, - authority: AUTHORITY, - validateAuthority: false, - }, - cache: { - cacheLocation: 'localStorage', - }, - }; - - tokenRequest = { - scopes: SCOPES, - }; - - msal = new UserAgentApplication(this.msalConfig); - - signIn(): Observable { - return from(this.msal.loginPopup(this.tokenRequest)); - } - - logout() { - this.cookieService.deleteAll(); - this.msal.logout(); - localStorage.removeItem('user'); - } - - getName(): string { - return this.msal.getAccount().name; - } - - // TODO: inused method - isAdmin() { - return this.msal.getAccount()?.idToken?.extension_role === 'time-tracker-admin'; - } - - isLogin() { - return this.msal.getAccount() && this.cookieService.check('msal.idtoken') ? true : false; - } - - setCookies() { - this.cookieService.set('msal.idtoken', this.getBearerToken(), 30); - this.cookieService.set('msal.client.info', this.getBearerClientInfo(), 30); - } - - setTenantId() { - if (this.msal.getAccount() && this.msal.getAccount().idToken) { - const pathArray = this.msal.getAccount().idToken.iss.split('/'); - const tenantId = pathArray[3]; - localStorage.setItem('tenant_id', tenantId); - } - } - - getTenantId(): string { - return localStorage.getItem('tenant_id'); - } - - getBearerClientInfo(): string { - return localStorage.getItem('msal.client.info'); - } - - getBearerToken(): string { - return localStorage.getItem('msal.idtoken'); - } - - getUserEmail(): string { - return this.msal.getAccount().idToken?.emails[0]; - } - - getUserGroup(): string { - return this.msal.getAccount().idToken?.extension_role; - } - - getUserId(): string { - return this.msal.getAccount().accountIdentifier; - } -} diff --git a/src/app/modules/login/services/login.service.spec.ts b/src/app/modules/login/services/login.service.spec.ts deleted file mode 100644 index 94e246cc6..000000000 --- a/src/app/modules/login/services/login.service.spec.ts +++ /dev/null @@ -1,167 +0,0 @@ -import { HttpClient } from '@angular/common/http'; -import { HttpClientTestingModule } from '@angular/common/http/testing'; -import { TestBed } from '@angular/core/testing'; -import { JwtHelperService } from '@auth0/angular-jwt'; -import { SocialAuthService } from 'angularx-social-login'; -import { CookieService } from 'ngx-cookie-service'; -import { of } from 'rxjs'; - -import { LoginService } from './login.service'; - -describe('LoginService', () => { - let service: LoginService; - let cookieService: CookieService; - let socialAuthService: SocialAuthService; - let account; - const socialAuthServiceStub = jasmine.createSpyObj('SocialAuthService', ['signOut', 'signIn']); - const httpClientSpy = jasmine.createSpyObj('HttpClient', ['post', 'get']); - const cookieStoreStub = {}; - const helper = new JwtHelperService(); - const getAccountInfo = () => { - return helper.decodeToken(account); - }; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [HttpClientTestingModule], - providers: [ - { providers: CookieService, useValue: cookieStoreStub }, - { provide: SocialAuthService, useValue: socialAuthServiceStub }, - { provide: HttpClient, useValue: httpClientSpy } - ], - }); - service = TestBed.inject(LoginService); - cookieService = TestBed.inject(CookieService); - socialAuthService = TestBed.inject(SocialAuthService); - account = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6ImFiYyIsIm5hbWUiOiJhYmMiLCJlbWFpbCI6ImFiYyIsImdyb3VwcyI6WyJhYmMiXX0.UNxyDT8XzXJhI1F3LySBU7TJlpENPUPHj8my7Obw2ZM'; - let store = {}; - const mockLocalStorage = { - getItem: (key: string): string => { - return key in store ? store[key] : null; - }, - setItem: (key: string, value: string) => { - store[key] = `${value}`; - }, - clear: () => { - store = {}; - }, - }; - spyOn(localStorage, 'getItem').and.callFake(mockLocalStorage.getItem); - spyOn(localStorage, 'setItem').and.callFake(mockLocalStorage.setItem); - spyOn(localStorage, 'clear').and.callFake(mockLocalStorage.clear); - localStorage.setItem('user', account); - localStorage.setItem('user2', '"test_token_123"'); - }); - - it('should be created', () => { - expect(service).toBeTruthy(); - }); - - it('should get name from localStorage', () => { - const name = service.getName(); - - expect(name).toEqual(getAccountInfo().name); - }); - - it('should get userId from localStorage', () => { - const userId = service.getUserId(); - - expect(userId).toEqual(getAccountInfo().id); - }); - - it('should get UserGroup from localStorage', () => { - const userGroup = service.getUserGroup(); - - expect(userGroup).toEqual(getAccountInfo().groups); - }); - - it('should get BearerToken from localStorage', () => { - localStorage.setItem('idToken', 'token'); - - const bearerToken = service.getBearerToken(); - - expect(bearerToken).toEqual('token'); - }); - - it('should set key and value in localStorage', () => { - service.setLocalStorage('key', 'value'); - - const value = localStorage.getItem('key'); - - expect(value).toEqual('value'); - }); - - it('load a user by sending a token using POST', () => { - const token = 'test_123'; - service.baseUrl = '/users'; - const mockSuccessDataPost = { - SUCCESS: true, - data: {} - }; - httpClientSpy.post.and.returnValue(of(mockSuccessDataPost)); - service.getUser(token).subscribe(); - expect(httpClientSpy.post).toHaveBeenCalled(); - }); - - it('should return true when user is Login', () => { - spyOn(cookieService, 'check').and.returnValue(true); - spyOn(service, 'isValidToken').and.returnValue(of(true)); - - service.isLogin().subscribe(isLogin => { - expect(isLogin).toEqual(true); - }); - }); - - it('should return false when user is not Login', () => { - spyOn(service, 'isValidToken').and.returnValue(of(false)); - - service.isLogin().subscribe(isLogin => { - expect(isLogin).toEqual(false); - }); - }); - - it('should logout with social angularx-social-login', () => { - spyOn(cookieService, 'deleteAll').and.returnValue(); - - service.logout(); - - expect(localStorage.clear).toHaveBeenCalled(); - expect(cookieService.deleteAll).toHaveBeenCalled(); - }); - - it('should call cookieService when app is isLegacyProd', () => { - service.isLegacyProd = true; - service.localStorageKey = 'user2'; - spyOn(cookieService, 'check').and.returnValue(true); - spyOn(service, 'isValidToken').and.returnValue(of(true)); - service.isLogin().subscribe(isLogin => { - expect(cookieService.check).toHaveBeenCalled(); - }); - }); - - it('should call JSON parse when app is isLegacyProd', () => { - spyOn(JSON, 'parse').and.returnValue('test_user_123'); - service.isLegacyProd = true; - service.localStorageKey = 'user2'; - service.getUserId(); - service.getName(); - service.getUserEmail(); - service.getUserGroup(); - expect(JSON.parse).toHaveBeenCalled(); - }); - - it('should call setLocalStorage when there is a new_token ', () => { - spyOn(cookieService, 'check').and.returnValue(true); - spyOn(service, 'setLocalStorage'); - const token = 'test123'; - service.baseUrl = '/users'; - const mockSuccessDataPost = { - SUCCESS: true, - new_token: 'test_token' - }; - httpClientSpy.post.and.returnValue(of(mockSuccessDataPost)); - service.isValidToken(token).subscribe(); - expect(service.setLocalStorage).toHaveBeenCalled(); - expect(cookieService.check).toHaveBeenCalled(); - }); -}); diff --git a/src/app/modules/login/services/login.service.ts b/src/app/modules/login/services/login.service.ts index 8a0869829..1ca347909 100644 --- a/src/app/modules/login/services/login.service.ts +++ b/src/app/modules/login/services/login.service.ts @@ -16,6 +16,8 @@ export class LoginService { isLegacyProd: boolean = environment.production === EnvironmentType.TT_PROD_LEGACY; localStorageKey = this.isLegacyProd ? 'user2' : 'user'; + + //get all of users from DB constructor( private http?: HttpClient, private cookieService?: CookieService, @@ -24,101 +26,27 @@ export class LoginService { this.helper = new JwtHelperService(); } - logout() { - this.cookieService.deleteAll(); - localStorage.clear(); - } - - isLogin() { - const token = this.getLocalStorage(this.localStorageKey); - if (this.isLegacyProd) { - const user = JSON.parse(token); - return user && this.cookieService.check('idtoken') ? of(true) : of(false); - } else { - return this.isValidToken(token); - } - } - - getUserId(): string { - const token = this.getLocalStorage(this.localStorageKey); - let user; - if (this.isLegacyProd) { - user = JSON.parse(token); - } else { - user = this.helper.decodeToken(token); + getUserPermissions = async () => { + try { + const response = this.http.get(`${this.baseUrl}/users/validate/token`); + return response?.status === 200 ? response?.data : null; + } catch (error) { + return null; } - return user[UserEnum.ID]; } - getName(): string { - const token = this.getLocalStorage(this.localStorageKey); - let user; - if (this.isLegacyProd) { - user = JSON.parse(token); - } else { - user = this.helper.decodeToken(token); - } - return user[UserEnum.NAME]; - } - - getUserEmail(): string { - const token = this.getLocalStorage(this.localStorageKey); - let user; - if (this.isLegacyProd) { - user = JSON.parse(token); - } else { - user = this.helper.decodeToken(token); - } - return user[UserEnum.EMAIL]; + logout() { + this.cookieService.deleteAll(); + localStorage.clear(); } - getUserGroup(): string { - const token = this.getLocalStorage(this.localStorageKey); - let user; - if (this.isLegacyProd) { - user = JSON.parse(token); - } else { - user = this.helper.decodeToken(token); + fetchAndCheckUserPermissions() { + const cookiesAuth = this.getUserPermissions(); + if(cookiesAuth.getRole() == 'timetracker-admin' && cookiesAuth.getUserGroup() == 'timetracker-admin'){ + return cookiesAuth.getRole(); } - return user[UserEnum.GROUPS]; - } - - getBearerToken(): string { - return this.getLocalStorage('idToken'); - } - - getUser(tokenString: string) { - const body = { - token: tokenString, - }; - - return this.http.post(`${this.baseUrl}/login`, body); - } - - setCookies() { - this.cookieService.set('idtoken', this.getLocalStorage('idToken'), 30); - } - - getLocalStorage(key: string) { - return localStorage.getItem(key); - } - - setLocalStorage(key: string, value: string) { - localStorage.setItem(key, value); - } + sessionStorage.clear(); - isValidToken(token: string) { - const body = { token }; - return this.http.post(`${this.baseUrl}/validate-token`, body).pipe( - map((response) => { - const responseString = JSON.stringify(response); - const responseJson = JSON.parse(responseString); - if (responseJson.new_token) { - this.setLocalStorage('user', responseJson.new_token); - } - return responseString !== '{}' && this.cookieService.check('idtoken') ? true : false; - }) - ); } } diff --git a/src/app/modules/user/services/user-info.service.ts b/src/app/modules/user/services/user-info.service.ts index 983861090..f89ce4b30 100644 --- a/src/app/modules/user/services/user-info.service.ts +++ b/src/app/modules/user/services/user-info.service.ts @@ -19,17 +19,9 @@ export class UserInfoService { } isMemberOf(groupName: string): Observable { - const token = this.loginService.getLocalStorage('user'); - if (this.isLegacyProduction) { - const user = JSON.parse(token); - const {groups = []} = user; - return of(groups.includes(groupName)); - } else { - const user = this.helper.decodeToken(token); - const {groups = []} = user; - if (groups.includes(groupName)) { - return this.loginService.isValidToken(token); - } + const userCookie = this.loginService.fetchAndCheckUserPermissions(); + if (userCookie === 'timetracker-admin') { + return of(true); } return of(false); }