AAE-35521 Refactor AuthenticationService unit tests (#10922)

* AAE-35521 Refactor AuthenticationService

* AAE-35521 Remove last ajax call

* AAE-35521 Add missing test
This commit is contained in:
Wojciech Duda
2025-06-09 17:07:22 +02:00
committed by GitHub
parent ac14541c2e
commit 0c147513cc
4 changed files with 351 additions and 273 deletions

View File

@@ -20,20 +20,30 @@ import { BasicAlfrescoAuthService } from './basic-alfresco-auth.service';
import { AppConfigService, AppConfigValues } from '../../app-config/app-config.service'; import { AppConfigService, AppConfigValues } from '../../app-config/app-config.service';
import { ProcessAuth } from './process-auth'; import { ProcessAuth } from './process-auth';
import { ContentAuth } from './content-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', () => { describe('BasicAlfrescoAuthService', () => {
let basicAlfrescoAuthService: BasicAlfrescoAuthService; let basicAlfrescoAuthService: BasicAlfrescoAuthService;
let processAuth: ProcessAuth;
let contentAuth: ContentAuth;
let appConfig: AppConfigService;
let appConfigSpy: jasmine.Spy;
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [HttpClientTestingModule], providers: [BasicAlfrescoAuthService, provideHttpClient()]
providers: [BasicAlfrescoAuthService]
}); });
basicAlfrescoAuthService = TestBed.inject(BasicAlfrescoAuthService); 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'); processAuth = TestBed.inject(ProcessAuth);
const appConfigSpy = spyOn(TestBed.inject(AppConfigService), 'get'); 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.CONTEXTROOTBPM).and.returnValue('activiti-app');
appConfigSpy.withArgs(AppConfigValues.CONTEXTROOTECM).and.returnValue('alfresco'); 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'); const ticket = basicAlfrescoAuthService.getTicketEcmBase64('http://www.example.com/activiti-app/alfresco/mock-api-url');
expect(ticket).toEqual('Basic Mock Process Auth ticket'); 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();
});
});
});
}); });

View File

@@ -20,7 +20,7 @@ import { OidcAuthenticationService } from './oidc-authentication.service';
import { OAuthService, OAuthStorage } from 'angular-oauth2-oidc'; import { OAuthService, OAuthStorage } from 'angular-oauth2-oidc';
import { AppConfigService, AuthService } from '@alfresco/adf-core'; import { AppConfigService, AuthService } from '@alfresco/adf-core';
import { AUTH_MODULE_CONFIG } from './auth-config'; import { AUTH_MODULE_CONFIG } from './auth-config';
import { of } from 'rxjs'; import { firstValueFrom, of, take, throwError } from 'rxjs';
interface MockAppConfigOAuth2 { interface MockAppConfigOAuth2 {
oauth2: { oauth2: {
@@ -28,59 +28,99 @@ interface MockAppConfigOAuth2 {
}; };
} }
class MockAppConfigService { const mockAppConfigService = {
config: MockAppConfigOAuth2 = { config: {
oauth2: { oauth2: {
logoutParameters: ['client_id', 'returnTo', 'response_type'] logoutParameters: ['client_id', 'returnTo', 'response_type']
} }
}; } as MockAppConfigOAuth2,
setConfig(newConfig: { logoutParameters: Array<string> }) { setConfig(newConfig: { logoutParameters: Array<string> }) {
this.config.oauth2 = newConfig; this.config.oauth2 = newConfig;
} },
get(key: string, defaultValue?: { logoutParameters: Array<string> }) { get(key: string, defaultValue?: { logoutParameters: Array<string> }) {
if (key === 'oauth2') { if (key === 'oauth2') {
return this.config.oauth2; return this.config.oauth2;
} }
if (key === 'providers') {
return 'mock-providers';
}
return defaultValue; return defaultValue;
} }
} };
class MockOAuthService { const mockOAuthService = {
clientId = 'testClientId'; clientId: 'testClientId',
redirectUri = 'testRedirectUri'; redirectUri: 'testRedirectUri',
logOut = jasmine.createSpy(); logOut: jasmine.createSpy(),
} hasValidAccessToken: jasmine.createSpy(),
hasValidIdToken: jasmine.createSpy()
};
const mockAuthService = {
baseAuthLogin: jasmine.createSpy()
};
describe('OidcAuthenticationService', () => { describe('OidcAuthenticationService', () => {
let service: OidcAuthenticationService; let service: OidcAuthenticationService;
let oauthService: OAuthService; let oauthService: OAuthService;
let appConfig: AppConfigService;
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
providers: [ providers: [
OidcAuthenticationService, OidcAuthenticationService,
{ provide: AppConfigService, useClass: MockAppConfigService }, { provide: AppConfigService, useValue: mockAppConfigService },
{ provide: OAuthService, useClass: MockOAuthService }, { provide: OAuthService, useValue: mockOAuthService },
{ provide: OAuthStorage, useValue: {} }, { provide: OAuthStorage, useValue: {} },
{ provide: AUTH_MODULE_CONFIG, useValue: {} }, { provide: AUTH_MODULE_CONFIG, useValue: {} },
{ provide: AuthService, useValue: {} } { provide: AuthService, useValue: mockAuthService }
] ]
}); });
service = TestBed.inject(OidcAuthenticationService); service = TestBed.inject(OidcAuthenticationService);
oauthService = TestBed.inject(OAuthService); oauthService = TestBed.inject(OAuthService);
appConfig = TestBed.inject(AppConfigService);
}); });
it('should be created', () => { it('should be created', () => {
expect(service).toBeTruthy(); 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', () => { describe('logout', () => {
let mockAppConfigService: MockAppConfigService; let appConfigService: AppConfigService;
beforeEach(() => { beforeEach(() => {
mockAppConfigService = TestBed.inject(AppConfigService) as any; appConfigService = TestBed.inject(AppConfigService) as any;
}); });
it('should handle logout with default parameters', () => { it('should handle logout with default parameters', () => {
@@ -93,7 +133,7 @@ describe('OidcAuthenticationService', () => {
}); });
it('should handle logout with additional parameter redirect_uri', () => { it('should handle logout with additional parameter redirect_uri', () => {
mockAppConfigService.setConfig({ appConfigService['setConfig']({
logoutParameters: ['client_id', 'returnTo', 'redirect_uri', 'response_type'] logoutParameters: ['client_id', 'returnTo', 'redirect_uri', 'response_type']
}); });
@@ -108,7 +148,7 @@ describe('OidcAuthenticationService', () => {
}); });
it('should handle logout with an empty configuration object', () => { it('should handle logout with an empty configuration object', () => {
mockAppConfigService.setConfig({ logoutParameters: [] }); appConfigService['setConfig']({ logoutParameters: [] });
service.logout(); service.logout();
@@ -116,7 +156,7 @@ describe('OidcAuthenticationService', () => {
}); });
it('should ignore undefined parameters', () => { it('should ignore undefined parameters', () => {
mockAppConfigService.setConfig({ appConfigService['setConfig']({
logoutParameters: ['client_id', 'unknown_param'] logoutParameters: ['client_id', 'unknown_param']
}); });
service.logout(); 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', () => { describe('OidcAuthenticationService shouldPerformSsoLogin', () => {
@@ -136,8 +252,8 @@ describe('OidcAuthenticationService shouldPerformSsoLogin', () => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
providers: [ providers: [
OidcAuthenticationService, OidcAuthenticationService,
{ provide: AppConfigService, useClass: MockAppConfigService }, { provide: AppConfigService, useValue: mockAppConfigService },
{ provide: OAuthService, useClass: MockOAuthService }, { provide: OAuthService, useValue: mockOAuthService },
{ provide: OAuthStorage, useValue: {} }, { provide: OAuthStorage, useValue: {} },
{ provide: AUTH_MODULE_CONFIG, useValue: {} }, { provide: AUTH_MODULE_CONFIG, useValue: {} },
{ provide: AuthService, useValue: {} }, { provide: AuthService, useValue: {} },

View File

@@ -15,35 +15,37 @@
* limitations under the License. * limitations under the License.
*/ */
import { fakeAsync, TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import { AuthenticationService } from './authentication.service'; import { AuthenticationService } from './authentication.service';
import { CookieService } from '../../common/services/cookie.service'; import { CookieService } from '../../common/services/cookie.service';
import { AppConfigService } from '../../app-config/app-config.service'; import { AppConfigService } from '../../app-config/app-config.service';
import { BasicAlfrescoAuthService } from '../basic-auth/basic-alfresco-auth.service'; import { BasicAlfrescoAuthService } from '../basic-auth/basic-alfresco-auth.service';
import { AuthModule } from '../oidc/auth.module'; 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 { CookieServiceMock } from '../../mock';
import { AppConfigServiceMock } from '../../common'; import { AppConfigServiceMock } from '../../common';
import { OidcAuthenticationService } from '../oidc/oidc-authentication.service'; import { OidcAuthenticationService } from '../oidc/oidc-authentication.service';
import { OAuthEvent } from 'angular-oauth2-oidc'; 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 { RedirectAuthService } from '../oidc/redirect-auth.service';
import { Injector } from '@angular/core'; import { Injector } from '@angular/core';
import { NoopTranslateModule } from '../../testing/noop-translate.module'; import { NoopTranslateModule } from '../../testing/noop-translate.module';
import { ContentAuth, ProcessAuth } from '../public-api';
declare let jasmine: any; declare let jasmine: any;
// eslint-disable-next-line describe('AuthenticationService', () => {
xdescribe('AuthenticationService', () => {
let authService: AuthenticationService; let authService: AuthenticationService;
let basicAlfrescoAuthService: BasicAlfrescoAuthService; let basicAlfrescoAuthService: BasicAlfrescoAuthService;
let appConfigService: AppConfigService; let appConfigService: AppConfigService;
let cookie: CookieService; let cookie: CookieService;
let oidcAuthenticationService: OidcAuthenticationService; let oidcAuthenticationService: OidcAuthenticationService;
let headers: HttpHeaders; let headers: HttpHeaders;
let processAuth: ProcessAuth;
let contentAuth: ContentAuth;
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [NoopTranslateModule, AuthModule.forRoot({ useHash: true }), HttpClientModule], imports: [NoopTranslateModule, AuthModule.forRoot({ useHash: true })],
providers: [ providers: [
{ {
provide: CookieService, provide: CookieService,
@@ -52,7 +54,8 @@ xdescribe('AuthenticationService', () => {
{ {
provide: AppConfigService, provide: AppConfigService,
useClass: AppConfigServiceMock useClass: AppConfigServiceMock
} },
provideHttpClient()
] ]
}); });
@@ -61,11 +64,16 @@ xdescribe('AuthenticationService', () => {
authService = TestBed.inject(AuthenticationService); authService = TestBed.inject(AuthenticationService);
basicAlfrescoAuthService = TestBed.inject(BasicAlfrescoAuthService); basicAlfrescoAuthService = TestBed.inject(BasicAlfrescoAuthService);
oidcAuthenticationService = TestBed.inject(OidcAuthenticationService); oidcAuthenticationService = TestBed.inject(OidcAuthenticationService);
spyOn(oidcAuthenticationService, 'logout').and.returnValue(of());
cookie = TestBed.inject(CookieService); 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(); cookie.clear();
jasmine.Ajax.install();
appConfigService = TestBed.inject(AppConfigService); appConfigService = TestBed.inject(AppConfigService);
appConfigService.config.pagination = { appConfigService.config.pagination = {
supportedPageSizes: [] supportedPageSizes: []
@@ -74,7 +82,6 @@ xdescribe('AuthenticationService', () => {
afterEach(() => { afterEach(() => {
cookie.clear(); cookie.clear();
jasmine.Ajax.uninstall();
}); });
describe('kerberos', () => { describe('kerberos', () => {
@@ -147,56 +154,18 @@ xdescribe('AuthenticationService', () => {
expect(authService.isEcmLoggedIn()).toBeFalsy(); expect(authService.isEcmLoggedIn()).toBeFalsy();
}); });
it('[ECM] should return an ECM ticket after the login done', (done) => { it('[ECM] should login in the ECM if no provider are defined calling the login', async () => {
const disposableLogin = basicAlfrescoAuthService.login('fake-username', 'fake-password').subscribe(() => { contentAuth.login = jasmine.createSpy().and.returnValue(Promise.resolve(fakeECMLoginResponse.ticket));
expect(authService.isLoggedIn()).toBe(true); const loginResponse = await firstValueFrom(basicAlfrescoAuthService.login('fake-username', 'fake-password'));
expect(authService.getToken()).toEqual('fake-post-ticket');
expect(authService.isEcmLoggedIn()).toBe(true);
disposableLogin.unsubscribe();
done();
});
jasmine.Ajax.requests.mostRecent().respondWith({ expect(contentAuth.login).toHaveBeenCalled();
status: 201,
contentType: 'application/json',
responseText: JSON.stringify({ entry: { id: 'fake-post-ticket', userId: 'admin' } })
});
});
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); expect(loginResponse).toEqual(fakeECMLoginResponse);
disposableLogin.unsubscribe();
}); });
jasmine.Ajax.requests.mostRecent().respondWith({ it('[ECM] should get token when provider is ECM', () => {
status: 201, spyOn(basicAlfrescoAuthService, 'getToken').and.returnValue('fake-ecm-token');
contentType: 'application/json', expect(basicAlfrescoAuthService.getToken()).toEqual('fake-ecm-token');
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 return false if the user is not logged in', () => { it('[ECM] should return false if the user is not logged in', () => {
expect(authService.isLoggedIn()).toBe(false); expect(authService.isLoggedIn()).toBe(false);
@@ -261,55 +230,12 @@ xdescribe('AuthenticationService', () => {
expect(authService.isBpmLoggedIn()).toBeFalsy(); expect(authService.isBpmLoggedIn()).toBeFalsy();
}); });
it('[BPM] should return an BPM ticket after the login done', (done) => { it('[BPM] should return an error when the logout return error', async () => {
const disposableLogin = basicAlfrescoAuthService.login('fake-username', 'fake-password').subscribe(() => { oidcAuthenticationService.logout = jasmine.createSpy().and.returnValue(throwError(() => 'logout'));
expect(authService.isLoggedIn()).toBe(true);
// cspell: disable-next
expect(authService.getToken()).toEqual('Basic ZmFrZS11c2VybmFtZTpmYWtlLXBhc3N3b3Jk');
expect(authService.isBpmLoggedIn()).toBe(true);
disposableLogin.unsubscribe();
done();
});
jasmine.Ajax.requests.mostRecent().respondWith({ await firstValueFrom(authService.logout()).catch((err) => {
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(err).toBeDefined();
expect(authService.getToken()).toBe(null); expect(authService.getToken()).toBe(null);
done();
}
);
jasmine.Ajax.requests.mostRecent().respondWith({
status: 403
}); });
}); });
@@ -350,59 +276,23 @@ xdescribe('AuthenticationService', () => {
appConfigService.load(); appConfigService.load();
}); });
it('[ECM] should save the remember me cookie as a session cookie after successful login', (done) => { it('[ECM] should save the remember me cookie as a session cookie after successful login', async () => {
const disposableLogin = basicAlfrescoAuthService.login('fake-username', 'fake-password', false).subscribe(() => { await firstValueFrom(basicAlfrescoAuthService.login('fake-username', 'fake-password', false));
expect(cookie['ALFRESCO_REMEMBER_ME']).not.toBeUndefined();
expect(cookie['ALFRESCO_REMEMBER_ME'].expiration).toBeNull(); expect(cookie.getItem('ALFRESCO_REMEMBER_ME')).toBe('1');
disposableLogin.unsubscribe();
done();
}); });
jasmine.Ajax.requests.mostRecent().respondWith({ it('[ECM] should save the remember me cookie as a persistent cookie after successful login', async () => {
status: 201, await firstValueFrom(basicAlfrescoAuthService.login('fake-username', 'fake-password', true));
contentType: 'application/json', expect(cookie.getItem('ALFRESCO_REMEMBER_ME')).not.toBeUndefined();
responseText: JSON.stringify({ entry: { id: 'fake-post-ticket', userId: 'admin' } }) expect(JSON.parse(cookie.getItem('ALFRESCO_REMEMBER_ME')).expiration).not.toBeNull();
});
}); });
it('[ECM] should save the remember me cookie as a persistent cookie after successful login', (done) => { it('[ECM] should not save the remember me cookie after failed login', async () => {
const disposableLogin = basicAlfrescoAuthService.login('fake-username', 'fake-password', true).subscribe(() => { contentAuth.login = jasmine.createSpy().and.returnValue(Promise.reject(new Error('Login failed')));
expect(cookie['ALFRESCO_REMEMBER_ME']).not.toBeUndefined();
expect(cookie['ALFRESCO_REMEMBER_ME'].expiration).not.toBeNull();
disposableLogin.unsubscribe();
done(); await firstValueFrom(basicAlfrescoAuthService.login('fake-username', 'fake-password')).catch(() => {
}); expect(cookie.getItem('ALFRESCO_REMEMBER_ME')).toBeNull();
jasmine.Ajax.requests.mostRecent().respondWith({
status: 201,
contentType: 'application/json',
responseText: JSON.stringify({ entry: { id: 'fake-post-ticket', userId: 'admin' } })
});
});
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();
}
);
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'
}
})
}); });
}); });
}); });
@@ -413,99 +303,6 @@ xdescribe('AuthenticationService', () => {
appConfigService.load(); 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', () => { it('[ALL] should return isECMProvider false', () => {
expect(authService.isECMProvider()).toBe(false); expect(authService.isECMProvider()).toBe(false);
}); });

View File

@@ -123,7 +123,7 @@ export abstract class BaseAuthenticationService implements AuthenticationService
*/ */
handleError(error: any): Observable<any> { handleError(error: any): Observable<any> {
this.onError.next(error || 'Server error'); this.onError.next(error || 'Server error');
return throwError(error || 'Server error'); return throwError(() => error || 'Server error');
} }
isOauth(): boolean { isOauth(): boolean {