From 0c147513cc5d6f9aa156cf3f64d13eb0820db290 Mon Sep 17 00:00:00 2001 From: Wojciech Duda <69160975+wojd0@users.noreply.github.com> Date: Mon, 9 Jun 2025 17:07:22 +0200 Subject: [PATCH] AAE-35521 Refactor AuthenticationService unit tests (#10922) * AAE-35521 Refactor AuthenticationService * AAE-35521 Remove last ajax call * AAE-35521 Add missing test --- .../basic-alfresco-auth.service.spec.ts | 177 ++++++++++- .../oidc/oidc-authentication.service.spec.ts | 158 ++++++++-- .../services/authentication.service.spec.ts | 287 +++--------------- .../services/base-authentication.service.ts | 2 +- 4 files changed, 351 insertions(+), 273 deletions(-) diff --git a/lib/core/src/lib/auth/basic-auth/basic-alfresco-auth.service.spec.ts b/lib/core/src/lib/auth/basic-auth/basic-alfresco-auth.service.spec.ts index 960dbc2c9f..e7bb0f1d95 100644 --- a/lib/core/src/lib/auth/basic-auth/basic-alfresco-auth.service.spec.ts +++ b/lib/core/src/lib/auth/basic-auth/basic-alfresco-auth.service.spec.ts @@ -20,20 +20,30 @@ import { BasicAlfrescoAuthService } from './basic-alfresco-auth.service'; import { AppConfigService, AppConfigValues } from '../../app-config/app-config.service'; import { ProcessAuth } from './process-auth'; import { ContentAuth } from './content-auth'; -import { HttpClientTestingModule } from '@angular/common/http/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { firstValueFrom } from 'rxjs'; +import { take } from 'rxjs/operators'; describe('BasicAlfrescoAuthService', () => { let basicAlfrescoAuthService: BasicAlfrescoAuthService; + let processAuth: ProcessAuth; + let contentAuth: ContentAuth; + let appConfig: AppConfigService; + let appConfigSpy: jasmine.Spy; beforeEach(() => { TestBed.configureTestingModule({ - imports: [HttpClientTestingModule], - providers: [BasicAlfrescoAuthService] + providers: [BasicAlfrescoAuthService, provideHttpClient()] }); basicAlfrescoAuthService = TestBed.inject(BasicAlfrescoAuthService); - spyOn(TestBed.inject(ProcessAuth), 'getToken').and.returnValue('Mock Process Auth ticket'); - spyOn(TestBed.inject(ContentAuth), 'getToken').and.returnValue('Mock Content Auth ticket'); - const appConfigSpy = spyOn(TestBed.inject(AppConfigService), 'get'); + + processAuth = TestBed.inject(ProcessAuth); + spyOn(processAuth, 'getToken').and.returnValue('Mock Process Auth ticket'); + contentAuth = TestBed.inject(ContentAuth); + spyOn(contentAuth, 'getToken').and.returnValue('Mock Content Auth ticket'); + + appConfig = TestBed.inject(AppConfigService); + appConfigSpy = spyOn(appConfig, 'get'); appConfigSpy.withArgs(AppConfigValues.CONTEXTROOTBPM).and.returnValue('activiti-app'); appConfigSpy.withArgs(AppConfigValues.CONTEXTROOTECM).and.returnValue('alfresco'); }); @@ -59,4 +69,159 @@ describe('BasicAlfrescoAuthService', () => { const ticket = basicAlfrescoAuthService.getTicketEcmBase64('http://www.example.com/activiti-app/alfresco/mock-api-url'); expect(ticket).toEqual('Basic Mock Process Auth ticket'); }); + + describe('login', () => { + let contentAuthSpy: jasmine.Spy; + let processAuthSpy: jasmine.Spy; + + beforeEach(() => { + contentAuthSpy = spyOn(contentAuth, 'login'); + processAuthSpy = spyOn(processAuth, 'login'); + }); + + it('should return both ECM and BPM tickets after the login', async () => { + appConfigSpy.withArgs(AppConfigValues.PROVIDERS).and.returnValue('ALL'); + const mockContentTicket = { ticket: 'mock-content-ticket' }; + const mockProcessTicket = { ticket: 'mock-process-ticket' }; + const onLogin = firstValueFrom(basicAlfrescoAuthService.onLogin.pipe(take(1))); + contentAuthSpy.and.returnValue(Promise.resolve(mockContentTicket)); + processAuthSpy.and.returnValue(Promise.resolve(mockProcessTicket)); + + const result = await firstValueFrom(basicAlfrescoAuthService.login('username', 'password')); + + expect(result).toEqual({ + type: 'ALL', + ticket: [mockContentTicket, mockProcessTicket] + }); + expect(contentAuth.login).toHaveBeenCalledWith('username', 'password'); + expect(processAuth.login).toHaveBeenCalledWith('username', 'password'); + expect(await onLogin).toBe('success'); + }); + + it('should return login fail on ECM login failure', async () => { + appConfigSpy.withArgs(AppConfigValues.PROVIDERS).and.returnValue('ECM'); + const mockError = 'ECM login failed'; + contentAuthSpy.and.returnValue(Promise.reject(mockError)); + + const onError = firstValueFrom(basicAlfrescoAuthService.onError.pipe(take(1))); + + await expectAsync(firstValueFrom(basicAlfrescoAuthService.login('username', 'password'))).toBeRejectedWith(mockError); + + expect(contentAuth.login).toHaveBeenCalledWith('username', 'password'); + expect(processAuth.login).not.toHaveBeenCalled(); + expect(await onError).toBe('ECM login failed'); + }); + + it('should return login fail on BPM login failure', async () => { + appConfigSpy.withArgs(AppConfigValues.PROVIDERS).and.returnValue('BPM'); + const mockError = 'BPM login failed'; + processAuthSpy.and.returnValue(Promise.reject(mockError)); + + const onError = firstValueFrom(basicAlfrescoAuthService.onError.pipe(take(1))); + + await expectAsync(firstValueFrom(basicAlfrescoAuthService.login('username', 'password'))).toBeRejectedWith(mockError); + + expect(contentAuth.login).not.toHaveBeenCalled(); + expect(processAuth.login).toHaveBeenCalledWith('username', 'password'); + expect(await onError).toBe('BPM login failed'); + }); + }); + + it('isBpmLoggedIn should return value from processAuth', () => { + spyOn(processAuth, 'isLoggedIn').and.returnValue(true); + const result = basicAlfrescoAuthService.isBpmLoggedIn(); + + expect(result).toBeTrue(); + expect(processAuth.isLoggedIn).toHaveBeenCalled(); + }); + + it('isEcmLoggedIn should return value from contentAuth', () => { + spyOn(contentAuth, 'isLoggedIn').and.returnValue(true); + const result = basicAlfrescoAuthService.isEcmLoggedIn(); + + expect(result).toBeTrue(); + expect(contentAuth.isLoggedIn).toHaveBeenCalled(); + }); + + describe('isLoggedIn', () => { + let contentAuthSpy: jasmine.Spy; + let processAuthSpy: jasmine.Spy; + + beforeEach(() => { + contentAuthSpy = spyOn(contentAuth, 'isLoggedIn'); + processAuthSpy = spyOn(processAuth, 'isLoggedIn'); + }); + + it('should default to false when no provider is set', () => { + appConfigSpy.withArgs(AppConfigValues.AUTH_WITH_CREDENTIALS, false).and.returnValue(false); + appConfigSpy.withArgs(AppConfigValues.PROVIDERS).and.returnValue(null); + + const result = basicAlfrescoAuthService.isLoggedIn(); + + expect(result).toBeFalse(); + expect(contentAuth.isLoggedIn).not.toHaveBeenCalled(); + expect(processAuth.isLoggedIn).not.toHaveBeenCalled(); + }); + + describe('BPM provider', () => { + it('should return processAuth value', () => { + appConfigSpy.withArgs(AppConfigValues.AUTH_WITH_CREDENTIALS, false).and.returnValue(true); + appConfigSpy.withArgs(AppConfigValues.PROVIDERS).and.returnValue('BPM'); + processAuthSpy.and.returnValue(true); + + const result = basicAlfrescoAuthService.isLoggedIn(); + + expect(result).toBeTrue(); + expect(processAuth.isLoggedIn).toHaveBeenCalled(); + }); + }); + + describe('ECM provider', () => { + it('should return true when kerberos enabled', () => { + appConfigSpy.withArgs(AppConfigValues.AUTH_WITH_CREDENTIALS, false).and.returnValue(true); + appConfigSpy.withArgs(AppConfigValues.PROVIDERS).and.returnValue('ECM'); + + const result = basicAlfrescoAuthService.isLoggedIn(); + + expect(result).toBeTrue(); + }); + + it('should return contentAuth value when kerberos disabled', () => { + appConfigSpy.withArgs(AppConfigValues.AUTH_WITH_CREDENTIALS, false).and.returnValue(false); + appConfigSpy.withArgs(AppConfigValues.PROVIDERS).and.returnValue('ECM'); + contentAuthSpy.and.returnValue(true); + + const result = basicAlfrescoAuthService.isLoggedIn(); + + expect(result).toBeTrue(); + expect(contentAuth.isLoggedIn).toHaveBeenCalled(); + }); + }); + + describe('ALL provider', () => { + it('should return true when kerberos enabled', () => { + appConfigSpy.withArgs(AppConfigValues.AUTH_WITH_CREDENTIALS, false).and.returnValue(true); + appConfigSpy.withArgs(AppConfigValues.PROVIDERS).and.returnValue('ALL'); + + const result = basicAlfrescoAuthService.isLoggedIn(); + + expect(result).toBeTrue(); + expect(processAuth.isLoggedIn).not.toHaveBeenCalled(); + expect(contentAuth.isLoggedIn).not.toHaveBeenCalled(); + }); + + it('should return true if both contentAuth or processAuth is logged in when kerberos disabled', () => { + appConfigSpy.withArgs(AppConfigValues.AUTH_WITH_CREDENTIALS, false).and.returnValue(false); + appConfigSpy.withArgs(AppConfigValues.PROVIDERS).and.returnValue('ALL'); + contentAuthSpy.and.returnValue(true); + processAuthSpy.and.returnValue(true); + + const result = basicAlfrescoAuthService.isLoggedIn(); + + expect(result).toBeTrue(); + expect(contentAuth.isLoggedIn).toHaveBeenCalled(); + expect(processAuth.isLoggedIn).toHaveBeenCalled(); + }); + }); + }); }); diff --git a/lib/core/src/lib/auth/oidc/oidc-authentication.service.spec.ts b/lib/core/src/lib/auth/oidc/oidc-authentication.service.spec.ts index 04828305f8..e7323bb58c 100644 --- a/lib/core/src/lib/auth/oidc/oidc-authentication.service.spec.ts +++ b/lib/core/src/lib/auth/oidc/oidc-authentication.service.spec.ts @@ -20,7 +20,7 @@ import { OidcAuthenticationService } from './oidc-authentication.service'; import { OAuthService, OAuthStorage } from 'angular-oauth2-oidc'; import { AppConfigService, AuthService } from '@alfresco/adf-core'; import { AUTH_MODULE_CONFIG } from './auth-config'; -import { of } from 'rxjs'; +import { firstValueFrom, of, take, throwError } from 'rxjs'; interface MockAppConfigOAuth2 { oauth2: { @@ -28,59 +28,99 @@ interface MockAppConfigOAuth2 { }; } -class MockAppConfigService { - config: MockAppConfigOAuth2 = { +const mockAppConfigService = { + config: { oauth2: { logoutParameters: ['client_id', 'returnTo', 'response_type'] } - }; + } as MockAppConfigOAuth2, setConfig(newConfig: { logoutParameters: Array }) { this.config.oauth2 = newConfig; - } + }, get(key: string, defaultValue?: { logoutParameters: Array }) { if (key === 'oauth2') { return this.config.oauth2; } + + if (key === 'providers') { + return 'mock-providers'; + } return defaultValue; } -} +}; -class MockOAuthService { - clientId = 'testClientId'; - redirectUri = 'testRedirectUri'; - logOut = jasmine.createSpy(); -} +const mockOAuthService = { + clientId: 'testClientId', + redirectUri: 'testRedirectUri', + logOut: jasmine.createSpy(), + hasValidAccessToken: jasmine.createSpy(), + hasValidIdToken: jasmine.createSpy() +}; + +const mockAuthService = { + baseAuthLogin: jasmine.createSpy() +}; describe('OidcAuthenticationService', () => { let service: OidcAuthenticationService; let oauthService: OAuthService; + let appConfig: AppConfigService; beforeEach(() => { TestBed.configureTestingModule({ providers: [ OidcAuthenticationService, - { provide: AppConfigService, useClass: MockAppConfigService }, - { provide: OAuthService, useClass: MockOAuthService }, + { provide: AppConfigService, useValue: mockAppConfigService }, + { provide: OAuthService, useValue: mockOAuthService }, { provide: OAuthStorage, useValue: {} }, { provide: AUTH_MODULE_CONFIG, useValue: {} }, - { provide: AuthService, useValue: {} } + { provide: AuthService, useValue: mockAuthService } ] }); service = TestBed.inject(OidcAuthenticationService); oauthService = TestBed.inject(OAuthService); + appConfig = TestBed.inject(AppConfigService); }); it('should be created', () => { expect(service).toBeTruthy(); }); + describe('login', () => { + it('should call AuthService with credentials', async () => { + const appConfigSpy = spyOn(mockAppConfigService, 'get').and.callThrough(); + const mockTokenResponse = { access_token: 'mock-token' }; + mockAuthService.baseAuthLogin.and.returnValue(of(mockTokenResponse)); + const onLogin = firstValueFrom(service.onLogin.pipe(take(1))); + + const response = await firstValueFrom(service.login('username', 'password')); + + expect(mockAuthService.baseAuthLogin).toHaveBeenCalledWith('username', 'password'); + expect(await onLogin).toEqual(mockTokenResponse); + expect(response).toEqual({ + type: 'mock-providers', + ticket: mockTokenResponse + }); + expect(appConfigSpy).toHaveBeenCalledWith('providers'); + }); + + it('should handle login errors', async () => { + const mockError = 'Login failed'; + mockAuthService.baseAuthLogin.and.returnValue(throwError(() => mockError)); + const onError = firstValueFrom(service.onError.pipe(take(1))); + + await expectAsync(firstValueFrom(service.login('username', 'password'))).toBeRejectedWith(mockError); + expect(await onError).toEqual(mockError); + }); + }); + describe('logout', () => { - let mockAppConfigService: MockAppConfigService; + let appConfigService: AppConfigService; beforeEach(() => { - mockAppConfigService = TestBed.inject(AppConfigService) as any; + appConfigService = TestBed.inject(AppConfigService) as any; }); it('should handle logout with default parameters', () => { @@ -93,7 +133,7 @@ describe('OidcAuthenticationService', () => { }); it('should handle logout with additional parameter redirect_uri', () => { - mockAppConfigService.setConfig({ + appConfigService['setConfig']({ logoutParameters: ['client_id', 'returnTo', 'redirect_uri', 'response_type'] }); @@ -108,7 +148,7 @@ describe('OidcAuthenticationService', () => { }); it('should handle logout with an empty configuration object', () => { - mockAppConfigService.setConfig({ logoutParameters: [] }); + appConfigService['setConfig']({ logoutParameters: [] }); service.logout(); @@ -116,7 +156,7 @@ describe('OidcAuthenticationService', () => { }); it('should ignore undefined parameters', () => { - mockAppConfigService.setConfig({ + appConfigService['setConfig']({ logoutParameters: ['client_id', 'unknown_param'] }); service.logout(); @@ -127,6 +167,82 @@ describe('OidcAuthenticationService', () => { }); }); + describe('loggedIn', () => { + it('should return true if has valid tokens', () => { + mockOAuthService.hasValidAccessToken.and.returnValue(true); + mockOAuthService.hasValidIdToken.and.returnValue(true); + + expect(service.isLoggedIn()).toBeTrue(); + }); + + it('should return false if does not have valid access token', () => { + mockOAuthService.hasValidAccessToken.and.returnValue(false); + mockOAuthService.hasValidIdToken.and.returnValue(true); + + expect(service.isLoggedIn()).toBeFalse(); + }); + + it('should return false if does not have valid id token', () => { + mockOAuthService.hasValidAccessToken.and.returnValue(true); + mockOAuthService.hasValidIdToken.and.returnValue(false); + + expect(service.isLoggedIn()).toBeFalse(); + }); + }); + + describe('isEcmLoggedIn', () => { + beforeEach(() => { + mockOAuthService.hasValidAccessToken.and.returnValue(true); + mockOAuthService.hasValidIdToken.and.returnValue(true); + }); + + it('should return true if is ECM provider', () => { + spyOn(appConfig, 'get').and.returnValue('ECM'); + expect(service.isEcmLoggedIn()).toBeTrue(); + }); + + it('should return true if is all provider', () => { + spyOn(appConfig, 'get').and.returnValue('ALL'); + expect(service.isEcmLoggedIn()).toBeTrue(); + }); + + it('should return false if is not ECM provider', () => { + spyOn(appConfig, 'get').and.returnValue('BPM'); + expect(service.isEcmLoggedIn()).toBeFalse(); + }); + + it('should return false if provider is not defined', () => { + spyOn(appConfig, 'get').and.returnValue(undefined); + expect(service.isEcmLoggedIn()).toBeFalse(); + }); + }); + + describe('isBpmLoggedIn', () => { + beforeEach(() => { + mockOAuthService.hasValidAccessToken.and.returnValue(true); + mockOAuthService.hasValidIdToken.and.returnValue(true); + }); + + it('should return true if is BPM provider', () => { + spyOn(appConfig, 'get').and.returnValue('BPM'); + expect(service.isBpmLoggedIn()).toBeTrue(); + }); + + it('should return true if is all provider', () => { + spyOn(appConfig, 'get').and.returnValue('ALL'); + expect(service.isBpmLoggedIn()).toBeTrue(); + }); + + it('should return false if is not BPM provider', () => { + spyOn(appConfig, 'get').and.returnValue('ECM'); + expect(service.isBpmLoggedIn()).toBeFalse(); + }); + + it('should return false if provider is not defined', () => { + spyOn(appConfig, 'get').and.returnValue(undefined); + expect(service.isBpmLoggedIn()).toBeFalse(); + }); + }); }); describe('OidcAuthenticationService shouldPerformSsoLogin', () => { @@ -136,8 +252,8 @@ describe('OidcAuthenticationService shouldPerformSsoLogin', () => { TestBed.configureTestingModule({ providers: [ OidcAuthenticationService, - { provide: AppConfigService, useClass: MockAppConfigService }, - { provide: OAuthService, useClass: MockOAuthService }, + { provide: AppConfigService, useValue: mockAppConfigService }, + { provide: OAuthService, useValue: mockOAuthService }, { provide: OAuthStorage, useValue: {} }, { provide: AUTH_MODULE_CONFIG, useValue: {} }, { provide: AuthService, useValue: {} }, diff --git a/lib/core/src/lib/auth/services/authentication.service.spec.ts b/lib/core/src/lib/auth/services/authentication.service.spec.ts index 4da081e9fe..c0ab9ddc0a 100644 --- a/lib/core/src/lib/auth/services/authentication.service.spec.ts +++ b/lib/core/src/lib/auth/services/authentication.service.spec.ts @@ -15,35 +15,37 @@ * limitations under the License. */ -import { fakeAsync, TestBed } from '@angular/core/testing'; +import { TestBed } from '@angular/core/testing'; import { AuthenticationService } from './authentication.service'; import { CookieService } from '../../common/services/cookie.service'; import { AppConfigService } from '../../app-config/app-config.service'; import { BasicAlfrescoAuthService } from '../basic-auth/basic-alfresco-auth.service'; import { AuthModule } from '../oidc/auth.module'; -import { HttpClientModule, HttpHeaders } from '@angular/common/http'; +import { HttpHeaders, provideHttpClient } from '@angular/common/http'; import { CookieServiceMock } from '../../mock'; import { AppConfigServiceMock } from '../../common'; import { OidcAuthenticationService } from '../oidc/oidc-authentication.service'; import { OAuthEvent } from 'angular-oauth2-oidc'; -import { Subject } from 'rxjs'; +import { firstValueFrom, of, Subject, throwError } from 'rxjs'; import { RedirectAuthService } from '../oidc/redirect-auth.service'; import { Injector } from '@angular/core'; import { NoopTranslateModule } from '../../testing/noop-translate.module'; +import { ContentAuth, ProcessAuth } from '../public-api'; declare let jasmine: any; -// eslint-disable-next-line -xdescribe('AuthenticationService', () => { +describe('AuthenticationService', () => { let authService: AuthenticationService; let basicAlfrescoAuthService: BasicAlfrescoAuthService; let appConfigService: AppConfigService; let cookie: CookieService; let oidcAuthenticationService: OidcAuthenticationService; let headers: HttpHeaders; + let processAuth: ProcessAuth; + let contentAuth: ContentAuth; beforeEach(() => { TestBed.configureTestingModule({ - imports: [NoopTranslateModule, AuthModule.forRoot({ useHash: true }), HttpClientModule], + imports: [NoopTranslateModule, AuthModule.forRoot({ useHash: true })], providers: [ { provide: CookieService, @@ -52,7 +54,8 @@ xdescribe('AuthenticationService', () => { { provide: AppConfigService, useClass: AppConfigServiceMock - } + }, + provideHttpClient() ] }); @@ -61,11 +64,16 @@ xdescribe('AuthenticationService', () => { authService = TestBed.inject(AuthenticationService); basicAlfrescoAuthService = TestBed.inject(BasicAlfrescoAuthService); oidcAuthenticationService = TestBed.inject(OidcAuthenticationService); - + spyOn(oidcAuthenticationService, 'logout').and.returnValue(of()); cookie = TestBed.inject(CookieService); + + processAuth = TestBed.inject(ProcessAuth); + spyOn(processAuth, 'login').and.returnValue(Promise.resolve()); + contentAuth = TestBed.inject(ContentAuth); + spyOn(contentAuth, 'login').and.returnValue(Promise.resolve()); + cookie.clear(); - jasmine.Ajax.install(); appConfigService = TestBed.inject(AppConfigService); appConfigService.config.pagination = { supportedPageSizes: [] @@ -74,7 +82,6 @@ xdescribe('AuthenticationService', () => { afterEach(() => { cookie.clear(); - jasmine.Ajax.uninstall(); }); describe('kerberos', () => { @@ -147,56 +154,18 @@ xdescribe('AuthenticationService', () => { expect(authService.isEcmLoggedIn()).toBeFalsy(); }); - it('[ECM] should return an ECM ticket after the login done', (done) => { - const disposableLogin = basicAlfrescoAuthService.login('fake-username', 'fake-password').subscribe(() => { - expect(authService.isLoggedIn()).toBe(true); - expect(authService.getToken()).toEqual('fake-post-ticket'); - expect(authService.isEcmLoggedIn()).toBe(true); - disposableLogin.unsubscribe(); - done(); - }); + it('[ECM] should login in the ECM if no provider are defined calling the login', async () => { + contentAuth.login = jasmine.createSpy().and.returnValue(Promise.resolve(fakeECMLoginResponse.ticket)); + const loginResponse = await firstValueFrom(basicAlfrescoAuthService.login('fake-username', 'fake-password')); - jasmine.Ajax.requests.mostRecent().respondWith({ - status: 201, - contentType: 'application/json', - responseText: JSON.stringify({ entry: { id: 'fake-post-ticket', userId: 'admin' } }) - }); + expect(contentAuth.login).toHaveBeenCalled(); + expect(loginResponse).toEqual(fakeECMLoginResponse); }); - it('[ECM] should login in the ECM if no provider are defined calling the login', fakeAsync(() => { - const disposableLogin = basicAlfrescoAuthService.login('fake-username', 'fake-password').subscribe((loginResponse) => { - expect(loginResponse).toEqual(fakeECMLoginResponse); - disposableLogin.unsubscribe(); - }); - - jasmine.Ajax.requests.mostRecent().respondWith({ - status: 201, - contentType: 'application/json', - responseText: JSON.stringify({ entry: { id: 'fake-post-ticket', userId: 'admin' } }) - }); - })); - - it('[ECM] should return a ticket undefined after logout', fakeAsync(() => { - const disposableLogin = basicAlfrescoAuthService.login('fake-username', 'fake-password').subscribe(() => { - const disposableLogout = authService.logout().subscribe(() => { - expect(authService.isLoggedIn()).toBe(false); - expect(authService.getToken()).toBe(null); - expect(authService.isEcmLoggedIn()).toBe(false); - disposableLogin.unsubscribe(); - disposableLogout.unsubscribe(); - }); - - jasmine.Ajax.requests.mostRecent().respondWith({ - status: 204 - }); - }); - - jasmine.Ajax.requests.mostRecent().respondWith({ - status: 201, - contentType: 'application/json', - responseText: JSON.stringify({ entry: { id: 'fake-post-ticket', userId: 'admin' } }) - }); - })); + it('[ECM] should get token when provider is ECM', () => { + spyOn(basicAlfrescoAuthService, 'getToken').and.returnValue('fake-ecm-token'); + expect(basicAlfrescoAuthService.getToken()).toEqual('fake-ecm-token'); + }); it('[ECM] should return false if the user is not logged in', () => { expect(authService.isLoggedIn()).toBe(false); @@ -261,55 +230,12 @@ xdescribe('AuthenticationService', () => { expect(authService.isBpmLoggedIn()).toBeFalsy(); }); - it('[BPM] should return an BPM ticket after the login done', (done) => { - const disposableLogin = basicAlfrescoAuthService.login('fake-username', 'fake-password').subscribe(() => { - expect(authService.isLoggedIn()).toBe(true); - // cspell: disable-next - expect(authService.getToken()).toEqual('Basic ZmFrZS11c2VybmFtZTpmYWtlLXBhc3N3b3Jk'); - expect(authService.isBpmLoggedIn()).toBe(true); - disposableLogin.unsubscribe(); - done(); - }); + it('[BPM] should return an error when the logout return error', async () => { + oidcAuthenticationService.logout = jasmine.createSpy().and.returnValue(throwError(() => 'logout')); - jasmine.Ajax.requests.mostRecent().respondWith({ - status: 200, - contentType: 'application/json' - }); - }); - - it('[BPM] should return a ticket undefined after logout', (done) => { - const disposableLogin = basicAlfrescoAuthService.login('fake-username', 'fake-password').subscribe(() => { - const disposableLogout = authService.logout().subscribe(() => { - expect(authService.isLoggedIn()).toBe(false); - expect(authService.getToken()).toBe(null); - expect(authService.isBpmLoggedIn()).toBe(false); - disposableLogout.unsubscribe(); - disposableLogin.unsubscribe(); - done(); - }); - - jasmine.Ajax.requests.mostRecent().respondWith({ - status: 200 - }); - }); - - jasmine.Ajax.requests.mostRecent().respondWith({ - status: 200 - }); - }); - - it('[BPM] should return an error when the logout return error', (done) => { - authService.logout().subscribe( - () => {}, - (err: any) => { - expect(err).toBeDefined(); - expect(authService.getToken()).toBe(null); - done(); - } - ); - - jasmine.Ajax.requests.mostRecent().respondWith({ - status: 403 + await firstValueFrom(authService.logout()).catch((err) => { + expect(err).toBeDefined(); + expect(authService.getToken()).toBe(null); }); }); @@ -350,59 +276,23 @@ xdescribe('AuthenticationService', () => { appConfigService.load(); }); - it('[ECM] should save the remember me cookie as a session cookie after successful login', (done) => { - const disposableLogin = basicAlfrescoAuthService.login('fake-username', 'fake-password', false).subscribe(() => { - expect(cookie['ALFRESCO_REMEMBER_ME']).not.toBeUndefined(); - expect(cookie['ALFRESCO_REMEMBER_ME'].expiration).toBeNull(); - disposableLogin.unsubscribe(); - done(); - }); + it('[ECM] should save the remember me cookie as a session cookie after successful login', async () => { + await firstValueFrom(basicAlfrescoAuthService.login('fake-username', 'fake-password', false)); - jasmine.Ajax.requests.mostRecent().respondWith({ - status: 201, - contentType: 'application/json', - responseText: JSON.stringify({ entry: { id: 'fake-post-ticket', userId: 'admin' } }) - }); + expect(cookie.getItem('ALFRESCO_REMEMBER_ME')).toBe('1'); }); - it('[ECM] should save the remember me cookie as a persistent cookie after successful login', (done) => { - const disposableLogin = basicAlfrescoAuthService.login('fake-username', 'fake-password', true).subscribe(() => { - expect(cookie['ALFRESCO_REMEMBER_ME']).not.toBeUndefined(); - expect(cookie['ALFRESCO_REMEMBER_ME'].expiration).not.toBeNull(); - disposableLogin.unsubscribe(); - - done(); - }); - - jasmine.Ajax.requests.mostRecent().respondWith({ - status: 201, - contentType: 'application/json', - responseText: JSON.stringify({ entry: { id: 'fake-post-ticket', userId: 'admin' } }) - }); + it('[ECM] should save the remember me cookie as a persistent cookie after successful login', async () => { + await firstValueFrom(basicAlfrescoAuthService.login('fake-username', 'fake-password', true)); + expect(cookie.getItem('ALFRESCO_REMEMBER_ME')).not.toBeUndefined(); + expect(JSON.parse(cookie.getItem('ALFRESCO_REMEMBER_ME')).expiration).not.toBeNull(); }); - it('[ECM] should not save the remember me cookie after failed login', (done) => { - const disposableLogin = basicAlfrescoAuthService.login('fake-username', 'fake-password').subscribe( - () => {}, - () => { - expect(cookie['ALFRESCO_REMEMBER_ME']).toBeUndefined(); - disposableLogin.unsubscribe(); - done(); - } - ); + it('[ECM] should not save the remember me cookie after failed login', async () => { + contentAuth.login = jasmine.createSpy().and.returnValue(Promise.reject(new Error('Login failed'))); - jasmine.Ajax.requests.mostRecent().respondWith({ - status: 403, - contentType: 'application/json', - responseText: JSON.stringify({ - error: { - errorKey: 'Login failed', - statusCode: 403, - briefSummary: '05150009 Login failed', - stackTrace: 'For security reasons the stack trace is no longer displayed, but the property is kept for previous versions.', - descriptionURL: 'https://api-explorer.alfresco.com' - } - }) + await firstValueFrom(basicAlfrescoAuthService.login('fake-username', 'fake-password')).catch(() => { + expect(cookie.getItem('ALFRESCO_REMEMBER_ME')).toBeNull(); }); }); }); @@ -413,99 +303,6 @@ xdescribe('AuthenticationService', () => { appConfigService.load(); }); - it('[ALL] should return both ECM and BPM tickets after the login done', (done) => { - const disposableLogin = basicAlfrescoAuthService.login('fake-username', 'fake-password').subscribe(() => { - expect(authService.isLoggedIn()).toBe(true); - expect(basicAlfrescoAuthService.getTicketEcm()).toEqual('fake-post-ticket'); - // cspell: disable-next - expect(basicAlfrescoAuthService.getTicketBpm()).toEqual('Basic ZmFrZS11c2VybmFtZTpmYWtlLXBhc3N3b3Jk'); - expect(authService.isBpmLoggedIn()).toBe(true); - expect(authService.isEcmLoggedIn()).toBe(true); - disposableLogin.unsubscribe(); - done(); - }); - - jasmine.Ajax.requests.at(0).respondWith({ - status: 201, - contentType: 'application/json', - responseText: JSON.stringify({ entry: { id: 'fake-post-ticket', userId: 'admin' } }) - }); - - jasmine.Ajax.requests.at(1).respondWith({ - status: 200 - }); - }); - - it('[ALL] should return login fail if only ECM call fail', (done) => { - const disposableLogin = basicAlfrescoAuthService.login('fake-username', 'fake-password').subscribe( - () => {}, - () => { - expect(authService.isLoggedIn()).toBe(false, 'isLoggedIn'); - expect(authService.getToken()).toBe(null, 'getTicketEcm'); - // cspell: disable-next - expect(authService.getToken()).toBe(null, 'getTicketBpm'); - expect(authService.isEcmLoggedIn()).toBe(false, 'isEcmLoggedIn'); - disposableLogin.unsubscribe(); - done(); - } - ); - - jasmine.Ajax.requests.at(0).respondWith({ - status: 403 - }); - - jasmine.Ajax.requests.at(1).respondWith({ - status: 200 - }); - }); - - it('[ALL] should return login fail if only BPM call fail', (done) => { - const disposableLogin = basicAlfrescoAuthService.login('fake-username', 'fake-password').subscribe( - () => {}, - () => { - expect(authService.isLoggedIn()).toBe(false); - expect(authService.getToken()).toBe(null); - expect(authService.getToken()).toBe(null); - expect(authService.isBpmLoggedIn()).toBe(false); - disposableLogin.unsubscribe(); - done(); - } - ); - - jasmine.Ajax.requests.at(0).respondWith({ - status: 201, - contentType: 'application/json', - responseText: JSON.stringify({ entry: { id: 'fake-post-ticket', userId: 'admin' } }) - }); - - jasmine.Ajax.requests.at(1).respondWith({ - status: 403 - }); - }); - - it('[ALL] should return ticket undefined when the credentials are wrong', (done) => { - const disposableLogin = basicAlfrescoAuthService.login('fake-username', 'fake-password').subscribe( - () => {}, - () => { - expect(authService.isLoggedIn()).toBe(false); - expect(authService.getToken()).toBe(null); - expect(authService.getToken()).toBe(null); - expect(authService.isBpmLoggedIn()).toBe(false); - expect(authService.isEcmLoggedIn()).toBe(false); - disposableLogin.unsubscribe(); - done(); - } - ); - - jasmine.Ajax.requests.at(0).respondWith({ - status: 403 - }); - - jasmine.Ajax.requests.at(1).respondWith({ - status: 403 - }); - }); - it('[ALL] should return isECMProvider false', () => { expect(authService.isECMProvider()).toBe(false); }); diff --git a/lib/core/src/lib/auth/services/base-authentication.service.ts b/lib/core/src/lib/auth/services/base-authentication.service.ts index aca1bd43e6..b43e2592ed 100644 --- a/lib/core/src/lib/auth/services/base-authentication.service.ts +++ b/lib/core/src/lib/auth/services/base-authentication.service.ts @@ -123,7 +123,7 @@ export abstract class BaseAuthenticationService implements AuthenticationService */ handleError(error: any): Observable { this.onError.next(error || 'Server error'); - return throwError(error || 'Server error'); + return throwError(() => error || 'Server error'); } isOauth(): boolean {