[AAE-12501] Align JS API (#8344)

* [AAE-12501] Provide an AlfrescoApiService implementation that disable the AlfrescoApi oauth initialization when we use new oidc implementation

* [AAE-12501] Replace oauth2Auth with authentication service, define get username as abstract

* [AAE-12501] Replace sitesService with authentication service since sitesService get the username from oauth2Auth

* [AAE-12501] Call implicitLogin by authentication service

* [AAE-12501] Replace Oauth2Auth with AlfrescoApi and call the custom api without using authentication

* [AAE-12501] Replace oauth2Auth with authentication service to get the token

* [AAE-12501] Replace oauth2Auth with alfrescoApi

* remove unneeded JS-API dep
move auth in the right place

* [AAE-10501] Rename alfresco-api.http-client to adf-http-client

* [AAE-10501] Remove config from a CoreModule, a different service is provided in AuthModule to use angular http client instead of super agent

* [AAE-10501] Disable AlfrescoApi oauth initialization while using new adf oidc authentication

* [AAE-12501] Replace alfresco api client with AdfHttpClient

* [AAE-12501] Restore get username methods

* [AAE-12501] Get username with authentication service

* [AAE-12501] removee unused method

* [AAE-12501] Trigger on login when token is received

* [AAE-12501] Fix content-services unit test

* [AAE-12501] Fix import

* [AAE-12501] Fix core unit tests

* [AAE-12501] Fix process-services-cloud unit tests

* [AAE-12501] Create a request options interface with the needed props, remove the import from js-api, return the body from request

* [AAE-12501] Fix process-services-cloud unit tests without Expectation

* [AAE-12501] Fix Core secondary entrypoints unit tests are not executed: move test.ts one level up in order to find all the spec files into the secondary entrypoints folders and update path

* [AAE-12501] Fix Core unit tests that weren't executed because of the previous test.ts wrong location

* [AAE-12501] Fix authentication token_issued subscription

* add emitters

* [AAE-12501] Replace Math.random() to fix hospot security issue, fix lint issues

* [AAE-12501] Install event-emitter dependency

* [AAE-12501] Comment temporary setCsrfToken because is not possible to import app config service from core due to circular dependencies

* [AAE-12501] Get disableCsrf from app config serviice when app configuration is loaded

* [AAE-12501] Fix license-header lint issue

* [AAE-14221] Regenerate lock file

* [AAE-14221] Fix sonarcloud issues

* [AAE-12501] Remove wrong character

* [AAE-12501] Regenerate lock file

* [AAE-12501] Fix BC: update alfresco api response error

---------

Co-authored-by: eromano <eugenioromano16@gmail.com>
This commit is contained in:
Amedeo Lepore
2023-06-27 17:22:30 +02:00
committed by GitHub
parent 037dce0ae7
commit 7abebf0652
53 changed files with 5474 additions and 10457 deletions

View File

@@ -303,7 +303,7 @@
"core": { "core": {
"projectType": "library", "projectType": "library",
"root": "lib/core", "root": "lib/core",
"sourceRoot": "lib/core/src", "sourceRoot": "lib/core",
"prefix": "adf", "prefix": "adf",
"architect": { "architect": {
"build": { "build": {
@@ -327,7 +327,7 @@
"test": { "test": {
"builder": "@angular-devkit/build-angular:karma", "builder": "@angular-devkit/build-angular:karma",
"options": { "options": {
"main": "lib/core/src/test.ts", "main": "lib/core/test.ts",
"tsConfig": "lib/core/tsconfig.spec.json", "tsConfig": "lib/core/tsconfig.spec.json",
"karmaConfig": "lib/core/karma.conf.js", "karmaConfig": "lib/core/karma.conf.js",
"sourceMap": true, "sourceMap": true,

View File

@@ -27,7 +27,6 @@ import { ObjectDataTableAdapter, AuthenticationService } from '@alfresco/adf-cor
<li>Global i18n: {{ 'APP_LAYOUT.DATATABLE_LAZY' | translate }}</li> <li>Global i18n: {{ 'APP_LAYOUT.DATATABLE_LAZY' | translate }}</li>
<li>Local i18n (work in progress): {{ 'LAZY.TEXT' | translate }}</li> <li>Local i18n (work in progress): {{ 'LAZY.TEXT' | translate }}</li>
<li>isLoggedIn: {{ isLoggedIn }}</li> <li>isLoggedIn: {{ isLoggedIn }}</li>
<li>ECM username: {{ username }}
</ul> </ul>
` `
}) })
@@ -39,10 +38,6 @@ export class LazyLoadingComponent {
return this.auth.isLoggedIn(); return this.auth.isLoggedIn();
} }
get username(): string {
return this.auth.getEcmUsername();
}
constructor(private auth: AuthenticationService) { constructor(private auth: AuthenticationService) {
this.data = new ObjectDataTableAdapter( this.data = new ObjectDataTableAdapter(
// data // data

View File

@@ -56,8 +56,7 @@ export class AppNotificationsService {
) { ) {
this.alfrescoApiService.alfrescoApiInitialized.subscribe(() => { this.alfrescoApiService.alfrescoApiInitialized.subscribe(() => {
if (this.isProcessServicesEnabled() && this.notificationsEnabled) { if (this.isProcessServicesEnabled() && this.notificationsEnabled) {
this.alfrescoApiService.getInstance().oauth2Auth.once('token_issued', () => { this.authenticationService.once('token_received').subscribe(() => {
const deployedApps = this.appConfigService.get('alfresco-deployed-apps', []); const deployedApps = this.appConfigService.get('alfresco-deployed-apps', []);
if (deployedApps?.length) { if (deployedApps?.length) {
deployedApps.forEach((app) => { deployedApps.forEach((app) => {
@@ -69,11 +68,8 @@ export class AppNotificationsService {
}); });
}); });
} }
}); });
} }
}); });
} }

View File

@@ -20,7 +20,7 @@ import { from, Observable, throwError, Subject } from 'rxjs';
import { catchError, map, switchMap, filter, take } from 'rxjs/operators'; import { catchError, map, switchMap, filter, take } from 'rxjs/operators';
import { RepositoryInfo, SystemPropertiesRepresentation } from '@alfresco/js-api'; import { RepositoryInfo, SystemPropertiesRepresentation } from '@alfresco/js-api';
import { BpmProductVersionModel, AlfrescoApiService, AuthenticationService } from '@alfresco/adf-core'; import { BpmProductVersionModel, AuthenticationService } from '@alfresco/adf-core';
import { ApiClientsService } from '@alfresco/adf-core/api'; import { ApiClientsService } from '@alfresco/adf-core/api';
@Injectable({ @Injectable({
@@ -34,13 +34,12 @@ export class DiscoveryApiService {
ecmProductInfo$ = new Subject<RepositoryInfo>(); ecmProductInfo$ = new Subject<RepositoryInfo>();
constructor( constructor(
private apiService: AlfrescoApiService,
private authenticationService: AuthenticationService, private authenticationService: AuthenticationService,
private apiClientsService: ApiClientsService private apiClientsService: ApiClientsService
) { ) {
this.authenticationService.onLogin this.authenticationService.onLogin
.pipe( .pipe(
filter(() => this.apiService.getInstance()?.isEcmLoggedIn()), filter(() => this.authenticationService.isEcmLoggedIn()),
take(1), take(1),
switchMap(() => this.getEcmProductInfo()) switchMap(() => this.getEcmProductInfo())
) )

View File

@@ -45,7 +45,8 @@ export class SitesService {
return this._sitesApi; return this._sitesApi;
} }
constructor(private apiService: AlfrescoApiService, private logService: LogService) { constructor(private apiService: AlfrescoApiService,
private logService: LogService) {
} }
/** /**
@@ -140,15 +141,6 @@ export class SitesService {
return from(this.sitesApi.listSiteMemberships(siteId, opts)); return from(this.sitesApi.listSiteMemberships(siteId, opts));
} }
/**
* Gets the username of the user currently logged into ACS.
*
* @returns Username string
*/
getEcmCurrentLoggedUserName(): string {
return this.apiService.getInstance().getEcmUsername();
}
/** /**
* Looks for a site inside the path of a Node and returns its guid if it finds one. * Looks for a site inside the path of a Node and returns its guid if it finds one.
* (return an empty string if no site is found) * (return an empty string if no site is found)

View File

@@ -17,7 +17,7 @@
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { Node } from '@alfresco/js-api'; import { Node } from '@alfresco/js-api';
import { AlfrescoApiService } from '@alfresco/adf-core'; import { AuthenticationService } from '@alfresco/adf-core';
import moment, { Moment } from 'moment'; import moment, { Moment } from 'moment';
@Injectable({ @Injectable({
@@ -25,7 +25,7 @@ import moment, { Moment } from 'moment';
}) })
export class LockService { export class LockService {
constructor(private alfrescoApiService: AlfrescoApiService) { constructor(private authService: AuthenticationService) {
} }
isLocked(node: Node): boolean { isLocked(node: Node): boolean {
@@ -34,7 +34,7 @@ export class LockService {
if (this.isReadOnlyLock(node)) { if (this.isReadOnlyLock(node)) {
isLocked = !this.isLockExpired(node); isLocked = !this.isLockExpired(node);
} else if (this.isLockOwnerAllowed(node)) { } else if (this.isLockOwnerAllowed(node)) {
isLocked = this.alfrescoApiService.getInstance().getEcmUsername() !== node.properties['cm:lockOwner'].id; isLocked = this.authService.getEcmUsername() !== node.properties['cm:lockOwner'].id;
if (this.isLockExpired(node)) { if (this.isLockExpired(node)) {
isLocked = false; isLocked = false;
} }

View File

@@ -19,7 +19,7 @@ import { DebugElement } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
import { DropdownSitesComponent, Relations } from './sites-dropdown.component'; import { DropdownSitesComponent, Relations } from './sites-dropdown.component';
import { setupTestBed } from '@alfresco/adf-core'; import { AuthenticationService, setupTestBed } from '@alfresco/adf-core';
import { of } from 'rxjs'; import { of } from 'rxjs';
import { getFakeSitePaging, import { getFakeSitePaging,
getFakeSitePagingNoMoreItems, getFakeSitePagingNoMoreItems,
@@ -57,6 +57,7 @@ describe('DropdownSitesComponent', () => {
let debug: DebugElement; let debug: DebugElement;
let element: HTMLElement; let element: HTMLElement;
let siteService: SitesService; let siteService: SitesService;
let authService: AuthenticationService;
setupTestBed({ setupTestBed({
imports: [ imports: [
@@ -293,10 +294,11 @@ describe('DropdownSitesComponent', () => {
beforeEach(() => { beforeEach(() => {
component.relations = Relations.Members; component.relations = Relations.Members;
authService = TestBed.inject(AuthenticationService);
}); });
it('should show only sites which logged user is member of when member relation is set', (done) => { it('should show only sites which logged user is member of when member relation is set', (done) => {
spyOn(siteService, 'getEcmCurrentLoggedUserName').and.returnValue('test'); spyOn(authService, 'getEcmUsername').and.returnValue('test');
fixture.detectChanges(); fixture.detectChanges();
fixture.whenStable().then(() => { fixture.whenStable().then(() => {
@@ -317,10 +319,11 @@ describe('DropdownSitesComponent', () => {
describe('No relations', () => { describe('No relations', () => {
beforeEach(() => { beforeEach(() => {
component.relations = []; component.relations = [];
authService = TestBed.inject(AuthenticationService);
}); });
it('should show all the sites if no relation is set', (done) => { it('should show all the sites if no relation is set', (done) => {
spyOn(siteService, 'getEcmCurrentLoggedUserName').and.returnValue('test'); spyOn(authService, 'getEcmUsername').and.returnValue('test');
fixture.detectChanges(); fixture.detectChanges();
fixture.whenStable().then(() => { fixture.whenStable().then(() => {

View File

@@ -16,7 +16,7 @@
*/ */
import { Component, EventEmitter, Input, OnInit, Output, ViewEncapsulation } from '@angular/core'; import { Component, EventEmitter, Input, OnInit, Output, ViewEncapsulation } from '@angular/core';
import { LogService, InfiniteSelectScrollDirective } from '@alfresco/adf-core'; import { LogService, InfiniteSelectScrollDirective, AuthenticationService } from '@alfresco/adf-core';
import { SitePaging, SiteEntry } from '@alfresco/js-api'; import { SitePaging, SiteEntry } from '@alfresco/js-api';
import { MatSelectChange } from '@angular/material/select'; import { MatSelectChange } from '@angular/material/select';
import {LiveAnnouncer} from '@angular/cdk/a11y'; import {LiveAnnouncer} from '@angular/cdk/a11y';
@@ -81,7 +81,8 @@ export class DropdownSitesComponent implements OnInit {
selected: SiteEntry = null; selected: SiteEntry = null;
MY_FILES_VALUE = '-my-'; MY_FILES_VALUE = '-my-';
constructor(private sitesService: SitesService, constructor(private authService: AuthenticationService,
private sitesService: SitesService,
private logService: LogService, private logService: LogService,
private liveAnnouncer: LiveAnnouncer, private liveAnnouncer: LiveAnnouncer,
private translateService: TranslateService) { private translateService: TranslateService) {
@@ -174,7 +175,7 @@ export class DropdownSitesComponent implements OnInit {
} }
private filteredResultsByMember(sites: SitePaging): SitePaging { private filteredResultsByMember(sites: SitePaging): SitePaging {
const loggedUserName = this.sitesService.getEcmCurrentLoggedUserName(); const loggedUserName = this.authService.getEcmUsername();
sites.list.entries = sites.list.entries.filter((site) => this.isCurrentUserMember(site, loggedUserName)); sites.list.entries = sites.list.entries.filter((site) => this.isCurrentUserMember(site, loggedUserName));
return sites; return sites;
} }

View File

@@ -19,4 +19,5 @@ export * from './lib/api-client.factory';
export * from './lib/api-clients.service'; export * from './lib/api-clients.service';
export * from './lib/clients'; export * from './lib/clients';
export * from './lib/types'; export * from './lib/types';
export * from './lib/alfresco-api/alfresco-api.http-client'; export * from './lib/adf-http-client.service';
export * from './lib/interfaces';

View File

@@ -19,8 +19,8 @@ import { Emitters, RequestOptions, ResultListDataRepresentationTaskRepresentatio
import { HttpParams } from '@angular/common/http'; import { HttpParams } from '@angular/common/http';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import { AlfrescoApiHttpClient } from './alfresco-api.http-client'; import { AdfHttpClient } from './adf-http-client.service';
import { AlfrescoApiResponseError } from './alfresco-api.response-error'; import { AlfrescoApiResponseError } from './alfresco-api/alfresco-api.response-error';
const securityOptions: SecurityOptions = { const securityOptions: SecurityOptions = {
authentications: {}, authentications: {},
@@ -52,8 +52,8 @@ const mockResponse = {
] ]
}; };
describe('AlfrescoApiHttpClient', () => { describe('AdfHttpClient', () => {
let angularHttpClient: AlfrescoApiHttpClient; let angularHttpClient: AdfHttpClient;
let controller: HttpTestingController; let controller: HttpTestingController;
beforeEach(() => { beforeEach(() => {
@@ -62,7 +62,7 @@ describe('AlfrescoApiHttpClient', () => {
HttpClientTestingModule HttpClientTestingModule
] ]
}); });
angularHttpClient = TestBed.inject(AlfrescoApiHttpClient); angularHttpClient = TestBed.inject(AdfHttpClient);
controller = TestBed.inject(HttpTestingController); controller = TestBed.inject(HttpTestingController);
}); });
@@ -90,7 +90,7 @@ describe('AlfrescoApiHttpClient', () => {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
expect(res.data![0].created instanceof Date).toBeTruthy(); expect(res.data![0].created instanceof Date).toBeTruthy();
done(); done();
}); }).catch(error=> fail(error));
const req = controller.expectOne('http://example.com'); const req = controller.expectOne('http://example.com');
expect(req.request.method).toEqual('POST'); expect(req.request.method).toEqual('POST');
@@ -110,7 +110,7 @@ describe('AlfrescoApiHttpClient', () => {
angularHttpClient.request('http://example.com', options, securityOptions, emitters).then((res) => { angularHttpClient.request('http://example.com', options, securityOptions, emitters).then((res) => {
expect(res).toEqual(mockResponse); expect(res).toEqual(mockResponse);
done(); done();
}); }).catch(error=> fail(error));
const req = controller.expectOne('http://example.com'); const req = controller.expectOne('http://example.com');
expect(req.request.method).toEqual('POST'); expect(req.request.method).toEqual('POST');
@@ -177,7 +177,9 @@ describe('AlfrescoApiHttpClient', () => {
returnType: null returnType: null
}; };
angularHttpClient.request('http://example.com', requestOptions, securityOptions, emitters); angularHttpClient.request('http://example.com', requestOptions, securityOptions, emitters).catch(error =>
fail(error)
);
const req = controller.expectOne('http://example.com?autoRename=true&include=allowableOperations'); const req = controller.expectOne('http://example.com?autoRename=true&include=allowableOperations');
expect(req.request.method).toEqual('POST'); expect(req.request.method).toEqual('POST');
@@ -232,9 +234,9 @@ describe('AlfrescoApiHttpClient', () => {
const errorResponse = new Blob(); const errorResponse = new Blob();
angularHttpClient.request('http://example.com', options, securityOptions, emitters).catch((res: AlfrescoApiResponseError) => { angularHttpClient.request('http://example.com', options, securityOptions, emitters).catch((err: AlfrescoApiResponseError) => {
expect(res.status).toBe(400); expect(err.status).toBe(400);
expect(res.error.response.body instanceof Blob).toBeTruthy(); expect(err.response.body instanceof Blob).toBeTruthy();
done(); done();
}); });
@@ -257,7 +259,9 @@ describe('AlfrescoApiHttpClient', () => {
} }
}; };
angularHttpClient.request('http://example.com/candidatebaseapp/query/v1/process-instances', options, securityOptions, emitters); angularHttpClient.request('http://example.com/candidatebaseapp/query/v1/process-instances', options, securityOptions, emitters).catch(error =>
fail(error)
);
const req = controller.expectOne('http://example.com/candidatebaseapp/query/v1/process-instances?skipCount=0&status=RUNNING&status=SUSPENDED&sort=startDate%2CDESC'); const req = controller.expectOne('http://example.com/candidatebaseapp/query/v1/process-instances?skipCount=0&status=RUNNING&status=SUSPENDED&sort=startDate%2CDESC');
expect(req.request.method).toEqual('POST'); expect(req.request.method).toEqual('POST');
@@ -274,7 +278,7 @@ describe('AlfrescoApiHttpClient', () => {
angularHttpClient.request('http://example.com', options, securityOptions, emitters).then((res) => { angularHttpClient.request('http://example.com', options, securityOptions, emitters).then((res) => {
expect(res).toEqual(''); expect(res).toEqual('');
done(); done();
}); }).catch(error=> fail(error));
const req = controller.expectOne('http://example.com'); const req = controller.expectOne('http://example.com');
@@ -290,7 +294,9 @@ describe('AlfrescoApiHttpClient', () => {
} }
}; };
angularHttpClient.request('http://example.com', options, securityOptions, emitters); angularHttpClient.request('http://example.com', options, securityOptions, emitters).catch(error =>
fail(error)
);
const req = controller.expectOne('http://example.com?lastModifiedFrom=2022-08-17T00%3A00%3A00.000%2B02%3A00'); const req = controller.expectOne('http://example.com?lastModifiedFrom=2022-08-17T00%3A00%3A00.000%2B02%3A00');
@@ -306,7 +312,9 @@ describe('AlfrescoApiHttpClient', () => {
} }
}; };
angularHttpClient.request('http://example.com', options, securityOptions, emitters); angularHttpClient.request('http://example.com', options, securityOptions, emitters).catch(error =>
fail(error)
);
const req = controller.expectOne('http://example.com?lastModifiedFrom=2022-08-17T00%3A00%3A00.000Z'); const req = controller.expectOne('http://example.com?lastModifiedFrom=2022-08-17T00%3A00%3A00.000Z');

View File

@@ -0,0 +1,353 @@
/*!
* @license
* Copyright © 2005-2023 Hyland Software, Inc. and its affiliates. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { SHOULD_ADD_AUTH_TOKEN } from '@alfresco/adf-core/auth';
import { Emitters as JsApiEmitters, HttpClient as JsApiHttpClient } from '@alfresco/js-api';
import {
HttpClient,
HttpContext,
HttpErrorResponse,
HttpEvent,
HttpHeaders,
HttpParams,
HttpResponse
} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, of, Subject, throwError } from 'rxjs';
import { catchError, map, takeUntil } from 'rxjs/operators';
import {
convertObjectToFormData,
getQueryParamsWithCustomEncoder,
isBlobResponse,
isConstructor,
isHttpResponseEvent,
isHttpUploadProgressEvent,
removeNilValues
} from './alfresco-api/alfresco-api.utils';
import { AlfrescoApiParamEncoder } from './alfresco-api/alfresco-api.param-encoder';
import { AlfrescoApiResponseError } from './alfresco-api/alfresco-api.response-error';
import { Constructor } from './types';
import { RequestOptions, SecurityOptions } from './interfaces';
import ee, { Emitter } from 'event-emitter';
export interface Emitters {
readonly eventEmitter: Emitter;
readonly apiClientEmitter: Emitter;
}
@Injectable({
providedIn: 'root'
})
export class AdfHttpClient implements ee.Emitter,JsApiHttpClient {
on: ee.EmitterMethod;
off: ee.EmitterMethod;
once: ee.EmitterMethod;
emit: (type: string, ...args: any[]) => void;
private _disableCsrf = false;
private defaultSecurityOptions = {
withCredentials: true,
isBpmRequest: false,
authentications: {},
defaultHeaders: {}
};
get disableCsrf(): boolean {
return this._disableCsrf;
}
set disableCsrf(disableCsrf: boolean) {
this._disableCsrf = disableCsrf;
}
constructor(private httpClient: HttpClient
) {
ee(this);
}
setDefaultSecurityOption(options: any) {
this.defaultSecurityOptions = this.merge(this.defaultSecurityOptions, options);
}
merge(...objects): any {
const result = {};
objects.forEach((source) => {
Object.keys(source).forEach((prop) => {
if (prop in result && Array.isArray(result[prop])) {
result[prop] = result[prop].concat(source[prop]);
} else if (prop in result && typeof result[prop] === 'object') {
result[prop] = this.merge(result[prop], source[prop]);
} else {
result[prop] = source[prop];
}
});
});
return result;
}
request<T = any>(url: string, options?: RequestOptions, sc: SecurityOptions = this.defaultSecurityOptions, emitters?: JsApiEmitters): Promise<T> {
const body = AdfHttpClient.getBody(options);
const params = getQueryParamsWithCustomEncoder(options.queryParams, new AlfrescoApiParamEncoder());
const responseType = AdfHttpClient.getResponseType(options);
const context = new HttpContext().set(SHOULD_ADD_AUTH_TOKEN, true);
const security: SecurityOptions = {...this.defaultSecurityOptions, ...sc};
const headers = this.getHeaders(options);
if (!emitters) {
emitters = this.getEventEmitters();
}
const request = this.httpClient.request(
options.httpMethod,
url,
{
context,
...(body && {body}),
...(responseType && {responseType}),
...security,
...(params && {params}),
headers,
observe: 'events',
reportProgress: true
}
);
return this.requestWithLegacyEventEmitters<T>(request, emitters, options.returnType);
}
post<T = any>(url: string, options?: RequestOptions, sc?: SecurityOptions, emitters?: JsApiEmitters): Promise<T> {
return this.request<T>(url, {...options, httpMethod: 'POST'}, sc, emitters);
}
put<T = any>(url: string, options?: RequestOptions, sc?: SecurityOptions, emitters?: JsApiEmitters): Promise<T> {
return this.request<T>(url, {...options, httpMethod: 'PUT'}, sc, emitters);
}
get<T = any>(url: string, options?: RequestOptions, sc?: SecurityOptions, emitters?: JsApiEmitters): Promise<T> {
return this.request<T>(url, {...options, httpMethod: 'GET'}, sc, emitters);
}
delete<T = void>(url: string, options?: RequestOptions, sc?: SecurityOptions, emitters?: JsApiEmitters): Promise<T> {
return this.request<T>(url, {...options, httpMethod: 'DELETE'}, sc, emitters);
}
private addPromiseListeners<T = any>(promise: Promise<T>, eventEmitter: any) {
const eventPromise = Object.assign(promise, {
on() {
eventEmitter.on.apply(eventEmitter, arguments);
return this;
},
once() {
eventEmitter.once.apply(eventEmitter, arguments);
return this;
},
emit() {
eventEmitter.emit.apply(eventEmitter, arguments);
return this;
},
off() {
eventEmitter.off.apply(eventEmitter, arguments);
return this;
}
});
return eventPromise;
}
private getEventEmitters(): Emitters {
const apiClientEmitter = {
on: this.on.bind(this),
off: this.off.bind(this),
once: this.once.bind(this),
emit: this.emit.bind(this)
};
return {
apiClientEmitter,
eventEmitter: ee({})
};
}
private requestWithLegacyEventEmitters<T = any>(request$: Observable<HttpEvent<T>>, emitters: JsApiEmitters, returnType: any): Promise<T> {
const abort$ = new Subject<void>();
const {eventEmitter, apiClientEmitter} = emitters;
const promise = request$.pipe(
map((res) => {
if (isHttpUploadProgressEvent(res)) {
const percent = Math.round((res.loaded / res.total) * 100);
eventEmitter.emit('progress', {loaded: res.loaded, total: res.total, percent});
}
if (isHttpResponseEvent(res)) {
eventEmitter.emit('success', res.body);
return AdfHttpClient.deserialize(res, returnType);
}
}),
catchError((err: HttpErrorResponse): Observable<AlfrescoApiResponseError> => {
// since we can't always determinate ahead of time if the response is going to be xml or plain text response
// we need to handle false positive cases here.
if (err.status === 200) {
eventEmitter.emit('success', err.error.text);
return of(err.error.text);
}
eventEmitter.emit('error', err);
apiClientEmitter.emit('error', err);
if (err.status === 401) {
eventEmitter.emit('unauthorized');
apiClientEmitter.emit('unauthorized');
}
// for backwards compatibility we need to convert it to error class as the HttpErrorResponse only implements Error interface, not extending it,
// and we need to be able to correctly pass instanceof Error conditions used inside repository
// we also need to pass error as Stringify string as we are detecting statusCodes using JSON.parse(error.message) in some places
const msg = typeof err.error === 'string' ? err.error : JSON.stringify(err.error);
// for backwards compatibility to handle cases in code where we try read response.error.response.body;
const error = {
response: {...err, body: err.error}
};
const alfrescoApiError = new AlfrescoApiResponseError(msg, err.status, error.response);
return throwError(alfrescoApiError);
}),
takeUntil(abort$)
).toPromise();
(promise as any).abort = function() {
eventEmitter.emit('abort');
abort$.next();
abort$.complete();
return this;
};
return this.addPromiseListeners(promise, eventEmitter);
}
private static getBody(options: RequestOptions): any {
const contentType = options.contentType;
const isFormData = contentType === 'multipart/form-data';
const isFormUrlEncoded = contentType === 'application/x-www-form-urlencoded';
const body = options.bodyParam;
if (isFormData) {
return convertObjectToFormData(options.formParams);
}
if (isFormUrlEncoded) {
return new HttpParams({fromObject: removeNilValues(options.formParams)});
}
return body;
}
private getHeaders(options: RequestOptions): HttpHeaders {
const optionsHeaders = {
...options.headerParams,
...(options.accept && {Accept: options.accept}),
...((options.contentType) && {'Content-Type': options.contentType})
};
if (!this.disableCsrf) {
this.setCsrfToken(optionsHeaders);
}
return new HttpHeaders(optionsHeaders);
}
private setCsrfToken(optionsHeaders: any) {
const token = this.createCSRFToken();
optionsHeaders['X-CSRF-TOKEN'] = token;
try {
document.cookie = 'CSRF-TOKEN=' + token + ';path=/';
} catch (err) {
/* continue regardless of error */
}
}
private createCSRFToken(a?: any): string {
const randomValue = window.crypto.getRandomValues(new Uint32Array(1))[0];
return a ? (a ^ ((randomValue * 16) >> (a / 4))).toString(16) : ([1e16] + (1e16).toString()).replace(/[01]/g, this.createCSRFToken);
}
private static getResponseType(options: RequestOptions): 'blob' | 'json' | 'text' {
const isBlobType = options.returnType?.toString().toLowerCase() === 'blob' || options.responseType?.toString().toLowerCase() === 'blob';
if (isBlobType) {
return 'blob';
}
if (options.returnType === 'String') {
return 'text';
}
return 'json';
}
/**
* Deserialize an HTTP response body into a value of the specified type.
*/
private static deserialize<T>(response: HttpResponse<T>, returnType?: Constructor<unknown> | 'blob'): any {
if (response === null) {
return null;
}
const body = response.body;
if (!returnType) {
// for backwards compatibility we need to return empty string instead of null,
// to avoid issues when accessing null response would break application [C309878]
// cannot read property 'entry' of null in cases like
// return this.post(apiUrl, saveFormRepresentation).pipe(map((res: any) => res.entry))
return body !== null ? body : '';
}
if (isBlobResponse(response, returnType)) {
return AdfHttpClient.deserializeBlobResponse(response);
}
if (!isConstructor(returnType)) {
return body;
}
if (Array.isArray(body)) {
return body.map((element) => new returnType(element));
}
return new returnType(body);
}
private static deserializeBlobResponse(response: HttpResponse<Blob>) {
return new Blob([response.body], {type: response.headers.get('Content-Type')});
}
}

View File

@@ -1,227 +0,0 @@
/*!
* @license
* Copyright © 2005-2023 Hyland Software, Inc. and its affiliates. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { SHOULD_ADD_AUTH_TOKEN } from '@alfresco/adf-core/auth';
import { Emitters as JsApiEmitters, HttpClient as JsApiHttpClient, RequestOptions, SecurityOptions, isBrowser } from '@alfresco/js-api';
import { HttpClient, HttpContext, HttpErrorResponse, HttpEvent, HttpHeaders, HttpParams, HttpResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, of, Subject, throwError } from 'rxjs';
import { catchError, map, takeUntil } from 'rxjs/operators';
import { convertObjectToFormData, getQueryParamsWithCustomEncoder, isBlobResponse, isConstructor, isHttpResponseEvent, isHttpUploadProgressEvent, removeNilValues } from './alfresco-api.utils';
import { AlfrescoApiParamEncoder } from './alfresco-api.param-encoder';
import { AlfrescoApiResponseError } from './alfresco-api.response-error';
import { Constructor } from '../types';
@Injectable({
providedIn: 'root'
})
export class AlfrescoApiHttpClient implements JsApiHttpClient {
constructor(private httpClient: HttpClient) {}
request<T = any>(url: string, options: RequestOptions, sc: SecurityOptions, emitters: JsApiEmitters): Promise<T> {
const body = AlfrescoApiHttpClient.getBody(options);
const params = getQueryParamsWithCustomEncoder(options.queryParams, new AlfrescoApiParamEncoder());
const headers = AlfrescoApiHttpClient.getHeaders(options);
const responseType = AlfrescoApiHttpClient.getResponseType(options);
const context = new HttpContext().set(SHOULD_ADD_AUTH_TOKEN, true);
const request = this.httpClient.request(
options.httpMethod,
url,
{
context,
...(body && { body }),
...(responseType && { responseType }),
...(sc.withCredentials && { withCredentials: true }),
...(params && { params }),
headers,
observe: 'events',
reportProgress: true
}
);
return this.requestWithLegacyEventEmitters<T>(request, emitters, options.returnType);
}
post<T = any>(url: string, options: RequestOptions, sc: SecurityOptions, emitters: JsApiEmitters): Promise<T> {
return this.request<T>(url, { ...options, httpMethod: 'POST' }, sc, emitters);
}
put<T = any>(url: string, options: RequestOptions, sc: SecurityOptions, emitters: JsApiEmitters): Promise<T> {
return this.request<T>(url, { ...options, httpMethod: 'PUT' }, sc, emitters);
}
get<T = any>(url: string, options: RequestOptions, sc: SecurityOptions, emitters: JsApiEmitters): Promise<T> {
return this.request<T>(url, { ...options, httpMethod: 'GET' }, sc, emitters);
}
delete<T = void>(url: string, options: RequestOptions, sc: SecurityOptions, emitters: JsApiEmitters): Promise<T> {
return this.request<T>(url, { ...options, httpMethod: 'DELETE' }, sc, emitters);
}
private requestWithLegacyEventEmitters<T = any>(request$: Observable<HttpEvent<T>>, emitters: JsApiEmitters, returnType: any): Promise<T> {
const abort$ = new Subject<void>();
const { eventEmitter, apiClientEmitter } = emitters;
const promise = request$.pipe(
map((res) => {
if (isHttpUploadProgressEvent(res)) {
const percent = Math.round((res.loaded / res.total) * 100);
eventEmitter.emit('progress', { loaded: res.loaded, total: res.total, percent });
}
if (isHttpResponseEvent(res)) {
eventEmitter.emit('success', res.body);
return AlfrescoApiHttpClient.deserialize(res, returnType);
}
}),
catchError((err: HttpErrorResponse): Observable<AlfrescoApiResponseError> => {
// since we can't always determinate ahead of time if the response is going to be xml or plain text response
// we need to handle false positive cases here.
if (err.status === 200) {
eventEmitter.emit('success', err.error.text);
return of(err.error.text);
}
eventEmitter.emit('error', err);
apiClientEmitter.emit('error', err);
if (err.status === 401) {
eventEmitter.emit('unauthorized');
apiClientEmitter.emit('unauthorized');
}
// for backwards compatibility we need to convert it to error class as the HttpErrorResponse only implements Error interface, not extending it,
// and we need to be able to correctly pass instanceof Error conditions used inside repository
// we also need to pass error as Stringify string as we are detecting statusCodes using JSON.parse(error.message) in some places
const msg = typeof err.error === 'string' ? err.error : JSON.stringify(err.error);
// for backwards compatibility to handle cases in code where we try read response.error.response.body;
const error = {
response: { ...err, body: err.error }
};
const alfrescoApiError = new AlfrescoApiResponseError(msg, err.status, error);
return throwError(alfrescoApiError);
}),
takeUntil(abort$)
).toPromise();
(promise as any).abort = function() {
eventEmitter.emit('abort');
abort$.next();
abort$.complete();
return this;
};
return promise;
}
private static getBody(options: RequestOptions): any {
const contentType = options.contentType;
const isFormData = contentType === 'multipart/form-data';
const isFormUrlEncoded = contentType === 'application/x-www-form-urlencoded';
const body = options.bodyParam;
if (isFormData) {
return convertObjectToFormData(options.formParams);
}
if (isFormUrlEncoded) {
return new HttpParams({ fromObject: removeNilValues(options.formParams) });
}
return body;
}
private static getHeaders(options: RequestOptions): HttpHeaders {
const optionsHeaders = {
...options.headerParams,
...(options.accept && { Accept: options.accept }),
...((options.contentType) && { 'Content-Type': options.contentType })
};
return new HttpHeaders(optionsHeaders);
}
private static getResponseType(options: RequestOptions): 'blob' | 'json' | 'text' {
const isBlobType = options.returnType?.toString().toLowerCase() === 'blob' || options.responseType?.toString().toLowerCase() === 'blob';
if (isBlobType) {
return 'blob';
}
if (options.returnType === 'String') {
return 'text';
}
return 'json';
}
/**
* Deserialize an HTTP response body into a value of the specified type.
*/
private static deserialize<T>(response: HttpResponse<T>, returnType?: Constructor<unknown> | 'blob'): any {
if (response === null) {
return null;
}
const body = response.body;
if (!returnType) {
// for backwards compatibility we need to return empty string instead of null,
// to avoid issues when accessing null response would break application [C309878]
// cannot read property 'entry' of null in cases like
// return this.post(apiUrl, saveFormRepresentation).pipe(map((res: any) => res.entry))
return body !== null ? body : '';
}
if (isBlobResponse(response, returnType)) {
return AlfrescoApiHttpClient.deserializeBlobResponse(response);
}
if (!isConstructor(returnType)) {
return body;
}
if (Array.isArray(body)) {
return body.map((element) => new returnType(element));
}
return new returnType(body);
}
private static deserializeBlobResponse(response: HttpResponse<Blob>) {
if (isBrowser()) {
return new Blob([response.body], { type: response.headers.get('Content-Type') });
}
return Buffer.from(response.body as unknown as WithImplicitCoercion<string>, 'binary');
}
}

View File

@@ -19,7 +19,7 @@ export class AlfrescoApiResponseError extends Error {
public name = 'AlfrescoApiResponseError'; public name = 'AlfrescoApiResponseError';
constructor(msg: string, public status: number, public error: { response: Record<string, any> }) { constructor(msg: string, public status: number, public response: Record<string, any> ) {
super(msg); super(msg);
} }
} }

View File

@@ -0,0 +1,36 @@
/*!
* @license
* Copyright © 2005-2023 Hyland Software, Inc. and its affiliates. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export interface RequestOptions {
httpMethod?: string;
queryParams?: any;
headerParams?: any;
formParams?: any;
bodyParam?: any;
returnType?: any;
responseType?: string;
readonly accept?: string;
readonly contentType?: string;
}
export interface SecurityOptions {
readonly isBpmRequest: boolean;
readonly enableCsrf?: boolean;
readonly withCredentials?: boolean;
readonly authentications: any;
readonly defaultHeaders: Record<string, string>;
}

View File

@@ -48,6 +48,7 @@ describe('AuthenticationInterceptor', () => {
}); });
it('should call add auth token method when SHOULD_ADD_AUTH_TOKEN context is set to true', () => { it('should call add auth token method when SHOULD_ADD_AUTH_TOKEN context is set to true', () => {
addTokenToHeaderSpy.and.callThrough();
request.context.set(SHOULD_ADD_AUTH_TOKEN, true); request.context.set(SHOULD_ADD_AUTH_TOKEN, true);
interceptor.intercept(request, mockNext); interceptor.intercept(request, mockNext);
expect(addTokenToHeaderSpy).toHaveBeenCalled(); expect(addTokenToHeaderSpy).toHaveBeenCalled();

View File

@@ -26,6 +26,7 @@ import { CommonModule } from '@angular/common';
import { ShellAppService, SHELL_APP_SERVICE } from '../../services/shell-app.service'; import { ShellAppService, SHELL_APP_SERVICE } from '../../services/shell-app.service';
import { HttpClientModule } from '@angular/common/http'; import { HttpClientModule } from '@angular/common/http';
import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { TranslateModule } from '@ngx-translate/core';
class MockRouter { class MockRouter {
private url = 'some-url'; private url = 'some-url';
@@ -57,7 +58,15 @@ describe('AppLayoutComponent', () => {
}; };
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CommonModule, NoopAnimationsModule, HttpClientModule, SidenavLayoutModule, ExtensionsModule, RouterModule.forChild([])], imports: [
CommonModule,
NoopAnimationsModule,
HttpClientModule,
SidenavLayoutModule,
ExtensionsModule,
RouterModule.forChild([]),
TranslateModule.forRoot()
],
providers: [ providers: [
{ {
provide: Router, provide: Router,

View File

@@ -15,7 +15,7 @@
* limitations under the License. * limitations under the License.
*/ */
import { AlfrescoApiHttpClient } from '@alfresco/adf-core/api'; import { AdfHttpClient } from '@alfresco/adf-core/api';
import { StorageService } from '../common/services/storage.service'; import { StorageService } from '../common/services/storage.service';
import { AlfrescoApi, AlfrescoApiConfig } from '@alfresco/js-api'; import { AlfrescoApi, AlfrescoApiConfig } from '@alfresco/js-api';
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
@@ -23,16 +23,19 @@ import { AppConfigService } from '../app-config';
import { AlfrescoApiService } from '../services/alfresco-api.service'; import { AlfrescoApiService } from '../services/alfresco-api.service';
@Injectable() @Injectable()
export class AlfrescoApiServiceWithAngularBasedHttpClient extends AlfrescoApiService { export class AlfrescoApiNoAuthService extends AlfrescoApiService {
constructor( constructor(
storage: StorageService, storage: StorageService,
appConfig: AppConfigService, appConfig: AppConfigService,
private readonly alfrescoApiHttpClient: AlfrescoApiHttpClient private readonly adfHttpClient: AdfHttpClient
) { ) {
super(appConfig, storage); super(appConfig, storage);
} }
override createInstance(config: AlfrescoApiConfig) { override createInstance(config: AlfrescoApiConfig) {
return new AlfrescoApi(config, this.alfrescoApiHttpClient); return new AlfrescoApi({
...config,
oauthInit: false
}, this.adfHttpClient);
} }
} }

View File

@@ -17,9 +17,11 @@
import { AppConfigService, AppConfigValues } from './app-config.service'; import { AppConfigService, AppConfigValues } from './app-config.service';
import { StorageService } from '../common/services/storage.service'; import { StorageService } from '../common/services/storage.service';
import { AdfHttpClient } from '@alfresco/adf-core/api';
export function loadAppConfig(appConfigService: AppConfigService, storageService: StorageService) { export function loadAppConfig(appConfigService: AppConfigService, storageService: StorageService, adfHttpClient: AdfHttpClient) {
return () => appConfigService.load().then(() => { return () => appConfigService.load().then(() => {
adfHttpClient.disableCsrf = appConfigService.get<boolean>(AppConfigValues.DISABLECSRF);
storageService.prefix = appConfigService.get<string>(AppConfigValues.STORAGE_PREFIX, ''); storageService.prefix = appConfigService.get<string>(AppConfigValues.STORAGE_PREFIX, '');
}); });
} }

View File

@@ -17,7 +17,7 @@
import { APP_INITIALIZER, ModuleWithProviders, NgModule } from '@angular/core'; import { APP_INITIALIZER, ModuleWithProviders, NgModule } from '@angular/core';
import { AuthConfig, AUTH_CONFIG, OAuthModule, OAuthService, OAuthStorage } from 'angular-oauth2-oidc'; import { AuthConfig, AUTH_CONFIG, OAuthModule, OAuthService, OAuthStorage } from 'angular-oauth2-oidc';
import { AlfrescoApiServiceWithAngularBasedHttpClient } from '../../api-factories/alfresco-api-service-with-angular-based-http-client'; import { AlfrescoApiNoAuthService } from '../../api-factories/alfresco-api-no-auth.service';
import { AlfrescoApiService } from '../../services/alfresco-api.service'; import { AlfrescoApiService } from '../../services/alfresco-api.service';
import { AuthGuardBpm } from '../guard/auth-guard-bpm.service'; import { AuthGuardBpm } from '../guard/auth-guard-bpm.service';
import { AuthGuardEcm } from '../guard/auth-guard-ecm.service'; import { AuthGuardEcm } from '../guard/auth-guard-ecm.service';
@@ -47,7 +47,7 @@ export function loginFactory(oAuthService: OAuthService, storage: OAuthStorage,
{ provide: AuthGuardEcm, useClass: OidcAuthGuard }, { provide: AuthGuardEcm, useClass: OidcAuthGuard },
{ provide: AuthGuardBpm, useClass: OidcAuthGuard }, { provide: AuthGuardBpm, useClass: OidcAuthGuard },
{ provide: AuthenticationService, useClass: OIDCAuthenticationService }, { provide: AuthenticationService, useClass: OIDCAuthenticationService },
{ provide: AlfrescoApiService, useClass: AlfrescoApiServiceWithAngularBasedHttpClient }, { provide: AlfrescoApiService, useClass: AlfrescoApiNoAuthService },
{ {
provide: AUTH_CONFIG, provide: AUTH_CONFIG,
useFactory: authConfigFactory, useFactory: authConfigFactory,

View File

@@ -16,11 +16,11 @@
*/ */
import { Injectable, inject } from '@angular/core'; import { Injectable, inject } from '@angular/core';
import { OAuthService, OAuthStorage } from 'angular-oauth2-oidc'; import { OAuthEvent, OAuthService, OAuthStorage } from 'angular-oauth2-oidc';
import { EMPTY, Observable } from 'rxjs'; import { EMPTY, Observable } from 'rxjs';
import { catchError, map } from 'rxjs/operators'; import { catchError, filter, map } from 'rxjs/operators';
import { AppConfigValues } from '../../app-config/app-config.service'; import { AppConfigValues } from '../../app-config/app-config.service';
import { BaseAuthenticationService } from '../../services/base-authentication.service'; import { BaseAuthenticationService } from '../services/base-authentication.service';
import { JwtHelperService } from '../services/jwt-helper.service'; import { JwtHelperService } from '../services/jwt-helper.service';
import { AuthConfigService } from '../oidc/auth-config.service'; import { AuthConfigService } from '../oidc/auth-config.service';
import { AuthService } from './auth.service'; import { AuthService } from './auth.service';
@@ -39,7 +39,9 @@ export class OIDCAuthenticationService extends BaseAuthenticationService {
constructor() { constructor() {
super(); super();
this.alfrescoApi.alfrescoApiInitialized.subscribe(() => { this.alfrescoApi.alfrescoApiInitialized.subscribe(() => {
this.alfrescoApi.getInstance().reply('logged-in', () => { this.oauthService.events.pipe(
filter((event)=> event.type === 'token_received')
).subscribe(()=>{
this.onLogin.next(); this.onLogin.next();
}); });
}); });
@@ -87,6 +89,14 @@ export class OIDCAuthenticationService extends BaseAuthenticationService {
); );
} }
getEcmUsername(): string {
return (this.oauthService.getIdentityClaims() as any).preferred_username;
}
getBpmUsername(): string {
return (this.oauthService.getIdentityClaims() as any).preferred_username;
}
ssoImplicitLogin() { ssoImplicitLogin() {
this.oauthService.initLoginFlow(); this.oauthService.initLoginFlow();
} }
@@ -117,4 +127,8 @@ export class OIDCAuthenticationService extends BaseAuthenticationService {
this.auth.login(); this.auth.login();
} }
} }
once(event: string): Observable<OAuthEvent> {
return this.oauthService.events.pipe(filter(_event => _event.type === event));
}
} }

View File

@@ -21,7 +21,7 @@ import { AppConfigValues } from '../../app-config/app-config.service';
import { map, catchError, tap } from 'rxjs/operators'; import { map, catchError, tap } from 'rxjs/operators';
import { JwtHelperService } from './jwt-helper.service'; import { JwtHelperService } from './jwt-helper.service';
import { StorageService } from '../../common/services/storage.service'; import { StorageService } from '../../common/services/storage.service';
import { BaseAuthenticationService } from '../../services/base-authentication.service'; import { BaseAuthenticationService } from './base-authentication.service';
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
@@ -152,6 +152,24 @@ export class AuthenticationService extends BaseAuthenticationService {
return false; return false;
} }
/**
* Gets the ECM username.
*
* @returns The ECM username
*/
getEcmUsername(): string {
return this.alfrescoApi.getInstance().getEcmUsername();
}
/**
* Gets the BPM username
*
* @returns The BPM username
*/
getBpmUsername(): string {
return this.alfrescoApi.getInstance().getBpmUsername();
}
isImplicitFlow(): boolean { isImplicitFlow(): boolean {
return !!this.appConfig.oauth2?.implicitFlow; return !!this.appConfig.oauth2?.implicitFlow;
} }
@@ -169,5 +187,12 @@ export class AuthenticationService extends BaseAuthenticationService {
return this.storageService.getItem(JwtHelperService.USER_ACCESS_TOKEN); return this.storageService.getItem(JwtHelperService.USER_ACCESS_TOKEN);
} }
reset() {} reset() { }
once(event: string): Observable<any> {
const alfrescoApiEvent = event === 'token_received' ? 'token_issued' : event;
return new Observable((subscriber) => {
this.alfrescoApi.getInstance().oauth2Auth.once(alfrescoApiEvent, () => subscriber.next());
});
}
} }

View File

@@ -15,14 +15,14 @@
* limitations under the License. * limitations under the License.
*/ */
import { PeopleApi, UserProfileApi, UserRepresentation } from '@alfresco/js-api'; import { PeopleApi, UserProfileApi } from '@alfresco/js-api';
import { HttpHeaders } from '@angular/common/http'; import { HttpHeaders } from '@angular/common/http';
import { RedirectionModel } from '../auth/models/redirection.model'; import { RedirectionModel } from '../models/redirection.model';
import { from, Observable, Observer, ReplaySubject, throwError } from 'rxjs'; import { Observable, Observer, ReplaySubject, throwError } from 'rxjs';
import { AppConfigService, AppConfigValues } from '../app-config/app-config.service'; import { AppConfigService, AppConfigValues } from '../../app-config/app-config.service';
import { AlfrescoApiService } from './alfresco-api.service'; import { AlfrescoApiService } from '../../services/alfresco-api.service';
import { CookieService } from '../common/services/cookie.service'; import { CookieService } from '../../common/services/cookie.service';
import { LogService } from '../common/services/log.service'; import { LogService } from '../../common/services/log.service';
import { inject } from '@angular/core'; import { inject } from '@angular/core';
const REMEMBER_ME_COOKIE_KEY = 'ALFRESCO_REMEMBER_ME'; const REMEMBER_ME_COOKIE_KEY = 'ALFRESCO_REMEMBER_ME';
@@ -57,14 +57,15 @@ export abstract class BaseAuthenticationService {
abstract isLoggedIn(): boolean; abstract isLoggedIn(): boolean;
abstract isLoggedInWith(provider: string): boolean; abstract isLoggedInWith(provider: string): boolean;
abstract isOauth(): boolean; abstract isOauth(): boolean;
abstract isImplicitFlow(): boolean;
abstract isAuthCodeFlow(): boolean;
abstract login(username: string, password: string, rememberMe?: boolean): Observable<{ type: string; ticket: any }>; abstract login(username: string, password: string, rememberMe?: boolean): Observable<{ type: string; ticket: any }>;
abstract ssoImplicitLogin(): void; abstract ssoImplicitLogin(): void;
abstract logout(): Observable<any>; abstract logout(): Observable<any>;
abstract isEcmLoggedIn(): boolean; abstract isEcmLoggedIn(): boolean;
abstract isBpmLoggedIn(): boolean; abstract isBpmLoggedIn(): boolean;
abstract getEcmUsername(): string;
abstract getBpmUsername(): string;
abstract reset(): void; abstract reset(): void;
abstract once(event: string): Observable<any>;
getBearerExcludedUrls(): readonly string[] { getBearerExcludedUrls(): readonly string[] {
return this.bearerExcludedUrls; return this.bearerExcludedUrls;
@@ -126,24 +127,6 @@ export abstract class BaseAuthenticationService {
return header.set('Authorization', ticket); return header.set('Authorization', ticket);
} }
/**
* Gets the ECM username.
*
* @returns The ECM username
*/
getEcmUsername(): string {
return this.alfrescoApi.getInstance().getEcmUsername();
}
/**
* Gets the BPM username
*
* @returns The BPM username
*/
getBpmUsername(): string {
return this.alfrescoApi.getInstance().getBpmUsername();
}
isPublicUrl(): boolean { isPublicUrl(): boolean {
return this.alfrescoApi.getInstance().isPublicUrl(); return this.alfrescoApi.getInstance().isPublicUrl();
} }
@@ -206,15 +189,6 @@ export abstract class BaseAuthenticationService {
return null; return null;
} }
/**
* Gets information about the user currently logged into APS.
*
* @returns User information
*/
getBpmLoggedUser(): Observable<UserRepresentation> {
return from(this.profileApi.getProfile());
}
/** /**
* Prints an error message in the console browser * Prints an error message in the console browser
* *

View File

@@ -17,7 +17,6 @@
import { fakeAsync, TestBed } from '@angular/core/testing'; import { fakeAsync, TestBed } from '@angular/core/testing';
import { setupTestBed } from '../../testing/setup-test-bed'; import { setupTestBed } from '../../testing/setup-test-bed';
import { AlfrescoApiService } from './../../services/alfresco-api.service';
import { IdentityGroupService } from './identity-group.service'; import { IdentityGroupService } from './identity-group.service';
import { HttpErrorResponse } from '@angular/common/http'; import { HttpErrorResponse } from '@angular/common/http';
import { throwError, of } from 'rxjs'; import { throwError, of } from 'rxjs';
@@ -25,23 +24,18 @@ import {
mockIdentityRoles, mockIdentityRoles,
clientRoles, clientRoles,
mockIdentityGroup1, mockIdentityGroup1,
mockIdentityGroupsCount mockIdentityGroupsCount,
mockIdentityGroups,
roleMappingMock
} from '../mock/identity-group.mock'; } from '../mock/identity-group.mock';
import { CoreTestingModule } from '../../testing/core.testing.module'; import { CoreTestingModule } from '../../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { import { AdfHttpClient } from '../../../../api/src';
applicationDetailsMockApi,
createGroupMappingApi,
deleteGroupMappingApi,
groupsMockApi,
noRoleMappingApi,
roleMappingApi,
updateGroupMappingApi
} from '../mock/oauth2.service.mock';
describe('IdentityGroupService', () => { describe('IdentityGroupService', () => {
let service: IdentityGroupService; let service: IdentityGroupService;
let apiService: AlfrescoApiService; let adfHttpClient: AdfHttpClient;
let requestSpy: jasmine.Spy;
setupTestBed({ setupTestBed({
imports: [ imports: [
@@ -52,11 +46,12 @@ describe('IdentityGroupService', () => {
beforeEach(fakeAsync(() => { beforeEach(fakeAsync(() => {
service = TestBed.inject(IdentityGroupService); service = TestBed.inject(IdentityGroupService);
apiService = TestBed.inject(AlfrescoApiService); adfHttpClient = TestBed.inject(AdfHttpClient);
requestSpy = spyOn(adfHttpClient, 'request');
})); }));
it('should be able to fetch groups based on group name', (done) => { it('should be able to fetch groups based on group name', (done) => {
spyOn(apiService, 'getInstance').and.returnValue(groupsMockApi); requestSpy.and.returnValue(Promise.resolve(mockIdentityGroups));
service.findGroupsByName({name: 'mock'}).subscribe((res) => { service.findGroupsByName({name: 'mock'}).subscribe((res) => {
expect(res).toBeDefined(); expect(res).toBeDefined();
expect(res).not.toBeNull(); expect(res).not.toBeNull();
@@ -72,7 +67,7 @@ describe('IdentityGroupService', () => {
}); });
it('should return true if group has client role mapping', (done) => { it('should return true if group has client role mapping', (done) => {
spyOn(apiService, 'getInstance').and.returnValue(roleMappingApi); requestSpy.and.returnValue(Promise.resolve(roleMappingMock));
service.checkGroupHasClientApp('mock-group-id', 'mock-app-id').subscribe((hasRole) => { service.checkGroupHasClientApp('mock-group-id', 'mock-app-id').subscribe((hasRole) => {
expect(hasRole).toBeDefined(); expect(hasRole).toBeDefined();
expect(hasRole).toBe(true); expect(hasRole).toBe(true);
@@ -81,7 +76,7 @@ describe('IdentityGroupService', () => {
}); });
it('should return false if group does not have client role mapping', (done) => { it('should return false if group does not have client role mapping', (done) => {
spyOn(apiService, 'getInstance').and.returnValue(noRoleMappingApi); requestSpy.and.returnValue(Promise.resolve([]));
service.checkGroupHasClientApp('mock-group-id', 'mock-app-id').subscribe((hasRole) => { service.checkGroupHasClientApp('mock-group-id', 'mock-app-id').subscribe((hasRole) => {
expect(hasRole).toBeDefined(); expect(hasRole).toBeDefined();
expect(hasRole).toBe(false); expect(hasRole).toBe(false);
@@ -226,7 +221,7 @@ describe('IdentityGroupService', () => {
}); });
it('should be able to fetch the client id', (done) => { it('should be able to fetch the client id', (done) => {
spyOn(apiService, 'getInstance').and.returnValue(applicationDetailsMockApi); requestSpy.and.returnValue(Promise.resolve([{id: 'mock-app-id', name: 'mock-app-name'}]));
service.getClientIdByApplicationName('mock-app-name').subscribe((clientId) => { service.getClientIdByApplicationName('mock-app-name').subscribe((clientId) => {
expect(clientId).toBeDefined(); expect(clientId).toBeDefined();
expect(clientId).not.toBeNull(); expect(clientId).not.toBeNull();
@@ -236,7 +231,7 @@ describe('IdentityGroupService', () => {
}); });
it('should be able to all fetch groups', (done) => { it('should be able to all fetch groups', (done) => {
spyOn(apiService, 'getInstance').and.returnValue(groupsMockApi); requestSpy.and.returnValue(Promise.resolve(mockIdentityGroups));
service.getGroups().subscribe((res) => { service.getGroups().subscribe((res) => {
expect(res.length).toBe(5); expect(res.length).toBe(5);
expect(res[0].id).toBe('mock-group-id-1'); expect(res[0].id).toBe('mock-group-id-1');
@@ -273,7 +268,7 @@ describe('IdentityGroupService', () => {
it('should be able to query groups based on first & max params', (done) => { it('should be able to query groups based on first & max params', (done) => {
spyOn(service, 'getTotalGroupsCount').and.returnValue(of(mockIdentityGroupsCount)); spyOn(service, 'getTotalGroupsCount').and.returnValue(of(mockIdentityGroupsCount));
spyOn(apiService, 'getInstance').and.returnValue(groupsMockApi); requestSpy.and.returnValue(Promise.resolve(mockIdentityGroups));
service.queryGroups({first: 0, max: 5}).subscribe((res) => { service.queryGroups({first: 0, max: 5}).subscribe((res) => {
expect(res).toBeDefined(); expect(res).toBeDefined();
expect(res).not.toBeNull(); expect(res).not.toBeNull();
@@ -314,7 +309,7 @@ describe('IdentityGroupService', () => {
}); });
it('should be able to create group', (done) => { it('should be able to create group', (done) => {
const createCustomApiSpy = spyOn(apiService, 'getInstance').and.returnValue(createGroupMappingApi); const createCustomApiSpy = requestSpy.and.returnValue(Promise.resolve());
service.createGroup(mockIdentityGroup1).subscribe(() => { service.createGroup(mockIdentityGroup1).subscribe(() => {
expect(createCustomApiSpy).toHaveBeenCalled(); expect(createCustomApiSpy).toHaveBeenCalled();
done(); done();
@@ -344,7 +339,7 @@ describe('IdentityGroupService', () => {
}); });
it('should be able to update group', (done) => { it('should be able to update group', (done) => {
const updateCustomApiSpy = spyOn(apiService, 'getInstance').and.returnValue(updateGroupMappingApi); const updateCustomApiSpy = requestSpy.and.returnValue(Promise.resolve());
service.updateGroup('mock-group-id', mockIdentityGroup1).subscribe(() => { service.updateGroup('mock-group-id', mockIdentityGroup1).subscribe(() => {
expect(updateCustomApiSpy).toHaveBeenCalled(); expect(updateCustomApiSpy).toHaveBeenCalled();
done(); done();
@@ -374,7 +369,7 @@ describe('IdentityGroupService', () => {
}); });
it('should be able to delete group', (done) => { it('should be able to delete group', (done) => {
const deleteCustomApiSpy = spyOn(apiService, 'getInstance').and.returnValue(deleteGroupMappingApi); const deleteCustomApiSpy = requestSpy.and.returnValue(Promise.resolve());
service.deleteGroup('mock-group-id').subscribe(() => { service.deleteGroup('mock-group-id').subscribe(() => {
expect(deleteCustomApiSpy).toHaveBeenCalled(); expect(deleteCustomApiSpy).toHaveBeenCalled();
done(); done();

View File

@@ -22,31 +22,20 @@ import {
mockIdentityUser1, mockIdentityUser1,
mockIdentityUser2, mockIdentityUser2,
mockIdentityRole, mockIdentityRole,
mockIdentityUsers mockIdentityUsers,
mockAssignedRoles,
mockAvailableRoles,
mockEffectiveRoles
} from '../mock/identity-user.mock'; } from '../mock/identity-user.mock';
import { mockJoinGroupRequest } from '../mock/identity-group.mock'; import { mockGroups, mockJoinGroupRequest } from '../mock/identity-group.mock';
import { IdentityUserService } from './identity-user.service'; import { IdentityUserService } from './identity-user.service';
import { JwtHelperService } from './jwt-helper.service'; import { JwtHelperService } from './jwt-helper.service';
import { setupTestBed } from '../../testing/setup-test-bed'; import { setupTestBed } from '../../testing/setup-test-bed';
import { AlfrescoApiService } from '../../services/alfresco-api.service';
import { mockToken } from '../mock/jwt-helper.service.spec'; import { mockToken } from '../mock/jwt-helper.service.spec';
import { IdentityRoleModel } from '../models/identity-role.model'; import { IdentityRoleModel } from '../models/identity-role.model';
import { CoreTestingModule } from '../../testing/core.testing.module'; import { CoreTestingModule } from '../../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { import { AdfHttpClient } from '../../../../api/src';
assignRolesMockApi,
createUserMockApi,
deleteUserMockApi,
getAssignedRolesMockApi,
getAvailableRolesMockApi,
getEffectiveRolesMockApi,
getInvolvedGroupsMockApi,
joinGroupMockApi,
leaveGroupMockApi,
queryUsersMockApi,
removeRolesMockApi,
updateUserMockApi
} from '../mock/oauth2.service.mock';
describe('IdentityUserService', () => { describe('IdentityUserService', () => {
@@ -59,7 +48,8 @@ describe('IdentityUserService', () => {
]; ];
let service: IdentityUserService; let service: IdentityUserService;
let alfrescoApiService: AlfrescoApiService; let adfHttpClient: AdfHttpClient;
let requestSpy: jasmine.Spy;
setupTestBed({ setupTestBed({
imports: [ imports: [
@@ -70,7 +60,8 @@ describe('IdentityUserService', () => {
beforeEach(() => { beforeEach(() => {
service = TestBed.inject(IdentityUserService); service = TestBed.inject(IdentityUserService);
alfrescoApiService = TestBed.inject(AlfrescoApiService); adfHttpClient = TestBed.inject(AdfHttpClient);
requestSpy = spyOn(adfHttpClient, 'request');
}); });
beforeEach(() => { beforeEach(() => {
@@ -297,7 +288,7 @@ describe('IdentityUserService', () => {
}); });
it('should be able to query users based on query params (first & max params)', (done) => { it('should be able to query users based on query params (first & max params)', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(queryUsersMockApi); requestSpy.and.returnValue(Promise.resolve(mockIdentityUsers));
service.queryUsers({first: 0, max: 5}).subscribe((res) => { service.queryUsers({first: 0, max: 5}).subscribe((res) => {
expect(res).toBeDefined(); expect(res).toBeDefined();
expect(res).not.toBeNull(); expect(res).not.toBeNull();
@@ -335,7 +326,7 @@ describe('IdentityUserService', () => {
}); });
it('should be able to create user', (done) => { it('should be able to create user', (done) => {
const createCustomApiSpy = spyOn(alfrescoApiService, 'getInstance').and.returnValue(createUserMockApi); const createCustomApiSpy = requestSpy.and.returnValue(Promise.resolve());
service.createUser(mockIdentityUser1).subscribe(() => { service.createUser(mockIdentityUser1).subscribe(() => {
expect(createCustomApiSpy).toHaveBeenCalled(); expect(createCustomApiSpy).toHaveBeenCalled();
done(); done();
@@ -365,7 +356,7 @@ describe('IdentityUserService', () => {
}); });
it('should be able to update user', (done) => { it('should be able to update user', (done) => {
const updateCustomApiSpy = spyOn(alfrescoApiService, 'getInstance').and.returnValue(updateUserMockApi); const updateCustomApiSpy = requestSpy.and.returnValue(Promise.resolve());
service.updateUser('mock-id-2', mockIdentityUser2).subscribe(() => { service.updateUser('mock-id-2', mockIdentityUser2).subscribe(() => {
expect(updateCustomApiSpy).toHaveBeenCalled(); expect(updateCustomApiSpy).toHaveBeenCalled();
done(); done();
@@ -395,7 +386,7 @@ describe('IdentityUserService', () => {
}); });
it('should be able to delete group', (done) => { it('should be able to delete group', (done) => {
const deleteCustomApiSpy = spyOn(alfrescoApiService, 'getInstance').and.returnValue(deleteUserMockApi); const deleteCustomApiSpy = requestSpy.and.returnValue(Promise.resolve());
service.deleteUser('mock-user-id').subscribe(() => { service.deleteUser('mock-user-id').subscribe(() => {
expect(deleteCustomApiSpy).toHaveBeenCalled(); expect(deleteCustomApiSpy).toHaveBeenCalled();
done(); done();
@@ -425,7 +416,7 @@ describe('IdentityUserService', () => {
}); });
it('should be able to fetch involved groups based on user id', (done) => { it('should be able to fetch involved groups based on user id', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(getInvolvedGroupsMockApi); requestSpy.and.returnValue(Promise.resolve(mockGroups));
service.getInvolvedGroups('mock-user-id').subscribe((res) => { service.getInvolvedGroups('mock-user-id').subscribe((res) => {
expect(res).toBeDefined(); expect(res).toBeDefined();
expect(res).not.toBeNull(); expect(res).not.toBeNull();
@@ -461,7 +452,7 @@ describe('IdentityUserService', () => {
}); });
it('should be able to join the group', (done) => { it('should be able to join the group', (done) => {
const joinGroupCustomApiSpy = spyOn(alfrescoApiService, 'getInstance').and.returnValue(joinGroupMockApi); const joinGroupCustomApiSpy = requestSpy.and.returnValue(Promise.resolve());
service.joinGroup(mockJoinGroupRequest).subscribe(() => { service.joinGroup(mockJoinGroupRequest).subscribe(() => {
expect(joinGroupCustomApiSpy).toHaveBeenCalled(); expect(joinGroupCustomApiSpy).toHaveBeenCalled();
done(); done();
@@ -491,7 +482,7 @@ describe('IdentityUserService', () => {
}); });
it('should be able to leave the group', (done) => { it('should be able to leave the group', (done) => {
const leaveGroupCustomApiSpy = spyOn(alfrescoApiService, 'getInstance').and.returnValue(leaveGroupMockApi); const leaveGroupCustomApiSpy = requestSpy.and.returnValue(Promise.resolve());
service.leaveGroup('mock-user-id', 'mock-group-id').subscribe(() => { service.leaveGroup('mock-user-id', 'mock-group-id').subscribe(() => {
expect(leaveGroupCustomApiSpy).toHaveBeenCalled(); expect(leaveGroupCustomApiSpy).toHaveBeenCalled();
done(); done();
@@ -521,7 +512,7 @@ describe('IdentityUserService', () => {
}); });
it('should be able to fetch available roles based on user id', (done) => { it('should be able to fetch available roles based on user id', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(getAvailableRolesMockApi); requestSpy.and.returnValue(Promise.resolve(mockAvailableRoles));
service.getAvailableRoles('mock-user-id').subscribe((res) => { service.getAvailableRoles('mock-user-id').subscribe((res) => {
expect(res).toBeDefined(); expect(res).toBeDefined();
expect(res).not.toBeNull(); expect(res).not.toBeNull();
@@ -559,7 +550,7 @@ describe('IdentityUserService', () => {
}); });
it('should be able to fetch assigned roles based on user id', (done) => { it('should be able to fetch assigned roles based on user id', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(getAssignedRolesMockApi); requestSpy.and.returnValue(Promise.resolve(mockAssignedRoles));
service.getAssignedRoles('mock-user-id').subscribe((res) => { service.getAssignedRoles('mock-user-id').subscribe((res) => {
expect(res).toBeDefined(); expect(res).toBeDefined();
expect(res).not.toBeNull(); expect(res).not.toBeNull();
@@ -597,7 +588,7 @@ describe('IdentityUserService', () => {
}); });
it('should be able to fetch effective roles based on user id', (done) => { it('should be able to fetch effective roles based on user id', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(getEffectiveRolesMockApi); requestSpy.and.returnValue(Promise.resolve(mockEffectiveRoles));
service.getEffectiveRoles('mock-user-id').subscribe((res) => { service.getEffectiveRoles('mock-user-id').subscribe((res) => {
expect(res).toBeDefined(); expect(res).toBeDefined();
expect(res).not.toBeNull(); expect(res).not.toBeNull();
@@ -635,7 +626,7 @@ describe('IdentityUserService', () => {
}); });
it('should be able to assign roles to the user', (done) => { it('should be able to assign roles to the user', (done) => {
const assignRolesCustomApiSpy = spyOn(alfrescoApiService, 'getInstance').and.returnValue(assignRolesMockApi); const assignRolesCustomApiSpy = requestSpy.and.returnValue(Promise.resolve());
service.assignRoles('mock-user-id', [mockIdentityRole]).subscribe(() => { service.assignRoles('mock-user-id', [mockIdentityRole]).subscribe(() => {
expect(assignRolesCustomApiSpy).toHaveBeenCalled(); expect(assignRolesCustomApiSpy).toHaveBeenCalled();
done(); done();
@@ -665,7 +656,7 @@ describe('IdentityUserService', () => {
}); });
it('should be able to remove roles', (done) => { it('should be able to remove roles', (done) => {
const removeRolesCustomApiSpy = spyOn(alfrescoApiService, 'getInstance').and.returnValue(removeRolesMockApi); const removeRolesCustomApiSpy = requestSpy.and.returnValue(Promise.resolve());
service.removeRoles('mock-user-id', [mockIdentityRole]).subscribe(() => { service.removeRoles('mock-user-id', [mockIdentityRole]).subscribe(() => {
expect(removeRolesCustomApiSpy).toHaveBeenCalled(); expect(removeRolesCustomApiSpy).toHaveBeenCalled();
done(); done();

View File

@@ -16,9 +16,8 @@
*/ */
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { AlfrescoApiService } from '../../services/alfresco-api.service';
import { Observable, from } from 'rxjs'; import { Observable, from } from 'rxjs';
import { Oauth2Auth } from '@alfresco/js-api'; import { AdfHttpClient } from '@alfresco/adf-core/api';
export const JSON_TYPE = ['application/json']; export const JSON_TYPE = ['application/json'];
@@ -32,25 +31,21 @@ export interface OAuth2RequestParams {
@Injectable({ providedIn: 'root' }) @Injectable({ providedIn: 'root' })
export class OAuth2Service { export class OAuth2Service {
constructor(private alfrescoApiService: AlfrescoApiService) {} constructor(private adfHttpClient: AdfHttpClient) {}
get apiClient(): Oauth2Auth {
return this.alfrescoApiService.getInstance().oauth2Auth;
}
request<T>(opts: OAuth2RequestParams): Observable<T> { request<T>(opts: OAuth2RequestParams): Observable<T> {
const { httpMethod, url, bodyParam, queryParams } = opts;
return from( return from(
this.apiClient.callCustomApi( this.adfHttpClient.request(
opts.url, url,
opts.httpMethod, {
opts.pathParams, httpMethod,
opts.queryParams, queryParams,
{}, headerParams: {},
{}, formParams: {},
opts.bodyParam, bodyParam,
JSON_TYPE, returnType: Object
JSON_TYPE, }
Object
) )
); );
} }

View File

@@ -45,7 +45,6 @@ import { BlankPageModule } from './blank-page/blank-page.module';
import { DirectiveModule } from './directives/directive.module'; import { DirectiveModule } from './directives/directive.module';
import { PipeModule } from './pipes/pipe.module'; import { PipeModule } from './pipes/pipe.module';
import { AlfrescoApiService } from './services/alfresco-api.service';
import { TranslationService } from './translation/translation.service'; import { TranslationService } from './translation/translation.service';
import { SortingPickerModule } from './sorting-picker/sorting-picker.module'; import { SortingPickerModule } from './sorting-picker/sorting-picker.module';
import { IconModule } from './icon/icon.module'; import { IconModule } from './icon/icon.module';
@@ -54,7 +53,7 @@ import { ExtensionsModule } from '@alfresco/adf-extensions';
import { directionalityConfigFactory } from './common/services/directionality-config-factory'; import { directionalityConfigFactory } from './common/services/directionality-config-factory';
import { DirectionalityConfigService } from './common/services/directionality-config.service'; import { DirectionalityConfigService } from './common/services/directionality-config.service';
import { SearchTextModule } from './search-text/search-text-input.module'; import { SearchTextModule } from './search-text/search-text-input.module';
import { AlfrescoJsClientsModule } from '@alfresco/adf-core/api'; import { AdfHttpClient, AlfrescoJsClientsModule } from '@alfresco/adf-core/api';
import { AuthenticationInterceptor, Authentication } from '@alfresco/adf-core/auth'; import { AuthenticationInterceptor, Authentication } from '@alfresco/adf-core/auth';
import { LegacyApiClientModule } from './api-factories/legacy-api-client.module'; import { LegacyApiClientModule } from './api-factories/legacy-api-client.module';
import { HttpClientModule, HttpClientXsrfModule, HTTP_INTERCEPTORS } from '@angular/common/http'; import { HttpClientModule, HttpClientXsrfModule, HTTP_INTERCEPTORS } from '@angular/common/http';
@@ -65,13 +64,6 @@ import { loadAppConfig } from './app-config/app-config.loader';
import { AppConfigService } from './app-config/app-config.service'; import { AppConfigService } from './app-config/app-config.service';
import { StorageService } from './common/services/storage.service'; import { StorageService } from './common/services/storage.service';
import { AlfrescoApiLoaderService, createAlfrescoApiInstance } from './api-factories/alfresco-api-v2-loader.service'; import { AlfrescoApiLoaderService, createAlfrescoApiInstance } from './api-factories/alfresco-api-v2-loader.service';
import { AlfrescoApiServiceWithAngularBasedHttpClient } from './api-factories/alfresco-api-service-with-angular-based-http-client';
interface Config {
readonly useAngularBasedHttpClientInAlfrescoJs: boolean;
}
const defaultConfig: Config = { useAngularBasedHttpClientInAlfrescoJs: false };
@NgModule({ @NgModule({
imports: [ imports: [
@@ -149,7 +141,7 @@ const defaultConfig: Config = { useAngularBasedHttpClientInAlfrescoJs: false };
] ]
}) })
export class CoreModule { export class CoreModule {
static forRoot(config: Config = defaultConfig): ModuleWithProviders<CoreModule> { static forRoot(): ModuleWithProviders<CoreModule> {
return { return {
ngModule: CoreModule, ngModule: CoreModule,
providers: [ providers: [
@@ -159,7 +151,7 @@ export class CoreModule {
{ {
provide: APP_INITIALIZER, provide: APP_INITIALIZER,
useFactory: loadAppConfig, useFactory: loadAppConfig,
deps: [ AppConfigService, StorageService ], multi: true deps: [ AppConfigService, StorageService, AdfHttpClient ], multi: true
}, },
{ {
provide: APP_INITIALIZER, provide: APP_INITIALIZER,
@@ -180,11 +172,7 @@ export class CoreModule {
useFactory: createAlfrescoApiInstance, useFactory: createAlfrescoApiInstance,
deps: [ AlfrescoApiLoaderService ], deps: [ AlfrescoApiLoaderService ],
multi: true multi: true
}, }
...(config.useAngularBasedHttpClientInAlfrescoJs
? [{ provide: AlfrescoApiService, useClass: AlfrescoApiServiceWithAngularBasedHttpClient }]
: []
)
] ]
}; };
} }

View File

@@ -24,7 +24,6 @@ import { Router, ActivatedRoute, Params } from '@angular/router';
import { AuthenticationService } from '../../auth/services/authentication.service'; import { AuthenticationService } from '../../auth/services/authentication.service';
import { TranslationService } from '../../translation/translation.service'; import { TranslationService } from '../../translation/translation.service';
import { UserPreferencesService } from '../../common/services/user-preferences.service'; import { UserPreferencesService } from '../../common/services/user-preferences.service';
import { AlfrescoApiService } from '../../services/alfresco-api.service';
import { LoginErrorEvent } from '../models/login-error.event'; import { LoginErrorEvent } from '../models/login-error.event';
import { LoginSubmitEvent } from '../models/login-submit.event'; import { LoginSubmitEvent } from '../models/login-submit.event';
@@ -136,8 +135,7 @@ export class LoginComponent implements OnInit, OnDestroy {
private appConfig: AppConfigService, private appConfig: AppConfigService,
private userPreferences: UserPreferencesService, private userPreferences: UserPreferencesService,
private route: ActivatedRoute, private route: ActivatedRoute,
private sanitizer: DomSanitizer, private sanitizer: DomSanitizer
private alfrescoApiService: AlfrescoApiService
) { ) {
} }
@@ -188,7 +186,7 @@ export class LoginComponent implements OnInit, OnDestroy {
} }
redirectToImplicitLogin() { redirectToImplicitLogin() {
this.alfrescoApiService.getInstance().oauth2Auth.implicitLogin(); this.authService.ssoImplicitLogin();
} }
/** /**

View File

@@ -12,6 +12,6 @@
} }
}, },
"exclude": ["src/test.ts", "**/*.spec.ts", "**/*.test.ts"], "exclude": ["./test.ts", "**/*.spec.ts", "**/*.test.ts"],
"include": ["**/*.ts"] "include": ["**/*.ts"]
} }

View File

@@ -3,6 +3,6 @@
"compilerOptions": { "compilerOptions": {
"outDir": "../../dist/out-tsc" "outDir": "../../dist/out-tsc"
}, },
"files": ["src/test.ts"], "files": ["./test.ts"],
"include": ["**/*.spec.ts", "**/*.test.ts", "**/*.d.ts"] "include": ["**/*.spec.ts", "**/*.test.ts", "**/*.d.ts"]
} }

View File

@@ -24,20 +24,15 @@ import { fakeApplicationInstance, fakeApplicationInstanceWithEnvironment } from
import { ProcessServiceCloudTestingModule } from '../../testing/process-service-cloud.testing.module'; import { ProcessServiceCloudTestingModule } from '../../testing/process-service-cloud.testing.module';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { fakeEnvironmentList } from '../../common/mock/environment.mock'; import { fakeEnvironmentList } from '../../common/mock/environment.mock';
import { AdfHttpClient } from '@alfresco/adf-core/api';
describe('AppsProcessCloudService', () => { describe('AppsProcessCloudService', () => {
let service: AppsProcessCloudService; let service: AppsProcessCloudService;
let appConfigService: AppConfigService; let appConfigService: AppConfigService;
let apiService: AlfrescoApiService; let adfHttpClient: AdfHttpClient;
const apiMock: any = { const apiMockResponse: any = Promise.resolve({list : { entries: [ {entry: fakeApplicationInstance[0]}, {entry: fakeApplicationInstance[1]}] }});
oauth2Auth: {
callCustomApi: () => Promise.resolve({list : { entries: [ {entry: fakeApplicationInstance[0]}, {entry: fakeApplicationInstance[1]}] }})
},
isEcmLoggedIn: () => false,
reply: jasmine.createSpy('reply')
};
setupTestBed({ setupTestBed({
imports: [ imports: [
@@ -52,8 +47,8 @@ describe('AppsProcessCloudService', () => {
}); });
beforeEach(() => { beforeEach(() => {
apiService = TestBed.inject(AlfrescoApiService); adfHttpClient = TestBed.inject(AdfHttpClient);
spyOn(apiService, 'getInstance').and.returnValue(apiMock); spyOn(adfHttpClient, 'request').and.returnValue(apiMockResponse);
service = TestBed.inject(AppsProcessCloudService); service = TestBed.inject(AppsProcessCloudService);
appConfigService = TestBed.inject(AppConfigService); appConfigService = TestBed.inject(AppConfigService);

View File

@@ -18,10 +18,11 @@
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { Observable, from, throwError, of } from 'rxjs'; import { Observable, from, throwError, of } from 'rxjs';
import { map, catchError } from 'rxjs/operators'; import { map, catchError } from 'rxjs/operators';
import { AlfrescoApiService, AppConfigService, LogService } from '@alfresco/adf-core'; import { AppConfigService, LogService } from '@alfresco/adf-core';
import { Oauth2Auth } from '@alfresco/js-api';
import { ApplicationInstanceModel } from '../models/application-instance.model'; import { ApplicationInstanceModel } from '../models/application-instance.model';
import { Environment } from '../../common/interface/environment.interface'; import { Environment } from '../../common/interface/environment.interface';
import { AdfHttpClient } from '@alfresco/adf-core/api';
import { RequestOptions } from '@alfresco/js-api';
@Injectable({ providedIn: 'root' }) @Injectable({ providedIn: 'root' })
export class AppsProcessCloudService { export class AppsProcessCloudService {
@@ -29,7 +30,7 @@ export class AppsProcessCloudService {
deployedApps: ApplicationInstanceModel[]; deployedApps: ApplicationInstanceModel[];
constructor( constructor(
private apiService: AlfrescoApiService, private adfHttpClient: AdfHttpClient,
private logService: LogService, private logService: LogService,
private appConfigService: AppConfigService) { private appConfigService: AppConfigService) {
this.loadApps(); this.loadApps();
@@ -73,18 +74,28 @@ export class AppsProcessCloudService {
if (status === '') { if (status === '') {
return of([]); return of([]);
} }
const api: Oauth2Auth = this.apiService.getInstance().oauth2Auth;
const path = this.getApplicationUrl(); const path = this.getApplicationUrl();
const pathParams = {}; const pathParams = {};
const queryParams = { status, roles : role, sort: 'name' }; const queryParams = { status, roles : role, sort: 'name' };
const httpMethod = 'GET';
const headerParams = {}; const headerParams = {};
const formParams = {}; const formParams = {};
const bodyParam = {}; const bodyParam = {};
const contentTypes = ['application/json']; const contentTypes = ['application/json'];
const accepts = ['application/json']; const accepts = ['application/json'];
const requestOptions: RequestOptions = {
path,
pathParams,
queryParams,
headerParams,
formParams,
bodyParam,
contentTypes,
accepts,
httpMethod
};
return from(api.callCustomApi(path, 'GET', pathParams, queryParams, headerParams, formParams, bodyParam, return from(this.adfHttpClient.request(path, requestOptions))
contentTypes, accepts))
.pipe( .pipe(
map((applications: any) => applications.list.entries.map((application) => application.entry)), map((applications: any) => applications.list.entries.map((application) => application.entry)),
catchError((err) => this.handleError(err)) catchError((err) => this.handleError(err))

View File

@@ -17,24 +17,24 @@
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import { FormCloudService } from './form-cloud.service'; import { FormCloudService } from './form-cloud.service';
import { AlfrescoApiService, setupTestBed } from '@alfresco/adf-core'; import { setupTestBed } from '@alfresco/adf-core';
import { of } from 'rxjs'; import { of } from 'rxjs';
import { ProcessServiceCloudTestingModule } from '../../testing/process-service-cloud.testing.module'; import { ProcessServiceCloudTestingModule } from '../../testing/process-service-cloud.testing.module';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { AdfHttpClient } from '@alfresco/adf-core/api';
declare let jasmine: any; const mockTaskResponseBody = {
const responseBody = {
entry: entry:
{ id: 'id', name: 'name', formKey: 'form-key' } { id: 'id', name: 'name', formKey: 'form-key' }
}; };
const oauth2Auth = jasmine.createSpyObj('oauth2Auth', ['callCustomApi']); const mockFormResponseBody = { formRepresentation: { id: 'form-id', name: 'task-form', taskId: 'task-id' } };
describe('Form Cloud service', () => { describe('Form Cloud service', () => {
let service: FormCloudService; let service: FormCloudService;
let apiService: AlfrescoApiService; let adfHttpClient: AdfHttpClient;
let requestSpy: jasmine.Spy;
const appName = 'app-name'; const appName = 'app-name';
const taskId = 'task-id'; const taskId = 'task-id';
const processInstanceId = 'process-instance-id'; const processInstanceId = 'process-instance-id';
@@ -48,26 +48,21 @@ describe('Form Cloud service', () => {
beforeEach(() => { beforeEach(() => {
service = TestBed.inject(FormCloudService); service = TestBed.inject(FormCloudService);
apiService = TestBed.inject(AlfrescoApiService); adfHttpClient = TestBed.inject(AdfHttpClient);
requestSpy = spyOn(adfHttpClient, 'request');
spyOn(apiService, 'getInstance').and.returnValue({
oauth2Auth,
isEcmLoggedIn: () => false,
reply: jasmine.createSpy('reply')
} as any);
}); });
describe('Form tests', () => { describe('Form tests', () => {
it('should fetch and parse form', (done) => { it('should fetch and parse form', (done) => {
const formId = 'form-id'; const formId = 'form-id';
oauth2Auth.callCustomApi.and.returnValue(Promise.resolve({ formRepresentation: { id: formId, name: 'task-form', taskId: 'task-id' } })); requestSpy.and.returnValue(Promise.resolve(mockFormResponseBody));
service.getForm(appName, formId).subscribe((result) => { service.getForm(appName, formId).subscribe((result) => {
expect(result).toBeDefined(); expect(result).toBeDefined();
expect(result.formRepresentation.id).toBe(formId); expect(result.formRepresentation.id).toBe(formId);
expect(result.formRepresentation.name).toBe('task-form'); expect(result.formRepresentation.name).toBe('task-form');
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[0].endsWith(`${appName}/form/v1/forms/${formId}`)).toBeTruthy(); expect(requestSpy.calls.mostRecent().args[0]).toContain(`${appName}/form/v1/forms/${formId}`);
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[1]).toBe('GET'); expect(requestSpy.calls.mostRecent().args[1].httpMethod).toBe('GET');
done(); done();
}); });
}); });
@@ -85,21 +80,21 @@ describe('Form Cloud service', () => {
describe('Task tests', () => { describe('Task tests', () => {
it('should fetch and parse task', (done) => { it('should fetch and parse task', (done) => {
oauth2Auth.callCustomApi.and.returnValue(Promise.resolve(responseBody)); requestSpy.and.returnValue(Promise.resolve(mockTaskResponseBody));
service.getTask(appName, taskId).subscribe((result) => { service.getTask(appName, taskId).subscribe((result) => {
expect(result).toBeDefined(); expect(result).toBeDefined();
expect(result.id).toBe(responseBody.entry.id); expect(result.id).toBe('id');
expect(result.name).toBe(responseBody.entry.name); expect(result.name).toBe('name');
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[0].endsWith(`${appName}/query/v1/tasks/${taskId}`)).toBeTruthy(); expect(requestSpy.calls.mostRecent().args[0]).toContain(`${appName}/query/v1/tasks/${taskId}`);
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[1]).toBe('GET'); expect(requestSpy.calls.mostRecent().args[1].httpMethod).toBe('GET');
done(); done();
}); });
}); });
it('should fetch task variables', (done) => { it('should fetch task variables', (done) => {
oauth2Auth.callCustomApi.and.returnValue(Promise.resolve({ requestSpy.and.returnValue(Promise.resolve({
list: { list: {
entries: [ entries: [
{ {
@@ -139,14 +134,14 @@ describe('Form Cloud service', () => {
expect(result.length).toBe(1); expect(result.length).toBe(1);
expect(result[0].name).toBe('fakeProperty'); expect(result[0].name).toBe('fakeProperty');
expect(result[0].value).toBe('fakeValue'); expect(result[0].value).toBe('fakeValue');
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[0].endsWith(`${appName}/query/v1/tasks/${taskId}/variables`)).toBeTruthy(); expect(requestSpy.calls.mostRecent().args[0]).toContain(`${appName}/query/v1/tasks/${taskId}/variables`);
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[1]).toBe('GET'); expect(requestSpy.calls.mostRecent().args[1].httpMethod).toBe('GET');
done(); done();
}); });
}); });
it('should fetch result if the variable value is 0', (done) => { it('should fetch result if the variable value is 0', (done) => {
oauth2Auth.callCustomApi.and.returnValue(Promise.resolve({ requestSpy.and.returnValue(Promise.resolve({
list: { list: {
entries: [ entries: [
{ {
@@ -191,7 +186,7 @@ describe('Form Cloud service', () => {
}); });
it('should fetch task form flattened', (done) => { it('should fetch task form flattened', (done) => {
spyOn(service, 'getTask').and.returnValue(of(responseBody.entry)); spyOn(service, 'getTask').and.returnValue(of(mockTaskResponseBody.entry));
spyOn(service, 'getForm').and.returnValue(of({ spyOn(service, 'getForm').and.returnValue(of({
formRepresentation: { formRepresentation: {
name: 'task-form', name: 'task-form',
@@ -202,38 +197,38 @@ describe('Form Cloud service', () => {
service.getTaskForm(appName, taskId).subscribe((result) => { service.getTaskForm(appName, taskId).subscribe((result) => {
expect(result).toBeDefined(); expect(result).toBeDefined();
expect(result.name).toBe('task-form'); expect(result.name).toBe('task-form');
expect(result.taskId).toBe(responseBody.entry.id); expect(result.taskId).toBe('id');
expect(result.taskName).toBe(responseBody.entry.name); expect(result.taskName).toBe('name');
done(); done();
}); });
}); });
it('should save task form', (done) => { it('should save task form', (done) => {
oauth2Auth.callCustomApi.and.returnValue(Promise.resolve(responseBody)); requestSpy.and.returnValue(Promise.resolve(mockTaskResponseBody));
const formId = 'form-id'; const formId = 'form-id';
service.saveTaskForm(appName, taskId, processInstanceId, formId, {}).subscribe((result: any) => { service.saveTaskForm(appName, taskId, processInstanceId, formId, {}).subscribe((result: any) => {
expect(result).toBeDefined(); expect(result).toBeDefined();
expect(result.id).toBe('id'); expect(result.id).toBe('id');
expect(result.name).toBe('name'); expect(result.name).toBe('name');
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[0].endsWith(`${appName}/form/v1/forms/${formId}/save`)).toBeTruthy(); expect(requestSpy.calls.mostRecent().args[0]).toContain(`${appName}/form/v1/forms/${formId}/save`);
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[1]).toBe('POST'); expect(requestSpy.calls.mostRecent().args[1].httpMethod).toBe('POST');
done(); done();
}); });
}); });
it('should complete task form', (done) => { it('should complete task form', (done) => {
oauth2Auth.callCustomApi.and.returnValue(Promise.resolve(responseBody)); requestSpy.and.returnValue(Promise.resolve(mockTaskResponseBody));
const formId = 'form-id'; const formId = 'form-id';
service.completeTaskForm(appName, taskId, processInstanceId, formId, {}, '', 1).subscribe((result: any) => { service.completeTaskForm(appName, taskId, processInstanceId, formId, {}, '', 1).subscribe((result: any) => {
expect(result).toBeDefined(); expect(result).toBeDefined();
expect(result.id).toBe('id'); expect(result.id).toBe('id');
expect(result.name).toBe('name'); expect(result.name).toBe('name');
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[0].endsWith(`${appName}/form/v1/forms/${formId}/submit/versions/1`)).toBeTruthy(); expect(requestSpy.calls.mostRecent().args[0]).toContain(`${appName}/form/v1/forms/${formId}/submit/versions/1`);
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[1]).toBe('POST'); expect(requestSpy.calls.mostRecent().args[1].httpMethod).toBe('POST');
done(); done();
}); });
}); });

View File

@@ -25,6 +25,7 @@ import { TaskVariableCloud } from '../models/task-variable-cloud.model';
import { BaseCloudService } from '../../services/base-cloud.service'; import { BaseCloudService } from '../../services/base-cloud.service';
import { FormContent } from '../../services/form-fields.interfaces'; import { FormContent } from '../../services/form-fields.interfaces';
import { FormCloudServiceInterface } from './form-cloud.service.interface'; import { FormCloudServiceInterface } from './form-cloud.service.interface';
import { AdfHttpClient } from '@alfresco/adf-core/api';
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
@@ -37,8 +38,10 @@ export class FormCloudService extends BaseCloudService implements FormCloudServi
return this._uploadApi; return this._uploadApi;
} }
constructor() { constructor(
super(); adfHttpClient: AdfHttpClient
) {
super(adfHttpClient);
} }
/** /**

View File

@@ -16,20 +16,17 @@
*/ */
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import { AlfrescoApiService, setupTestBed } from '@alfresco/adf-core'; import { setupTestBed } from '@alfresco/adf-core';
import { FormDefinitionSelectorCloudService } from './form-definition-selector-cloud.service'; import { FormDefinitionSelectorCloudService } from './form-definition-selector-cloud.service';
import { ProcessServiceCloudTestingModule } from '../../testing/process-service-cloud.testing.module'; import { ProcessServiceCloudTestingModule } from '../../testing/process-service-cloud.testing.module';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { mockFormRepresentations } from '../mocks/form-representation.mock'; import { mockFormRepresentations } from '../mocks/form-representation.mock';
import { AdfHttpClient } from '@alfresco/adf-core/api';
declare let jasmine: any;
const oauth2Auth = jasmine.createSpyObj('oauth2Auth', ['callCustomApi', 'on']);
describe('Form Definition Selector Cloud Service', () => { describe('Form Definition Selector Cloud Service', () => {
let service: FormDefinitionSelectorCloudService; let service: FormDefinitionSelectorCloudService;
let apiService: AlfrescoApiService; let adfHttpClient: AdfHttpClient;
const appName = 'app-name'; const appName = 'app-name';
setupTestBed({ setupTestBed({
@@ -41,17 +38,11 @@ describe('Form Definition Selector Cloud Service', () => {
beforeEach(() => { beforeEach(() => {
service = TestBed.inject(FormDefinitionSelectorCloudService); service = TestBed.inject(FormDefinitionSelectorCloudService);
apiService = TestBed.inject(AlfrescoApiService); adfHttpClient = TestBed.inject(AdfHttpClient);
spyOn(apiService, 'getInstance').and.returnValue({ spyOn(adfHttpClient, 'request').and.returnValue(Promise.resolve(mockFormRepresentations));
oauth2Auth,
isEcmLoggedIn: () => false,
reply: jasmine.createSpy('reply')
} as any);
}); });
it('should fetch all the forms when getForms is called', (done) => { it('should fetch all the forms when getForms is called', (done) => {
oauth2Auth.callCustomApi.and.returnValue(Promise.resolve(mockFormRepresentations));
service.getForms(appName).subscribe((result) => { service.getForms(appName).subscribe((result) => {
expect(result).toBeDefined(); expect(result).toBeDefined();
expect(result.length).toBe(3); expect(result.length).toBe(3);
@@ -60,8 +51,6 @@ describe('Form Definition Selector Cloud Service', () => {
}); });
it('should fetch only standalone enabled forms when getStandaloneTaskForms is called', (done) => { it('should fetch only standalone enabled forms when getStandaloneTaskForms is called', (done) => {
oauth2Auth.callCustomApi.and.returnValue(Promise.resolve(mockFormRepresentations));
service.getStandAloneTaskForms(appName).subscribe((result) => { service.getStandAloneTaskForms(appName).subscribe((result) => {
expect(result).toBeDefined(); expect(result).toBeDefined();
expect(result.length).toBe(2); expect(result.length).toBe(2);

View File

@@ -16,8 +16,6 @@
*/ */
import { HttpErrorResponse } from '@angular/common/http'; import { HttpErrorResponse } from '@angular/common/http';
import { throwError } from 'rxjs';
import { IdentityGroupModel } from '../models/identity-group.model';
import { IdentityGroupFilterInterface } from '../services/identity-group-filter.interface'; import { IdentityGroupFilterInterface } from '../services/identity-group-filter.interface';
export const mockSearchGroupByRoles: IdentityGroupFilterInterface = { export const mockSearchGroupByRoles: IdentityGroupFilterInterface = {
@@ -35,23 +33,7 @@ export const mockSearchGroupByApp: IdentityGroupFilterInterface = {
withinApplication: 'fake-app-name' withinApplication: 'fake-app-name'
}; };
export function oAuthMockApiWithIdentityGroups(groups: IdentityGroupModel[]) { export const mockHttpErrorResponse = new HttpErrorResponse({
return {
oauth2Auth: {
callCustomApi: () => Promise.resolve(groups)
},
reply: jasmine.createSpy('reply')
};
}
const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404, statusText: 'Not Found'
}); });
export const oAuthMockApiWithError = {
oauth2Auth: {
callCustomApi: () => throwError(errorResponse)
},
reply: jasmine.createSpy('reply')
};

View File

@@ -17,22 +17,23 @@
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { AlfrescoApiService, setupTestBed } from '@alfresco/adf-core'; import { setupTestBed } from '@alfresco/adf-core';
import { ProcessServiceCloudTestingModule } from '../../testing/process-service-cloud.testing.module'; import { ProcessServiceCloudTestingModule } from '../../testing/process-service-cloud.testing.module';
import { IdentityGroupService } from './identity-group.service'; import { IdentityGroupService } from './identity-group.service';
import { import {
mockHttpErrorResponse,
mockSearchGroupByApp, mockSearchGroupByApp,
mockSearchGroupByRoles, mockSearchGroupByRoles,
mockSearchGroupByRolesAndApp, mockSearchGroupByRolesAndApp
oAuthMockApiWithError,
oAuthMockApiWithIdentityGroups
} from '../mock/identity-group.service.mock'; } from '../mock/identity-group.service.mock';
import { mockFoodGroups } from '../mock/group-cloud.mock'; import { mockFoodGroups } from '../mock/group-cloud.mock';
import { AdfHttpClient } from '@alfresco/adf-core/api';
describe('IdentityGroupService', () => { describe('IdentityGroupService', () => {
let service: IdentityGroupService; let service: IdentityGroupService;
let alfrescoApiService: AlfrescoApiService; let adfHttpClient: AdfHttpClient;
let requestSpy: jasmine.Spy;
setupTestBed({ setupTestBed({
imports: [ imports: [
@@ -43,13 +44,14 @@ describe('IdentityGroupService', () => {
beforeEach(() => { beforeEach(() => {
service = TestBed.inject(IdentityGroupService); service = TestBed.inject(IdentityGroupService);
alfrescoApiService = TestBed.inject(AlfrescoApiService); adfHttpClient = TestBed.inject(AdfHttpClient);
requestSpy = spyOn(adfHttpClient, 'request');
}); });
describe('Search', () => { describe('Search', () => {
it('should fetch groups', (done) => { it('should fetch groups', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithIdentityGroups(mockFoodGroups )as any); requestSpy.and.returnValue(Promise.resolve(mockFoodGroups));
const searchSpy = spyOn(service, 'search').and.callThrough(); const searchSpy = spyOn(service, 'search').and.callThrough();
service.search('fake').subscribe( service.search('fake').subscribe(
@@ -65,7 +67,7 @@ describe('IdentityGroupService', () => {
}); });
it('should not fetch groups if error occurred', (done) => { it('should not fetch groups if error occurred', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithError as any); requestSpy.and.returnValue(Promise.reject(mockHttpErrorResponse));
const searchSpy = spyOn(service, 'search').and.callThrough(); const searchSpy = spyOn(service, 'search').and.callThrough();
@@ -85,7 +87,7 @@ describe('IdentityGroupService', () => {
}); });
it('should fetch groups by roles', (done) => { it('should fetch groups by roles', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithIdentityGroups(mockFoodGroups) as any); requestSpy.and.returnValue(Promise.resolve(mockFoodGroups));
const searchSpy = spyOn(service, 'search').and.callThrough(); const searchSpy = spyOn(service, 'search').and.callThrough();
service.search('fake', mockSearchGroupByRoles).subscribe( service.search('fake', mockSearchGroupByRoles).subscribe(
@@ -102,7 +104,7 @@ describe('IdentityGroupService', () => {
}); });
it('should not fetch groups by roles if error occurred', (done) => { it('should not fetch groups by roles if error occurred', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithError as any); requestSpy.and.returnValue(Promise.reject(mockHttpErrorResponse));
const searchSpy = spyOn(service, 'search').and.callThrough(); const searchSpy = spyOn(service, 'search').and.callThrough();
service.search('fake', mockSearchGroupByRoles) service.search('fake', mockSearchGroupByRoles)
@@ -125,7 +127,7 @@ describe('IdentityGroupService', () => {
}); });
it('should fetch groups within app', (done) => { it('should fetch groups within app', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithIdentityGroups(mockFoodGroups) as any); requestSpy.and.returnValue(Promise.resolve(mockFoodGroups));
service.search('fake', mockSearchGroupByApp).subscribe( service.search('fake', mockSearchGroupByApp).subscribe(
res => { res => {
@@ -140,7 +142,7 @@ describe('IdentityGroupService', () => {
}); });
it('should fetch groups within app with roles', (done) => { it('should fetch groups within app with roles', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithIdentityGroups(mockFoodGroups) as any); requestSpy.and.returnValue(Promise.resolve(mockFoodGroups));
service.search('fake', mockSearchGroupByRolesAndApp).subscribe( service.search('fake', mockSearchGroupByRolesAndApp).subscribe(
res => { res => {
@@ -156,7 +158,7 @@ describe('IdentityGroupService', () => {
}); });
it('should not fetch groups within app if error occurred', (done) => { it('should not fetch groups within app if error occurred', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithError as any); requestSpy.and.returnValue(Promise.reject(mockHttpErrorResponse));
const searchSpy = spyOn(service, 'search').and.callThrough(); const searchSpy = spyOn(service, 'search').and.callThrough();
service.search('fake', mockSearchGroupByApp) service.search('fake', mockSearchGroupByApp)

View File

@@ -16,8 +16,6 @@
*/ */
import { HttpErrorResponse } from '@angular/common/http'; import { HttpErrorResponse } from '@angular/common/http';
import { throwError } from 'rxjs';
import { IdentityUserModel } from '../models/identity-user.model';
import { IdentityUserFilterInterface } from '../services/identity-user-filter.interface'; import { IdentityUserFilterInterface } from '../services/identity-user-filter.interface';
export const mockSearchUserEmptyFilters: IdentityUserFilterInterface = { export const mockSearchUserEmptyFilters: IdentityUserFilterInterface = {
@@ -68,23 +66,7 @@ export const mockSearchUserByAppAndGroups: IdentityUserFilterInterface = {
withinApplication: 'fake-app-name' withinApplication: 'fake-app-name'
}; };
export function oAuthMockApiWithIdentityUsers(users: IdentityUserModel[]) { export const mockHttpErrorResponse = new HttpErrorResponse({
return {
oauth2Auth: {
callCustomApi: () => Promise.resolve(users)
},
reply: jasmine.createSpy('reply')
} as any;
}
const errorResponse = new HttpErrorResponse({
error: 'Mock Error', error: 'Mock Error',
status: 404, statusText: 'Not Found' status: 404, statusText: 'Not Found'
}); });
export const oAuthMockApiWithError = {
oauth2Auth: {
callCustomApi: () => throwError(errorResponse)
},
reply: jasmine.createSpy('reply')
} as any;

View File

@@ -17,7 +17,7 @@
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { AlfrescoApiService, JwtHelperService, setupTestBed } from '@alfresco/adf-core'; import { JwtHelperService, setupTestBed } from '@alfresco/adf-core';
import { IdentityUserService } from './identity-user.service'; import { IdentityUserService } from './identity-user.service';
import { mockToken } from '../mock/jwt-helper.service.spec'; import { mockToken } from '../mock/jwt-helper.service.spec';
import { ProcessServiceCloudTestingModule } from '../../testing/process-service-cloud.testing.module'; import { ProcessServiceCloudTestingModule } from '../../testing/process-service-cloud.testing.module';
@@ -28,16 +28,17 @@ import {
mockSearchUserByGroupsAndRoles, mockSearchUserByGroupsAndRoles,
mockSearchUserByGroupsAndRolesAndApp, mockSearchUserByGroupsAndRolesAndApp,
mockSearchUserByRoles, mockSearchUserByRoles,
mockSearchUserByRolesAndApp, mockSearchUserByRolesAndApp
oAuthMockApiWithError,
oAuthMockApiWithIdentityUsers
} from '../mock/identity-user.service.mock'; } from '../mock/identity-user.service.mock';
import { mockFoodUsers } from '../mock/people-cloud.mock'; import { mockFoodUsers } from '../mock/people-cloud.mock';
import { AdfHttpClient } from '@alfresco/adf-core/api';
import { mockHttpErrorResponse } from '../../group/mock/identity-group.service.mock';
describe('IdentityUserService', () => { describe('IdentityUserService', () => {
let service: IdentityUserService; let service: IdentityUserService;
let alfrescoApiService: AlfrescoApiService; let adfHttpClient: AdfHttpClient;
let requestSpy: jasmine.Spy;
setupTestBed({ setupTestBed({
imports: [ imports: [
@@ -48,7 +49,8 @@ describe('IdentityUserService', () => {
beforeEach(() => { beforeEach(() => {
service = TestBed.inject(IdentityUserService); service = TestBed.inject(IdentityUserService);
alfrescoApiService = TestBed.inject(AlfrescoApiService); adfHttpClient = TestBed.inject(AdfHttpClient);
requestSpy = spyOn(adfHttpClient, 'request');
}); });
describe('Current user info (JWT token)', () => { describe('Current user info (JWT token)', () => {
@@ -85,7 +87,7 @@ describe('IdentityUserService', () => {
describe('Search', () => { describe('Search', () => {
it('should fetch users', (done) => { it('should fetch users', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithIdentityUsers(mockFoodUsers)); requestSpy.and.returnValue(Promise.resolve(mockFoodUsers));
const searchSpy = spyOn(service, 'search').and.callThrough(); const searchSpy = spyOn(service, 'search').and.callThrough();
service.search('fake').subscribe( service.search('fake').subscribe(
@@ -101,7 +103,7 @@ describe('IdentityUserService', () => {
}); });
it('should not fetch users if error occurred', (done) => { it('should not fetch users if error occurred', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithError as any); requestSpy.and.returnValue(Promise.reject(mockHttpErrorResponse));
const searchSpy = spyOn(service, 'search').and.callThrough(); const searchSpy = spyOn(service, 'search').and.callThrough();
@@ -121,7 +123,7 @@ describe('IdentityUserService', () => {
}); });
it('should fetch users by roles', (done) => { it('should fetch users by roles', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithIdentityUsers(mockFoodUsers)); requestSpy.and.returnValue(Promise.resolve(mockFoodUsers));
const searchSpy = spyOn(service, 'search').and.callThrough(); const searchSpy = spyOn(service, 'search').and.callThrough();
service.search('fake', mockSearchUserByRoles).subscribe( service.search('fake', mockSearchUserByRoles).subscribe(
@@ -138,7 +140,7 @@ describe('IdentityUserService', () => {
}); });
it('should not fetch users by roles if error occurred', (done) => { it('should not fetch users by roles if error occurred', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithError); requestSpy.and.returnValue(Promise.reject(mockHttpErrorResponse));
service.search('fake', mockSearchUserByRoles) service.search('fake', mockSearchUserByRoles)
.subscribe( .subscribe(
@@ -155,7 +157,7 @@ describe('IdentityUserService', () => {
}); });
it('should fetch users by groups', (done) => { it('should fetch users by groups', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithIdentityUsers(mockFoodUsers)); requestSpy.and.returnValue(Promise.resolve(mockFoodUsers));
const searchSpy = spyOn(service, 'search').and.callThrough(); const searchSpy = spyOn(service, 'search').and.callThrough();
service.search('fake', mockSearchUserByGroups).subscribe( service.search('fake', mockSearchUserByGroups).subscribe(
@@ -172,7 +174,7 @@ describe('IdentityUserService', () => {
}); });
it('should fetch users by roles with groups', (done) => { it('should fetch users by roles with groups', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithIdentityUsers(mockFoodUsers)); requestSpy.and.returnValue(Promise.resolve(mockFoodUsers));
const searchSpy = spyOn(service, 'search').and.callThrough(); const searchSpy = spyOn(service, 'search').and.callThrough();
service.search('fake', mockSearchUserByGroupsAndRoles).subscribe( service.search('fake', mockSearchUserByGroupsAndRoles).subscribe(
@@ -190,7 +192,7 @@ describe('IdentityUserService', () => {
}); });
it('should fetch users by roles with groups and appName', (done) => { it('should fetch users by roles with groups and appName', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithIdentityUsers(mockFoodUsers)); requestSpy.and.returnValue(Promise.resolve(mockFoodUsers));
const searchSpy = spyOn(service, 'search').and.callThrough(); const searchSpy = spyOn(service, 'search').and.callThrough();
service.search('fake', mockSearchUserByGroupsAndRolesAndApp).subscribe( service.search('fake', mockSearchUserByGroupsAndRolesAndApp).subscribe(
@@ -209,7 +211,7 @@ describe('IdentityUserService', () => {
}); });
it('should not fetch users by groups if error occurred', (done) => { it('should not fetch users by groups if error occurred', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithError); requestSpy.and.returnValue(Promise.reject(mockHttpErrorResponse));
service.search('fake', mockSearchUserByGroups) service.search('fake', mockSearchUserByGroups)
.subscribe( .subscribe(
@@ -226,7 +228,7 @@ describe('IdentityUserService', () => {
}); });
it('should fetch users within app', (done) => { it('should fetch users within app', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithIdentityUsers(mockFoodUsers)); requestSpy.and.returnValue(Promise.resolve(mockFoodUsers));
service.search('fake', mockSearchUserByApp).subscribe( service.search('fake', mockSearchUserByApp).subscribe(
res => { res => {
@@ -241,7 +243,7 @@ describe('IdentityUserService', () => {
}); });
it('should fetch users within app with roles', (done) => { it('should fetch users within app with roles', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithIdentityUsers(mockFoodUsers)); requestSpy.and.returnValue(Promise.resolve(mockFoodUsers));
service.search('fake', mockSearchUserByRolesAndApp).subscribe( service.search('fake', mockSearchUserByRolesAndApp).subscribe(
res => { res => {
@@ -257,7 +259,7 @@ describe('IdentityUserService', () => {
}); });
it('should fetch users within app with groups', (done) => { it('should fetch users within app with groups', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithIdentityUsers(mockFoodUsers)); requestSpy.and.returnValue(Promise.resolve(mockFoodUsers));
const searchSpy = spyOn(service, 'search').and.callThrough(); const searchSpy = spyOn(service, 'search').and.callThrough();
service.search('fake', mockSearchUserByAppAndGroups).subscribe( service.search('fake', mockSearchUserByAppAndGroups).subscribe(
@@ -275,7 +277,7 @@ describe('IdentityUserService', () => {
}); });
it('should not fetch users within app if error occurred', (done) => { it('should not fetch users within app if error occurred', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithError); requestSpy.and.returnValue(Promise.reject(mockHttpErrorResponse));
service.search('fake', mockSearchUserByApp) service.search('fake', mockSearchUserByApp)
.subscribe( .subscribe(

View File

@@ -16,42 +16,24 @@
*/ */
import { fakeAsync, TestBed } from '@angular/core/testing'; import { fakeAsync, TestBed } from '@angular/core/testing';
import { setupTestBed, AlfrescoApiService } from '@alfresco/adf-core'; import { setupTestBed } from '@alfresco/adf-core';
import { ProcessListCloudService } from './process-list-cloud.service'; import { ProcessListCloudService } from './process-list-cloud.service';
import { ProcessQueryCloudRequestModel } from '../models/process-cloud-query-request.model'; import { ProcessQueryCloudRequestModel } from '../models/process-cloud-query-request.model';
import { ProcessServiceCloudTestingModule } from '../../../testing/process-service-cloud.testing.module'; import { ProcessServiceCloudTestingModule } from '../../../testing/process-service-cloud.testing.module';
import { AdfHttpClient } from '@alfresco/adf-core/api';
describe('ProcessListCloudService', () => { describe('ProcessListCloudService', () => {
let service: ProcessListCloudService; let service: ProcessListCloudService;
let alfrescoApiService: AlfrescoApiService; let adfHttpClient: AdfHttpClient;
let requestSpy: jasmine.Spy;
const returnCallQueryParameters = (): any => ({ const returnCallQueryParameters = (_queryUrl, options) => Promise.resolve(options.queryParams);
oauth2Auth: {
callCustomApi: (_queryUrl, _operation, _context, queryParams) => Promise.resolve(queryParams)
},
isEcmLoggedIn: () => false
});
const returnCallUrl = (): any => ({ const returnCallUrl = (queryUrl) => Promise.resolve(queryUrl);
oauth2Auth: {
callCustomApi: (queryUrl) => Promise.resolve(queryUrl)
},
isEcmLoggedIn: () => false
});
const returnCallOperation = (): any => ({ const returnCallOperation = (_queryUrl, options) => Promise.resolve(options);
oauth2Auth: {
callCustomApi: (_queryUrl, operation, _context, _queryParams) => Promise.resolve(operation)
},
isEcmLoggedIn: () => false
});
const returnCallBody = (): any => ({ const returnCallBody = (_queryUrl, options) => Promise.resolve(options.bodyParam);
oauth2Auth: {
callCustomApi: (_queryUrl, _operation, _context, _queryParams, _headerParams, _formParams, bodyParam) => Promise.resolve(bodyParam)
},
isEcmLoggedIn: () => false
});
setupTestBed({ setupTestBed({
imports: [ imports: [
@@ -60,13 +42,14 @@ describe('ProcessListCloudService', () => {
}); });
beforeEach(fakeAsync(() => { beforeEach(fakeAsync(() => {
alfrescoApiService = TestBed.inject(AlfrescoApiService); adfHttpClient = TestBed.inject(AdfHttpClient);
service = TestBed.inject(ProcessListCloudService); service = TestBed.inject(ProcessListCloudService);
requestSpy = spyOn(adfHttpClient, 'request');
})); }));
it('should append to the call all the parameters', (done) => { it('should append to the call all the parameters', (done) => {
const processRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service' } as ProcessQueryCloudRequestModel; const processRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service' } as ProcessQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallQueryParameters); requestSpy.and.callFake(returnCallQueryParameters);
service.getProcessByRequest(processRequest).subscribe((res) => { service.getProcessByRequest(processRequest).subscribe((res) => {
expect(res).toBeDefined(); expect(res).toBeDefined();
expect(res).not.toBeNull(); expect(res).not.toBeNull();
@@ -79,7 +62,7 @@ describe('ProcessListCloudService', () => {
it('should concat the app name to the request url', (done) => { it('should concat the app name to the request url', (done) => {
const processRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service' } as ProcessQueryCloudRequestModel; const processRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service' } as ProcessQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallUrl); requestSpy.and.callFake(returnCallUrl);
service.getProcessByRequest(processRequest).subscribe((requestUrl) => { service.getProcessByRequest(processRequest).subscribe((requestUrl) => {
expect(requestUrl).toBeDefined(); expect(requestUrl).toBeDefined();
expect(requestUrl).not.toBeNull(); expect(requestUrl).not.toBeNull();
@@ -93,7 +76,7 @@ describe('ProcessListCloudService', () => {
appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service', appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service',
sorting: [{ orderBy: 'NAME', direction: 'DESC' }, { orderBy: 'TITLE', direction: 'ASC' }] sorting: [{ orderBy: 'NAME', direction: 'DESC' }, { orderBy: 'TITLE', direction: 'ASC' }]
} as ProcessQueryCloudRequestModel; } as ProcessQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallQueryParameters); requestSpy.and.callFake(returnCallQueryParameters);
service.getProcessByRequest(processRequest).subscribe((res) => { service.getProcessByRequest(processRequest).subscribe((res) => {
expect(res).toBeDefined(); expect(res).toBeDefined();
expect(res).not.toBeNull(); expect(res).not.toBeNull();
@@ -104,7 +87,7 @@ describe('ProcessListCloudService', () => {
it('should return an error when app name is not specified', (done) => { it('should return an error when app name is not specified', (done) => {
const processRequest = { appName: null } as ProcessQueryCloudRequestModel; const processRequest = { appName: null } as ProcessQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallUrl); requestSpy.and.callFake(returnCallUrl);
service.getProcessByRequest(processRequest).subscribe( service.getProcessByRequest(processRequest).subscribe(
() => { }, () => { },
(error) => { (error) => {
@@ -118,7 +101,7 @@ describe('ProcessListCloudService', () => {
it('should append to the call all the parameters', async () => { it('should append to the call all the parameters', async () => {
const processRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service' } as ProcessQueryCloudRequestModel; const processRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service' } as ProcessQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallQueryParameters); requestSpy.and.callFake(returnCallQueryParameters);
const request = await service.getAdminProcessByRequest(processRequest).toPromise(); const request = await service.getAdminProcessByRequest(processRequest).toPromise();
expect(request).toBeDefined(); expect(request).toBeDefined();
@@ -130,7 +113,7 @@ describe('ProcessListCloudService', () => {
it('should concat the app name to the request url', async () => { it('should concat the app name to the request url', async () => {
const processRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service' } as ProcessQueryCloudRequestModel; const processRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service' } as ProcessQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallUrl); requestSpy.and.callFake(returnCallUrl);
const requestUrl = await service.getAdminProcessByRequest(processRequest).toPromise(); const requestUrl = await service.getAdminProcessByRequest(processRequest).toPromise();
expect(requestUrl).toBeDefined(); expect(requestUrl).toBeDefined();
@@ -143,7 +126,7 @@ describe('ProcessListCloudService', () => {
appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service', appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service',
sorting: [{ orderBy: 'NAME', direction: 'DESC' }, { orderBy: 'TITLE', direction: 'ASC' }] sorting: [{ orderBy: 'NAME', direction: 'DESC' }, { orderBy: 'TITLE', direction: 'ASC' }]
} as ProcessQueryCloudRequestModel; } as ProcessQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallQueryParameters); requestSpy.and.callFake(returnCallQueryParameters);
const request = await service.getAdminProcessByRequest(processRequest).toPromise(); const request = await service.getAdminProcessByRequest(processRequest).toPromise();
expect(request).toBeDefined(); expect(request).toBeDefined();
@@ -153,7 +136,7 @@ describe('ProcessListCloudService', () => {
it('should return an error when app name is not specified', async () => { it('should return an error when app name is not specified', async () => {
const processRequest = { appName: null } as ProcessQueryCloudRequestModel; const processRequest = { appName: null } as ProcessQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallUrl); requestSpy.and.callFake(returnCallUrl);
try { try {
await service.getAdminProcessByRequest(processRequest).toPromise(); await service.getAdminProcessByRequest(processRequest).toPromise();
@@ -166,16 +149,16 @@ describe('ProcessListCloudService', () => {
it('should make post request', async () => { it('should make post request', async () => {
const processRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service' } as ProcessQueryCloudRequestModel; const processRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service' } as ProcessQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallOperation); requestSpy.and.callFake(returnCallOperation);
const requestMethod = await service.getAdminProcessByRequest(processRequest).toPromise(); const adminProcessResponse = await service.getAdminProcessByRequest(processRequest).toPromise();
expect(requestMethod).toBeDefined(); expect(adminProcessResponse).toBeDefined();
expect(requestMethod).not.toBeNull(); expect(adminProcessResponse).not.toBeNull();
expect(requestMethod).toBe('POST'); expect(adminProcessResponse.httpMethod).toBe('POST');
}); });
it('should not have variable keys as part of query parameters', async () => { it('should not have variable keys as part of query parameters', async () => {
const processRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service', variableKeys: ['test-one', 'test-two'] } as ProcessQueryCloudRequestModel; const processRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service', variableKeys: ['test-one', 'test-two'] } as ProcessQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallQueryParameters); requestSpy.and.callFake(returnCallQueryParameters);
const requestParams = await service.getAdminProcessByRequest(processRequest).toPromise(); const requestParams = await service.getAdminProcessByRequest(processRequest).toPromise();
expect(requestParams).toBeDefined(); expect(requestParams).toBeDefined();
@@ -185,7 +168,7 @@ describe('ProcessListCloudService', () => {
it('should send right variable keys as post body', async () => { it('should send right variable keys as post body', async () => {
const processRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service', variableKeys: ['test-one', 'test-two'] } as ProcessQueryCloudRequestModel; const processRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service', variableKeys: ['test-one', 'test-two'] } as ProcessQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallBody); requestSpy.and.callFake(returnCallBody);
const requestBodyParams = await service.getAdminProcessByRequest(processRequest).toPromise(); const requestBodyParams = await service.getAdminProcessByRequest(processRequest).toPromise();
expect(requestBodyParams).toBeDefined(); expect(requestBodyParams).toBeDefined();

View File

@@ -17,16 +17,17 @@
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import { of, throwError } from 'rxjs'; import { of, throwError } from 'rxjs';
import { setupTestBed, AlfrescoApiService } from '@alfresco/adf-core'; import { setupTestBed } from '@alfresco/adf-core';
import { StartProcessCloudService } from './start-process-cloud.service'; import { StartProcessCloudService } from './start-process-cloud.service';
import { fakeProcessPayload } from '../mock/start-process.component.mock'; import { fakeProcessPayload } from '../mock/start-process.component.mock';
import { ProcessDefinitionCloud } from '../../../models/process-definition-cloud.model'; import { ProcessDefinitionCloud } from '../../../models/process-definition-cloud.model';
import { HttpErrorResponse, HttpClientModule } from '@angular/common/http'; import { HttpErrorResponse, HttpClientModule } from '@angular/common/http';
import { AdfHttpClient } from '@alfresco/adf-core/api';
describe('StartProcessCloudService', () => { describe('StartProcessCloudService', () => {
let service: StartProcessCloudService; let service: StartProcessCloudService;
let alfrescoApiService: AlfrescoApiService; let adfHttpClient: AdfHttpClient;
setupTestBed({ setupTestBed({
imports: [HttpClientModule] imports: [HttpClientModule]
@@ -34,7 +35,7 @@ describe('StartProcessCloudService', () => {
beforeEach(() => { beforeEach(() => {
service = TestBed.inject(StartProcessCloudService); service = TestBed.inject(StartProcessCloudService);
alfrescoApiService = TestBed.inject(AlfrescoApiService); adfHttpClient = TestBed.inject(AdfHttpClient);
}); });
it('should be able to create a new process', (done) => { it('should be able to create a new process', (done) => {
@@ -105,11 +106,8 @@ describe('StartProcessCloudService', () => {
it('should transform the response into task variables', (done) => { it('should transform the response into task variables', (done) => {
const appName = 'test-app'; const appName = 'test-app';
const processDefinitionId = 'processDefinitionId'; const processDefinitionId = 'processDefinitionId';
const oauth2Auth = jasmine.createSpyObj('oauth2Auth', ['callCustomApi']); const requestSpy = spyOn(adfHttpClient, 'request');
oauth2Auth.callCustomApi.and.returnValue(Promise.resolve({ static1: 'value', static2: 0, static3: true })); requestSpy.and.returnValue(Promise.resolve({ static1: 'value', static2: 0, static3: true }));
spyOn(alfrescoApiService, 'getInstance').and.returnValue({
oauth2Auth
} as any);
service.getStartEventFormStaticValuesMapping(appName, processDefinitionId).subscribe((result) => { service.getStartEventFormStaticValuesMapping(appName, processDefinitionId).subscribe((result) => {
expect(result.length).toEqual(3); expect(result.length).toEqual(3);
@@ -122,8 +120,8 @@ describe('StartProcessCloudService', () => {
expect(result[2].name).toEqual('static3'); expect(result[2].name).toEqual('static3');
expect(result[2].id).toEqual('static3'); expect(result[2].id).toEqual('static3');
expect(result[2].value).toEqual(true); expect(result[2].value).toEqual(true);
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[0].endsWith(`${appName}/rb/v1/process-definitions/${processDefinitionId}/static-values`)).toBeTruthy(); expect(requestSpy.calls.mostRecent().args[0]).toContain(`${appName}/rb/v1/process-definitions/${processDefinitionId}/static-values`);
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[1]).toBe('GET'); expect(requestSpy.calls.mostRecent().args[1].httpMethod).toBe('GET');
done(); done();
}); });
}); });

View File

@@ -18,35 +18,27 @@
import { AlfrescoApiService, AppConfigService, LogService } from '@alfresco/adf-core'; import { AlfrescoApiService, AppConfigService, LogService } from '@alfresco/adf-core';
import { Injectable, inject } from '@angular/core'; import { Injectable, inject } from '@angular/core';
import { from, Observable } from 'rxjs'; import { from, Observable } from 'rxjs';
import { AdfHttpClient } from '@alfresco/adf-core/api';
import { RequestOptions } from '@alfresco/js-api';
export interface CallApiParams {
path: string;
httpMethod: string;
pathParams?: any;
queryParams?: any;
headerParams?: any;
formParams?: any;
bodyParam?: any;
contentTypes?: string[];
accepts?: string[];
returnType?: any;
contextRoot?: string;
responseType?: string;
}
@Injectable() @Injectable()
export class BaseCloudService { export class BaseCloudService {
protected apiService = inject(AlfrescoApiService); protected apiService = inject(AlfrescoApiService);
protected appConfigService = inject(AppConfigService); protected appConfigService = inject(AppConfigService);
protected logService = inject(LogService); protected logService = inject(LogService);
protected defaultParams: CallApiParams = { protected defaultParams: RequestOptions = {
path: '', path: '',
httpMethod: '', httpMethod: '',
contentTypes: ['application/json'], contentTypes: ['application/json'],
accepts: ['application/json'] accepts: ['application/json']
}; };
constructor(
protected adfHttpClient: AdfHttpClient) {}
getBasePath(appName: string): string { getBasePath(appName: string): string {
return appName return appName
? `${this.contextRoot}/${appName}` ? `${this.contextRoot}/${appName}`
@@ -55,63 +47,64 @@ export class BaseCloudService {
protected post<T, R>(url: string, data?: T, queryParams?: any): Observable<R> { protected post<T, R>(url: string, data?: T, queryParams?: any): Observable<R> {
return from( return from(
this.callApi<R>({ this.callApi<R>(
url,
{
...this.defaultParams, ...this.defaultParams,
path: url, path: url,
httpMethod: 'POST', httpMethod: 'POST',
bodyParam: data, bodyParam: data,
queryParams queryParams
}) }
)
); );
} }
protected put<T, R>(url: string, data?: T): Observable<R> { protected put<T, R>(url: string, data?: T): Observable<R> {
return from( return from(
this.callApi<R>({ this.callApi<R>(
url,
{
...this.defaultParams, ...this.defaultParams,
path: url, path: url,
httpMethod: 'PUT', httpMethod: 'PUT',
bodyParam: data bodyParam: data
}) }
)
); );
} }
protected delete(url: string): Observable<void> { protected delete(url: string): Observable<void> {
return from( return from(
this.callApi<void>({ this.callApi<void>(
url,
{
...this.defaultParams, ...this.defaultParams,
path: url, path: url,
httpMethod: 'DELETE' httpMethod: 'DELETE'
}) }
)
); );
} }
protected get<T>(url: string, queryParams?: any): Observable<T> { protected get<T>(url: string, queryParams?: any): Observable<T> {
return from( return from(
this.callApi<T>({ this.callApi<T>(
url,
{
...this.defaultParams, ...this.defaultParams,
path: url, path: url,
httpMethod: 'GET', httpMethod: 'GET',
queryParams queryParams
}) }
)
); );
} }
protected callApi<T>(params: CallApiParams): Promise<T> { protected callApi<T>(url: string, params: RequestOptions): Promise<T> {
return this.apiService.getInstance() return this.adfHttpClient.request(
.oauth2Auth.callCustomApi( url,
params.path, params
params.httpMethod,
params.pathParams,
params.queryParams,
params.headerParams,
params.formParams,
params.bodyParam,
params.contentTypes,
params.accepts,
params.returnType,
params.contextRoot,
params.responseType
); );
} }

View File

@@ -16,7 +16,7 @@
*/ */
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import { AlfrescoApiService, setupTestBed } from '@alfresco/adf-core'; import { setupTestBed } from '@alfresco/adf-core';
import { ProcessServiceCloudTestingModule } from '../testing/process-service-cloud.testing.module'; import { ProcessServiceCloudTestingModule } from '../testing/process-service-cloud.testing.module';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { NotificationCloudService } from './notification-cloud.service'; import { NotificationCloudService } from './notification-cloud.service';
@@ -27,7 +27,7 @@ describe('NotificationCloudService', () => {
let apollo: Apollo; let apollo: Apollo;
let apolloCreateSpy: jasmine.Spy; let apolloCreateSpy: jasmine.Spy;
let apolloSubscribeSpy: jasmine.Spy; let apolloSubscribeSpy: jasmine.Spy;
let apiService: AlfrescoApiService;
const useMock: any = { const useMock: any = {
subscribe: () => {} subscribe: () => {}
}; };
@@ -43,14 +43,6 @@ describe('NotificationCloudService', () => {
} }
`; `;
const apiServiceMock: any = {
oauth2Auth: {
token: '1234567'
},
isEcmLoggedIn: () => false,
reply: jasmine.createSpy('reply')
};
setupTestBed({ setupTestBed({
imports: [ imports: [
TranslateModule.forRoot(), TranslateModule.forRoot(),
@@ -61,9 +53,7 @@ describe('NotificationCloudService', () => {
beforeEach(() => { beforeEach(() => {
service = TestBed.inject(NotificationCloudService); service = TestBed.inject(NotificationCloudService);
apollo = TestBed.inject(Apollo); apollo = TestBed.inject(Apollo);
apiService = TestBed.inject(AlfrescoApiService);
spyOn(apiService, 'getInstance').and.returnValue(apiServiceMock);
service.appsListening = []; service.appsListening = [];
apolloCreateSpy = spyOn(apollo, 'createNamed'); apolloCreateSpy = spyOn(apollo, 'createNamed');
apolloSubscribeSpy = spyOn(apollo, 'use').and.returnValue(useMock); apolloSubscribeSpy = spyOn(apollo, 'use').and.returnValue(useMock);

View File

@@ -22,7 +22,9 @@ import { WebSocketLink } from '@apollo/client/link/ws';
import { onError } from '@apollo/client/link/error'; import { onError } from '@apollo/client/link/error';
import { getMainDefinition } from '@apollo/client/utilities'; import { getMainDefinition } from '@apollo/client/utilities';
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { AuthenticationService } from '@alfresco/adf-core';
import { BaseCloudService } from './base-cloud.service'; import { BaseCloudService } from './base-cloud.service';
import { AdfHttpClient } from '@alfresco/adf-core/api';
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
@@ -30,8 +32,12 @@ import { BaseCloudService } from './base-cloud.service';
export class NotificationCloudService extends BaseCloudService { export class NotificationCloudService extends BaseCloudService {
appsListening = []; appsListening = [];
constructor(public apollo: Apollo, private http: HttpLink) { constructor(
super(); public apollo: Apollo,
private http: HttpLink,
private authService: AuthenticationService,
protected adfHttpClient: AdfHttpClient) {
super(adfHttpClient);
} }
private get webSocketHost() { private get webSocketHost() {
@@ -57,7 +63,7 @@ export class NotificationCloudService extends BaseCloudService {
connectionParams: { connectionParams: {
kaInterval: 2000, kaInterval: 2000,
// eslint-disable-next-line @typescript-eslint/naming-convention // eslint-disable-next-line @typescript-eslint/naming-convention
'X-Authorization': 'Bearer ' + this.apiService.getInstance().oauth2Auth.token 'X-Authorization': 'Bearer ' + this.authService.getToken()
} }
} }
}); });
@@ -81,7 +87,7 @@ export class NotificationCloudService extends BaseCloudService {
headers: { headers: {
...oldHeaders, ...oldHeaders,
// eslint-disable-next-line @typescript-eslint/naming-convention // eslint-disable-next-line @typescript-eslint/naming-convention
'X-Authorization': 'Bearer ' + this.apiService.getInstance().oauth2Auth.token 'X-Authorization': 'Bearer ' + this.authService.getToken()
} }
}); });
forward(operation); forward(operation);

View File

@@ -17,36 +17,22 @@
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import { UserPreferenceCloudService } from './user-preference-cloud.service'; import { UserPreferenceCloudService } from './user-preference-cloud.service';
import { setupTestBed, AlfrescoApiService } from '@alfresco/adf-core'; import { setupTestBed } from '@alfresco/adf-core';
import { mockPreferences, getMockPreference, createMockPreference, updateMockPreference } from '../mock/user-preference.mock'; import { mockPreferences, getMockPreference, createMockPreference, updateMockPreference } from '../mock/user-preference.mock';
import { ProcessServiceCloudTestingModule } from '../testing/process-service-cloud.testing.module'; import { ProcessServiceCloudTestingModule } from '../testing/process-service-cloud.testing.module';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { AdfHttpClient } from '@alfresco/adf-core/api';
describe('PreferenceService', () => { describe('PreferenceService', () => {
let service: UserPreferenceCloudService; let service: UserPreferenceCloudService;
let alfrescoApiMock: AlfrescoApiService; let adfHttpClient: AdfHttpClient;
let getInstanceSpy: jasmine.Spy; let requestSpy: jasmine.Spy;
const errorResponse = { const errorResponse = {
error: 'Mock Error', error: 'Mock Error',
state: 404, stateText: 'Not Found' state: 404, stateText: 'Not Found'
}; };
const apiMock = (mockResponse): any => ({
oauth2Auth: {
callCustomApi: () => Promise.resolve(mockResponse)
},
isEcmLoggedIn: () => false,
reply: jasmine.createSpy('reply')
});
const apiErrorMock: any = {
oauth2Auth: {
callCustomApi: () => Promise.reject(errorResponse)
},
isEcmLoggedIn:() => false
};
setupTestBed({ setupTestBed({
imports: [ imports: [
TranslateModule.forRoot(), TranslateModule.forRoot(),
@@ -56,8 +42,8 @@ describe('PreferenceService', () => {
beforeEach(() => { beforeEach(() => {
service = TestBed.inject(UserPreferenceCloudService); service = TestBed.inject(UserPreferenceCloudService);
alfrescoApiMock = TestBed.inject(AlfrescoApiService); adfHttpClient = TestBed.inject(AdfHttpClient);
getInstanceSpy = spyOn(alfrescoApiMock, 'getInstance').and.returnValue(apiMock(mockPreferences)); requestSpy = spyOn(adfHttpClient, 'request').and.returnValue(Promise.resolve(mockPreferences));
}); });
it('should return the preferences', (done) => { it('should return the preferences', (done) => {
@@ -81,7 +67,7 @@ describe('PreferenceService', () => {
}); });
it('Should not fetch preferences if error occurred', (done) => { it('Should not fetch preferences if error occurred', (done) => {
getInstanceSpy.and.returnValue(apiErrorMock); requestSpy.and.returnValue(Promise.reject(errorResponse));
service.getPreferences('mock-app-name') service.getPreferences('mock-app-name')
.subscribe( .subscribe(
() => fail('expected an error, not preferences'), () => fail('expected an error, not preferences'),
@@ -95,7 +81,7 @@ describe('PreferenceService', () => {
}); });
it('should return the preference by key', (done) => { it('should return the preference by key', (done) => {
getInstanceSpy.and.returnValue(apiMock(getMockPreference)); requestSpy.and.returnValue(Promise.resolve(getMockPreference));
service.getPreferenceByKey('mock-app-name', 'mock-preference-key').subscribe((res: any) => { service.getPreferenceByKey('mock-app-name', 'mock-preference-key').subscribe((res: any) => {
expect(res).toBeDefined(); expect(res).toBeDefined();
expect(res).not.toBeNull(); expect(res).not.toBeNull();
@@ -109,7 +95,7 @@ describe('PreferenceService', () => {
}); });
it('Should not fetch preference by key if error occurred', (done) => { it('Should not fetch preference by key if error occurred', (done) => {
getInstanceSpy.and.returnValue(apiErrorMock); requestSpy.and.returnValue(Promise.reject(errorResponse));
service.getPreferenceByKey('mock-app-name', 'mock-preference-key') service.getPreferenceByKey('mock-app-name', 'mock-preference-key')
.subscribe( .subscribe(
() => fail('expected an error, not preference'), () => fail('expected an error, not preference'),
@@ -123,7 +109,7 @@ describe('PreferenceService', () => {
}); });
it('should create preference', (done) => { it('should create preference', (done) => {
getInstanceSpy.and.returnValue(apiMock(createMockPreference)); requestSpy.and.returnValue(Promise.resolve(createMockPreference));
service.createPreference('mock-app-name', 'mock-preference-key', createMockPreference).subscribe((res: any) => { service.createPreference('mock-app-name', 'mock-preference-key', createMockPreference).subscribe((res: any) => {
expect(res).toBeDefined(); expect(res).toBeDefined();
expect(res).not.toBeNull(); expect(res).not.toBeNull();
@@ -135,7 +121,7 @@ describe('PreferenceService', () => {
}); });
it('Should not create preference if error occurred', (done) => { it('Should not create preference if error occurred', (done) => {
getInstanceSpy.and.returnValue(apiErrorMock); requestSpy.and.returnValue(Promise.reject(errorResponse));
service.createPreference('mock-app-name', 'mock-preference-key', createMockPreference) service.createPreference('mock-app-name', 'mock-preference-key', createMockPreference)
.subscribe( .subscribe(
() => fail('expected an error, not to create preference'), () => fail('expected an error, not to create preference'),
@@ -149,7 +135,7 @@ describe('PreferenceService', () => {
}); });
it('should update preference', (done) => { it('should update preference', (done) => {
getInstanceSpy.and.returnValue(apiMock(updateMockPreference)); requestSpy.and.returnValue(Promise.resolve(updateMockPreference));
service.updatePreference('mock-app-name', 'mock-preference-key', updateMockPreference).subscribe((res: any) => { service.updatePreference('mock-app-name', 'mock-preference-key', updateMockPreference).subscribe((res: any) => {
expect(res).toBeDefined(); expect(res).toBeDefined();
expect(res).not.toBeNull(); expect(res).not.toBeNull();
@@ -161,7 +147,7 @@ describe('PreferenceService', () => {
}); });
it('Should not update preference if error occurred', (done) => { it('Should not update preference if error occurred', (done) => {
getInstanceSpy.and.returnValue(apiErrorMock); requestSpy.and.returnValue(Promise.reject(errorResponse));
service.createPreference('mock-app-name', 'mock-preference-key', updateMockPreference) service.createPreference('mock-app-name', 'mock-preference-key', updateMockPreference)
.subscribe( .subscribe(
() => fail('expected an error, not to update preference'), () => fail('expected an error, not to update preference'),
@@ -175,7 +161,7 @@ describe('PreferenceService', () => {
}); });
it('should delete preference', (done) => { it('should delete preference', (done) => {
getInstanceSpy.and.returnValue(apiMock('')); requestSpy.and.returnValue(Promise.resolve(''));
service.deletePreference('mock-app-name', 'mock-preference-key').subscribe((res: any) => { service.deletePreference('mock-app-name', 'mock-preference-key').subscribe((res: any) => {
expect(res).toBeDefined(); expect(res).toBeDefined();
done(); done();
@@ -183,7 +169,7 @@ describe('PreferenceService', () => {
}); });
it('Should not delete preference if error occurred', (done) => { it('Should not delete preference if error occurred', (done) => {
getInstanceSpy.and.returnValue(apiErrorMock); requestSpy.and.returnValue(Promise.reject(errorResponse));
service.deletePreference('mock-app-name', 'mock-preference-key') service.deletePreference('mock-app-name', 'mock-preference-key')
.subscribe( .subscribe(
() => fail('expected an error, not to delete preference'), () => fail('expected an error, not to delete preference'),

View File

@@ -16,7 +16,7 @@
*/ */
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import { setupTestBed, TranslationService, AlfrescoApiService } from '@alfresco/adf-core'; import { setupTestBed, TranslationService } from '@alfresco/adf-core';
import { TaskCloudService } from './task-cloud.service'; import { TaskCloudService } from './task-cloud.service';
import { taskCompleteCloudMock } from '../task-header/mocks/fake-complete-task.mock'; import { taskCompleteCloudMock } from '../task-header/mocks/fake-complete-task.mock';
import { assignedTaskDetailsCloudMock, createdTaskDetailsCloudMock, emptyOwnerTaskDetailsCloudMock } from '../task-header/mocks/task-details-cloud.mock'; import { assignedTaskDetailsCloudMock, createdTaskDetailsCloudMock, emptyOwnerTaskDetailsCloudMock } from '../task-header/mocks/task-details-cloud.mock';
@@ -25,53 +25,25 @@ import { cloudMockUser } from '../start-task/mock/user-cloud.mock';
import { ProcessServiceCloudTestingModule } from '../../testing/process-service-cloud.testing.module'; import { ProcessServiceCloudTestingModule } from '../../testing/process-service-cloud.testing.module';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { IdentityUserService } from '../../people/services/identity-user.service'; import { IdentityUserService } from '../../people/services/identity-user.service';
import { AdfHttpClient } from '@alfresco/adf-core/api';
describe('Task Cloud Service', () => { describe('Task Cloud Service', () => {
let service: TaskCloudService; let service: TaskCloudService;
let alfrescoApiMock: AlfrescoApiService; let adfHttpClient: AdfHttpClient;
let identityUserService: IdentityUserService; let identityUserService: IdentityUserService;
let translateService: TranslationService; let translateService: TranslationService;
let requestSpy: jasmine.Spy;
const returnFakeTaskCompleteResults = (): any => ({ const returnFakeTaskCompleteResults = () => Promise.resolve(taskCompleteCloudMock);
reply: () => {},
oauth2Auth: {
callCustomApi : () => Promise.resolve(taskCompleteCloudMock)
},
isEcmLoggedIn: () => false
});
const returnFakeTaskCompleteResultsError = (): any => ({ const returnFakeTaskCompleteResultsError = () => Promise.reject(taskCompleteCloudMock);
reply: () => {},
oauth2Auth: {
callCustomApi : () => Promise.reject(taskCompleteCloudMock)
},
isEcmLoggedIn: () => false
});
const returnFakeTaskDetailsResults = (): any => ({ const returnFakeTaskDetailsResults = () => Promise.resolve(fakeTaskDetailsCloud);
reply: () => {},
oauth2Auth: {
callCustomApi : () => Promise.resolve(fakeTaskDetailsCloud)
},
isEcmLoggedIn: () => false
});
const returnFakeCandidateUsersResults = (): any => ({ const returnFakeCandidateUsersResults = () => Promise.resolve(['mockuser1', 'mockuser2', 'mockuser3']);
reply: () => {},
oauth2Auth: {
callCustomApi : () => Promise.resolve(['mockuser1', 'mockuser2', 'mockuser3'])
},
isEcmLoggedIn: () => false
});
const returnFakeCandidateGroupResults = (): any => ({ const returnFakeCandidateGroupResults = () => Promise.resolve(['mockgroup1', 'mockgroup2', 'mockgroup3']);
reply: () => {},
oauth2Auth: {
callCustomApi : () => Promise.resolve(['mockgroup1', 'mockgroup2', 'mockgroup3'])
},
isEcmLoggedIn: () => false
});
setupTestBed({ setupTestBed({
imports: [ imports: [
@@ -81,18 +53,19 @@ describe('Task Cloud Service', () => {
}); });
beforeEach(() => { beforeEach(() => {
alfrescoApiMock = TestBed.inject(AlfrescoApiService); adfHttpClient = TestBed.inject(AdfHttpClient);
identityUserService = TestBed.inject(IdentityUserService); identityUserService = TestBed.inject(IdentityUserService);
translateService = TestBed.inject(TranslationService); translateService = TestBed.inject(TranslationService);
service = TestBed.inject(TaskCloudService); service = TestBed.inject(TaskCloudService);
spyOn(translateService, 'instant').and.callFake((key) => key ? `${key}_translated` : null); spyOn(translateService, 'instant').and.callFake((key) => key ? `${key}_translated` : null);
spyOn(identityUserService, 'getCurrentUserInfo').and.returnValue(cloudMockUser); spyOn(identityUserService, 'getCurrentUserInfo').and.returnValue(cloudMockUser);
requestSpy = spyOn(adfHttpClient, 'request');
}); });
it('should complete a task', (done) => { it('should complete a task', (done) => {
const appName = 'simple-app'; const appName = 'simple-app';
const taskId = '68d54a8f'; const taskId = '68d54a8f';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskCompleteResults); requestSpy.and.callFake(returnFakeTaskCompleteResults);
service.completeTask(appName, taskId).subscribe((res: any) => { service.completeTask(appName, taskId).subscribe((res: any) => {
expect(res).toBeDefined(); expect(res).toBeDefined();
expect(res).not.toBeNull(); expect(res).not.toBeNull();
@@ -103,7 +76,7 @@ describe('Task Cloud Service', () => {
}); });
it('should not complete a task', (done) => { it('should not complete a task', (done) => {
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskCompleteResultsError); requestSpy.and.callFake(returnFakeTaskCompleteResultsError);
const appName = 'simple-app'; const appName = 'simple-app';
const taskId = '68d54a8f'; const taskId = '68d54a8f';
@@ -140,7 +113,7 @@ describe('Task Cloud Service', () => {
const appName = 'simple-app'; const appName = 'simple-app';
const taskId = '68d54a8f'; const taskId = '68d54a8f';
const canCompleteTaskResult = service.canCompleteTask(emptyOwnerTaskDetailsCloudMock); const canCompleteTaskResult = service.canCompleteTask(emptyOwnerTaskDetailsCloudMock);
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskCompleteResults); requestSpy.and.callFake(returnFakeTaskCompleteResults);
service.completeTask(appName, taskId).subscribe((res: any) => { service.completeTask(appName, taskId).subscribe((res: any) => {
expect(canCompleteTaskResult).toEqual(true); expect(canCompleteTaskResult).toEqual(true);
@@ -156,7 +129,7 @@ describe('Task Cloud Service', () => {
const appName = 'taskp-app'; const appName = 'taskp-app';
const assignee = 'user12'; const assignee = 'user12';
const taskId = '68d54a8f'; const taskId = '68d54a8f';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults); requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.claimTask(appName, taskId, assignee).subscribe((res: any) => { service.claimTask(appName, taskId, assignee).subscribe((res: any) => {
expect(res).toBeDefined(); expect(res).toBeDefined();
expect(res).not.toBeNull(); expect(res).not.toBeNull();
@@ -170,7 +143,7 @@ describe('Task Cloud Service', () => {
const appName = null; const appName = null;
const taskId = '68d54a8f'; const taskId = '68d54a8f';
const assignee = 'user12'; const assignee = 'user12';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults); requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.claimTask(appName, taskId, assignee).subscribe( service.claimTask(appName, taskId, assignee).subscribe(
() => { }, () => { },
(error) => { (error) => {
@@ -183,7 +156,7 @@ describe('Task Cloud Service', () => {
const appName = 'task-app'; const appName = 'task-app';
const taskId = null; const taskId = null;
const assignee = 'user12'; const assignee = 'user12';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults); requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.claimTask(appName, taskId, assignee).subscribe( service.claimTask(appName, taskId, assignee).subscribe(
() => { }, () => { },
(error) => { (error) => {
@@ -195,7 +168,7 @@ describe('Task Cloud Service', () => {
it('should return the task details when unclaiming a task', (done) => { it('should return the task details when unclaiming a task', (done) => {
const appName = 'taskp-app'; const appName = 'taskp-app';
const taskId = '68d54a8f'; const taskId = '68d54a8f';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults); requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.unclaimTask(appName, taskId).subscribe((res: any) => { service.unclaimTask(appName, taskId).subscribe((res: any) => {
expect(res).toBeDefined(); expect(res).toBeDefined();
expect(res).not.toBeNull(); expect(res).not.toBeNull();
@@ -208,7 +181,7 @@ describe('Task Cloud Service', () => {
it('should throw error if appName is not defined when unclaiming a task', (done) => { it('should throw error if appName is not defined when unclaiming a task', (done) => {
const appName = null; const appName = null;
const taskId = '68d54a8f'; const taskId = '68d54a8f';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults); requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.unclaimTask(appName, taskId).subscribe( service.unclaimTask(appName, taskId).subscribe(
() => { }, () => { },
(error) => { (error) => {
@@ -220,7 +193,7 @@ describe('Task Cloud Service', () => {
it('should throw error if taskId is not defined when unclaiming a task', (done) => { it('should throw error if taskId is not defined when unclaiming a task', (done) => {
const appName = 'task-app'; const appName = 'task-app';
const taskId = null; const taskId = null;
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults); requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.unclaimTask(appName, taskId).subscribe( service.unclaimTask(appName, taskId).subscribe(
() => { }, () => { },
(error) => { (error) => {
@@ -232,7 +205,7 @@ describe('Task Cloud Service', () => {
it('should return the task details when querying by id', (done) => { it('should return the task details when querying by id', (done) => {
const appName = 'taskp-app'; const appName = 'taskp-app';
const taskId = '68d54a8f'; const taskId = '68d54a8f';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults); requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.getTaskById(appName, taskId).subscribe((res: any) => { service.getTaskById(appName, taskId).subscribe((res: any) => {
expect(res).toBeDefined(); expect(res).toBeDefined();
expect(res).not.toBeNull(); expect(res).not.toBeNull();
@@ -245,7 +218,7 @@ describe('Task Cloud Service', () => {
it('should throw error if appName is not defined when querying by id', (done) => { it('should throw error if appName is not defined when querying by id', (done) => {
const appName = null; const appName = null;
const taskId = '68d54a8f'; const taskId = '68d54a8f';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults); requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.getTaskById(appName, taskId).subscribe( service.getTaskById(appName, taskId).subscribe(
() => { }, () => { },
(error) => { (error) => {
@@ -257,7 +230,7 @@ describe('Task Cloud Service', () => {
it('should throw error if taskId is not defined when querying by id', (done) => { it('should throw error if taskId is not defined when querying by id', (done) => {
const appName = 'task-app'; const appName = 'task-app';
const taskId = null; const taskId = null;
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults); requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.getTaskById(appName, taskId).subscribe( service.getTaskById(appName, taskId).subscribe(
() => { }, () => { },
(error) => { (error) => {
@@ -270,7 +243,7 @@ describe('Task Cloud Service', () => {
const appName = null; const appName = null;
const taskId = '68d54a8f'; const taskId = '68d54a8f';
const updatePayload = { description: 'New description' }; const updatePayload = { description: 'New description' };
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults); requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.updateTask(appName, taskId, updatePayload).subscribe( service.updateTask(appName, taskId, updatePayload).subscribe(
() => { }, () => { },
(error) => { (error) => {
@@ -283,7 +256,7 @@ describe('Task Cloud Service', () => {
const appName = 'task-app'; const appName = 'task-app';
const taskId = null; const taskId = null;
const updatePayload = { description: 'New description' }; const updatePayload = { description: 'New description' };
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults); requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.updateTask(appName, taskId, updatePayload).subscribe( service.updateTask(appName, taskId, updatePayload).subscribe(
() => { }, () => { },
(error) => { (error) => {
@@ -296,7 +269,7 @@ describe('Task Cloud Service', () => {
const appName = 'taskp-app'; const appName = 'taskp-app';
const taskId = '68d54a8f'; const taskId = '68d54a8f';
const updatePayload = { description: 'New description' }; const updatePayload = { description: 'New description' };
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults); requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.updateTask(appName, taskId, updatePayload).subscribe((res: any) => { service.updateTask(appName, taskId, updatePayload).subscribe((res: any) => {
expect(res).toBeDefined(); expect(res).toBeDefined();
expect(res).not.toBeNull(); expect(res).not.toBeNull();
@@ -310,7 +283,7 @@ describe('Task Cloud Service', () => {
const appName = null; const appName = null;
const taskId = '68d54a8f'; const taskId = '68d54a8f';
const updatePayload = { description: 'New description' }; const updatePayload = { description: 'New description' };
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults); requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.updateTask(appName, taskId, updatePayload).subscribe( service.updateTask(appName, taskId, updatePayload).subscribe(
() => { }, () => { },
(error) => { (error) => {
@@ -323,7 +296,7 @@ describe('Task Cloud Service', () => {
const appName = 'task-app'; const appName = 'task-app';
const taskId = null; const taskId = null;
const updatePayload = { description: 'New description' }; const updatePayload = { description: 'New description' };
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults); requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.updateTask(appName, taskId, updatePayload).subscribe( service.updateTask(appName, taskId, updatePayload).subscribe(
() => { }, () => { },
(error) => { (error) => {
@@ -335,7 +308,7 @@ describe('Task Cloud Service', () => {
it('should return the candidate users by appName and taskId', (done) => { it('should return the candidate users by appName and taskId', (done) => {
const appName = 'taskp-app'; const appName = 'taskp-app';
const taskId = '68d54a8f'; const taskId = '68d54a8f';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeCandidateUsersResults); requestSpy.and.callFake(returnFakeCandidateUsersResults);
service.getCandidateUsers(appName, taskId).subscribe((res: string[]) => { service.getCandidateUsers(appName, taskId).subscribe((res: string[]) => {
expect(res).toBeDefined(); expect(res).toBeDefined();
expect(res).not.toBeNull(); expect(res).not.toBeNull();
@@ -349,7 +322,7 @@ describe('Task Cloud Service', () => {
it('should log message and return empty array if appName is not defined when fetching candidate users', (done) => { it('should log message and return empty array if appName is not defined when fetching candidate users', (done) => {
const appName = null; const appName = null;
const taskId = '68d54a8f'; const taskId = '68d54a8f';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeCandidateUsersResults); requestSpy.and.callFake(returnFakeCandidateUsersResults);
service.getCandidateUsers(appName, taskId).subscribe( service.getCandidateUsers(appName, taskId).subscribe(
(res: any[]) => { (res: any[]) => {
expect(res.length).toBe(0); expect(res.length).toBe(0);
@@ -360,7 +333,7 @@ describe('Task Cloud Service', () => {
it('should log message and return empty array if taskId is not defined when fetching candidate users', (done) => { it('should log message and return empty array if taskId is not defined when fetching candidate users', (done) => {
const appName = 'task-app'; const appName = 'task-app';
const taskId = null; const taskId = null;
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeCandidateUsersResults); requestSpy.and.callFake(returnFakeCandidateUsersResults);
service.getCandidateUsers(appName, taskId).subscribe( service.getCandidateUsers(appName, taskId).subscribe(
(res: any[]) => { (res: any[]) => {
expect(res.length).toBe(0); expect(res.length).toBe(0);
@@ -371,7 +344,7 @@ describe('Task Cloud Service', () => {
it('should return the candidate groups by appName and taskId', (done) => { it('should return the candidate groups by appName and taskId', (done) => {
const appName = 'taskp-app'; const appName = 'taskp-app';
const taskId = '68d54a8f'; const taskId = '68d54a8f';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeCandidateGroupResults); requestSpy.and.callFake(returnFakeCandidateGroupResults);
service.getCandidateGroups(appName, taskId).subscribe((res: string[]) => { service.getCandidateGroups(appName, taskId).subscribe((res: string[]) => {
expect(res).toBeDefined(); expect(res).toBeDefined();
expect(res).not.toBeNull(); expect(res).not.toBeNull();
@@ -385,7 +358,7 @@ describe('Task Cloud Service', () => {
it('should log message and return empty array if appName is not defined when fetching candidate groups', (done) => { it('should log message and return empty array if appName is not defined when fetching candidate groups', (done) => {
const appName = null; const appName = null;
const taskId = '68d54a8f'; const taskId = '68d54a8f';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeCandidateGroupResults); requestSpy.and.callFake(returnFakeCandidateGroupResults);
service.getCandidateGroups(appName, taskId).subscribe( service.getCandidateGroups(appName, taskId).subscribe(
(res: any[]) => { (res: any[]) => {
expect(res.length).toBe(0); expect(res.length).toBe(0);
@@ -396,7 +369,7 @@ describe('Task Cloud Service', () => {
it('should log message and return empty array if taskId is not defined when fetching candidate groups', (done) => { it('should log message and return empty array if taskId is not defined when fetching candidate groups', (done) => {
const appName = 'task-app'; const appName = 'task-app';
const taskId = null; const taskId = null;
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeCandidateGroupResults); requestSpy.and.callFake(returnFakeCandidateGroupResults);
service.getCandidateGroups(appName, taskId).subscribe( service.getCandidateGroups(appName, taskId).subscribe(
(res: any[]) => { (res: any[]) => {
expect(res.length).toBe(0); expect(res.length).toBe(0);
@@ -407,7 +380,7 @@ describe('Task Cloud Service', () => {
it('should call assign api and return updated task details', (done) => { it('should call assign api and return updated task details', (done) => {
const appName = 'task-app'; const appName = 'task-app';
const taskId = '68d54a8f'; const taskId = '68d54a8f';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults); requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.assign(appName, taskId, 'Phil Woods').subscribe( service.assign(appName, taskId, 'Phil Woods').subscribe(
(res) => { (res) => {
expect(res.assignee).toBe('Phil Woods'); expect(res.assignee).toBe('Phil Woods');
@@ -418,7 +391,7 @@ describe('Task Cloud Service', () => {
it('should throw error if appName is not defined when changing task assignee', (done) => { it('should throw error if appName is not defined when changing task assignee', (done) => {
const appName = ''; const appName = '';
const taskId = '68d54a8f'; const taskId = '68d54a8f';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults); requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.assign(appName, taskId, 'mock-assignee').subscribe( service.assign(appName, taskId, 'mock-assignee').subscribe(
() => { }, () => { },
(error) => { (error) => {
@@ -430,7 +403,7 @@ describe('Task Cloud Service', () => {
it('should throw error if taskId is not defined when changing task assignee', (done) => { it('should throw error if taskId is not defined when changing task assignee', (done) => {
const appName = 'task-app'; const appName = 'task-app';
const taskId = ''; const taskId = '';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults); requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.assign(appName, taskId, 'mock-assignee').subscribe( service.assign(appName, taskId, 'mock-assignee').subscribe(
() => { }, () => { },
(error) => { (error) => {

View File

@@ -33,6 +33,7 @@ import { ProcessDefinitionCloud } from '../../models/process-definition-cloud.mo
import { DEFAULT_TASK_PRIORITIES, TaskPriorityOption } from '../models/task.model'; import { DEFAULT_TASK_PRIORITIES, TaskPriorityOption } from '../models/task.model';
import { TaskCloudServiceInterface } from './task-cloud.service.interface'; import { TaskCloudServiceInterface } from './task-cloud.service.interface';
import { IdentityUserService } from '../../people/services/identity-user.service'; import { IdentityUserService } from '../../people/services/identity-user.service';
import { AdfHttpClient } from '@alfresco/adf-core/api';
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
@@ -43,9 +44,10 @@ export class TaskCloudService extends BaseCloudService implements TaskCloudServi
constructor( constructor(
private translateService: TranslationService, private translateService: TranslationService,
private identityUserService: IdentityUserService private identityUserService: IdentityUserService,
adfHttpClient: AdfHttpClient
) { ) {
super(); super(adfHttpClient);
} }
/** /**

View File

@@ -26,6 +26,7 @@ import { TaskCloudNodePaging } from '../../../models/task-cloud.model';
import { NotificationCloudService } from '../../../services/notification-cloud.service'; import { NotificationCloudService } from '../../../services/notification-cloud.service';
import { TaskCloudEngineEvent } from '../../../models/engine-event-cloud.model'; import { TaskCloudEngineEvent } from '../../../models/engine-event-cloud.model';
import { IdentityUserService } from '../../../people/services/identity-user.service'; import { IdentityUserService } from '../../../people/services/identity-user.service';
import { AdfHttpClient } from '@alfresco/adf-core/api';
const TASK_EVENT_SUBSCRIPTION_QUERY = ` const TASK_EVENT_SUBSCRIPTION_QUERY = `
subscription { subscription {
@@ -54,8 +55,9 @@ export class TaskFilterCloudService extends BaseCloudService {
private identityUserService: IdentityUserService, private identityUserService: IdentityUserService,
@Inject(TASK_FILTERS_SERVICE_TOKEN) @Inject(TASK_FILTERS_SERVICE_TOKEN)
public preferenceService: PreferenceCloudServiceInterface, public preferenceService: PreferenceCloudServiceInterface,
private notificationCloudService: NotificationCloudService) { private notificationCloudService: NotificationCloudService,
super(); adfHttpClient: AdfHttpClient) {
super(adfHttpClient);
this.filtersSubject = new BehaviorSubject([]); this.filtersSubject = new BehaviorSubject([]);
this.filters$ = this.filtersSubject.asObservable(); this.filters$ = this.filtersSubject.asObservable();
} }

View File

@@ -296,6 +296,7 @@ describe('TaskFormCloudComponent', () => {
spyOn(component.cancelClick,'emit').and.stub(); spyOn(component.cancelClick,'emit').and.stub();
fixture.detectChanges(); fixture.detectChanges();
const cancelBtn = debugElement.query(By.css('#adf-cloud-cancel-task')); const cancelBtn = debugElement.query(By.css('#adf-cloud-cancel-task'));
cancelBtn.triggerEventHandler('click', {}); cancelBtn.triggerEventHandler('click', {});
fixture.detectChanges(); fixture.detectChanges();
@@ -347,7 +348,7 @@ describe('TaskFormCloudComponent', () => {
expect(component.error.emit).toHaveBeenCalled(); expect(component.error.emit).toHaveBeenCalled();
}); });
it('should reload when task is completed', () => { it('should reload when task is completed', async () => {
spyOn(taskCloudService, 'completeTask').and.returnValue(of({})); spyOn(taskCloudService, 'completeTask').and.returnValue(of({}));
const reloadSpy = spyOn(component, 'ngOnChanges').and.callThrough(); const reloadSpy = spyOn(component, 'ngOnChanges').and.callThrough();
@@ -356,10 +357,11 @@ describe('TaskFormCloudComponent', () => {
const completeBtn = debugElement.query(By.css('[adf-cloud-complete-task]')); const completeBtn = debugElement.query(By.css('[adf-cloud-complete-task]'));
completeBtn.nativeElement.click(); completeBtn.nativeElement.click();
await fixture.whenStable();
expect(reloadSpy).toHaveBeenCalled(); expect(reloadSpy).toHaveBeenCalled();
}); });
it('should reload when task is claimed', () => { it('should reload when task is claimed', async () => {
spyOn(taskCloudService, 'claimTask').and.returnValue(of({})); spyOn(taskCloudService, 'claimTask').and.returnValue(of({}));
spyOn(component, 'hasCandidateUsers').and.returnValue(true); spyOn(component, 'hasCandidateUsers').and.returnValue(true);
const reloadSpy = spyOn(component, 'ngOnChanges').and.callThrough(); const reloadSpy = spyOn(component, 'ngOnChanges').and.callThrough();
@@ -372,10 +374,11 @@ describe('TaskFormCloudComponent', () => {
const claimBtn = debugElement.query(By.css('[adf-cloud-claim-task]')); const claimBtn = debugElement.query(By.css('[adf-cloud-claim-task]'));
claimBtn.nativeElement.click(); claimBtn.nativeElement.click();
await fixture.whenStable();
expect(reloadSpy).toHaveBeenCalled(); expect(reloadSpy).toHaveBeenCalled();
}); });
it('should emit taskUnclaimed when task is unclaimed', () => { it('should emit taskUnclaimed when task is unclaimed', async () => {
spyOn(taskCloudService, 'unclaimTask').and.returnValue(of({})); spyOn(taskCloudService, 'unclaimTask').and.returnValue(of({}));
const reloadSpy = spyOn(component, 'ngOnChanges').and.callThrough(); const reloadSpy = spyOn(component, 'ngOnChanges').and.callThrough();
spyOn(component, 'hasCandidateUsers').and.returnValue(true); spyOn(component, 'hasCandidateUsers').and.returnValue(true);
@@ -389,6 +392,7 @@ describe('TaskFormCloudComponent', () => {
const unclaimBtn = debugElement.query(By.css('[adf-cloud-unclaim-task]')); const unclaimBtn = debugElement.query(By.css('[adf-cloud-unclaim-task]'));
unclaimBtn.nativeElement.click(); unclaimBtn.nativeElement.click();
await fixture.whenStable();
expect(reloadSpy).toHaveBeenCalled(); expect(reloadSpy).toHaveBeenCalled();
}); });

View File

@@ -16,32 +16,23 @@
*/ */
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import { setupTestBed, AlfrescoApiService, LogService } from '@alfresco/adf-core'; import { setupTestBed, LogService } from '@alfresco/adf-core';
import { ServiceTaskListCloudService } from './service-task-list-cloud.service'; import { ServiceTaskListCloudService } from './service-task-list-cloud.service';
import { ServiceTaskQueryCloudRequestModel } from '../models/service-task-cloud.model'; import { ServiceTaskQueryCloudRequestModel } from '../models/service-task-cloud.model';
import { ProcessServiceCloudTestingModule } from '../../../testing/process-service-cloud.testing.module'; import { ProcessServiceCloudTestingModule } from '../../../testing/process-service-cloud.testing.module';
import { of } from 'rxjs'; import { of } from 'rxjs';
import { AdfHttpClient } from '@alfresco/adf-core/api';
describe('Activiti ServiceTaskList Cloud Service', () => { describe('Activiti ServiceTaskList Cloud Service', () => {
let service: ServiceTaskListCloudService; let service: ServiceTaskListCloudService;
let alfrescoApiService: AlfrescoApiService; let adfHttpClient: AdfHttpClient;
let logService: LogService; let logService: LogService;
let requestSpy: jasmine.Spy;
const returnCallQueryParameters = (): any => ({ const returnCallQueryParameters = (_queryUrl, options) => Promise.resolve(options.queryParams);
oauth2Auth: {
callCustomApi: (_queryUrl, _operation, _context, queryParams) => Promise.resolve(queryParams)
},
isEcmLoggedIn: () => false,
reply: jasmine.createSpy('reply')
});
const returnCallUrl = (): any => ({ const returnCallUrl = (queryUrl) => Promise.resolve(queryUrl);
oauth2Auth: {
callCustomApi: (queryUrl) => Promise.resolve(queryUrl)
},
isEcmLoggedIn: () => false
});
setupTestBed({ setupTestBed({
imports: [ imports: [
@@ -50,14 +41,15 @@ describe('Activiti ServiceTaskList Cloud Service', () => {
}); });
beforeEach(() => { beforeEach(() => {
alfrescoApiService = TestBed.inject(AlfrescoApiService); adfHttpClient = TestBed.inject(AdfHttpClient);
service = TestBed.inject(ServiceTaskListCloudService); service = TestBed.inject(ServiceTaskListCloudService);
logService = TestBed.inject(LogService); logService = TestBed.inject(LogService);
requestSpy = spyOn(adfHttpClient, 'request');
}); });
it('should append to the call all the parameters', (done) => { it('should append to the call all the parameters', (done) => {
const taskRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service' } as ServiceTaskQueryCloudRequestModel; const taskRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service' } as ServiceTaskQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallQueryParameters); requestSpy.and.callFake(returnCallQueryParameters);
service.getServiceTaskByRequest(taskRequest).subscribe((res) => { service.getServiceTaskByRequest(taskRequest).subscribe((res) => {
expect(res).toBeDefined(); expect(res).toBeDefined();
expect(res).not.toBeNull(); expect(res).not.toBeNull();
@@ -70,7 +62,7 @@ describe('Activiti ServiceTaskList Cloud Service', () => {
it('should concat the app name to the request url', (done) => { it('should concat the app name to the request url', (done) => {
const taskRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service' } as ServiceTaskQueryCloudRequestModel; const taskRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service' } as ServiceTaskQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallUrl); requestSpy.and.callFake(returnCallUrl);
service.getServiceTaskByRequest(taskRequest).subscribe((requestUrl) => { service.getServiceTaskByRequest(taskRequest).subscribe((requestUrl) => {
expect(requestUrl).toBeDefined(); expect(requestUrl).toBeDefined();
expect(requestUrl).not.toBeNull(); expect(requestUrl).not.toBeNull();
@@ -84,7 +76,7 @@ describe('Activiti ServiceTaskList Cloud Service', () => {
appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service', appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service',
sorting: [{ orderBy: 'NAME', direction: 'DESC' }, { orderBy: 'TITLE', direction: 'ASC' }] sorting: [{ orderBy: 'NAME', direction: 'DESC' }, { orderBy: 'TITLE', direction: 'ASC' }]
} as ServiceTaskQueryCloudRequestModel; } as ServiceTaskQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallQueryParameters); requestSpy.and.callFake(returnCallQueryParameters);
service.getServiceTaskByRequest(taskRequest).subscribe((res) => { service.getServiceTaskByRequest(taskRequest).subscribe((res) => {
expect(res).toBeDefined(); expect(res).toBeDefined();
expect(res).not.toBeNull(); expect(res).not.toBeNull();
@@ -95,7 +87,7 @@ describe('Activiti ServiceTaskList Cloud Service', () => {
it('should return an error when app name is not specified', (done) => { it('should return an error when app name is not specified', (done) => {
const taskRequest = { appName: null } as ServiceTaskQueryCloudRequestModel; const taskRequest = { appName: null } as ServiceTaskQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallUrl); requestSpy.and.callFake(returnCallUrl);
service.getServiceTaskByRequest(taskRequest).subscribe( service.getServiceTaskByRequest(taskRequest).subscribe(
() => { }, () => { },
(error) => { (error) => {
@@ -111,7 +103,7 @@ describe('Activiti ServiceTaskList Cloud Service', () => {
beforeEach(() => { beforeEach(() => {
spyOn(service, 'getBasePath').and.returnValue('http://localhost/fakeName'); spyOn(service, 'getBasePath').and.returnValue('http://localhost/fakeName');
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallUrl); requestSpy.and.callFake(returnCallUrl);
logServiceErrorSpy = spyOn(logService, 'error'); logServiceErrorSpy = spyOn(logService, 'error');
}); });

View File

@@ -16,31 +16,22 @@
*/ */
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import { setupTestBed, AlfrescoApiService } from '@alfresco/adf-core'; import { setupTestBed } from '@alfresco/adf-core';
import { TaskListCloudService } from './task-list-cloud.service'; import { TaskListCloudService } from './task-list-cloud.service';
import { TaskQueryCloudRequestModel } from '../../../models/filter-cloud-model'; import { TaskQueryCloudRequestModel } from '../../../models/filter-cloud-model';
import { ProcessServiceCloudTestingModule } from '../../../testing/process-service-cloud.testing.module'; import { ProcessServiceCloudTestingModule } from '../../../testing/process-service-cloud.testing.module';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { AdfHttpClient } from '@alfresco/adf-core/api';
describe('TaskListCloudService', () => { describe('TaskListCloudService', () => {
let service: TaskListCloudService; let service: TaskListCloudService;
let alfrescoApiService: AlfrescoApiService; let adfHttpClient: AdfHttpClient;
let requestSpy: jasmine.Spy;
const returnCallQueryParameters = (): any => ({ const returnCallQueryParameters = (_queryUrl, options) => Promise.resolve(options.queryParams);
oauth2Auth: {
callCustomApi : (_queryUrl, _operation, _context, queryParams) => Promise.resolve(queryParams)
},
isEcmLoggedIn: () => false,
reply: jasmine.createSpy('reply')
});
const returnCallUrl = (): any => ({ const returnCallUrl = (queryUrl) => Promise.resolve(queryUrl);
oauth2Auth: {
callCustomApi : (queryUrl) => Promise.resolve(queryUrl)
},
isEcmLoggedIn: () => false
});
setupTestBed({ setupTestBed({
imports: [ imports: [
@@ -50,13 +41,14 @@ describe('TaskListCloudService', () => {
}); });
beforeEach(() => { beforeEach(() => {
alfrescoApiService = TestBed.inject(AlfrescoApiService); adfHttpClient = TestBed.inject(AdfHttpClient);
service = TestBed.inject(TaskListCloudService); service = TestBed.inject(TaskListCloudService);
requestSpy = spyOn(adfHttpClient, 'request');
}); });
it('should append to the call all the parameters', (done) => { it('should append to the call all the parameters', (done) => {
const taskRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service' } as TaskQueryCloudRequestModel; const taskRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service' } as TaskQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallQueryParameters); requestSpy.and.callFake(returnCallQueryParameters);
service.getTaskByRequest(taskRequest).subscribe((res) => { service.getTaskByRequest(taskRequest).subscribe((res) => {
expect(res).toBeDefined(); expect(res).toBeDefined();
expect(res).not.toBeNull(); expect(res).not.toBeNull();
@@ -69,7 +61,7 @@ describe('TaskListCloudService', () => {
it('should concat the app name to the request url', (done) => { it('should concat the app name to the request url', (done) => {
const taskRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service' } as TaskQueryCloudRequestModel; const taskRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service' } as TaskQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallUrl); requestSpy.and.callFake(returnCallUrl);
service.getTaskByRequest(taskRequest).subscribe((requestUrl) => { service.getTaskByRequest(taskRequest).subscribe((requestUrl) => {
expect(requestUrl).toBeDefined(); expect(requestUrl).toBeDefined();
expect(requestUrl).not.toBeNull(); expect(requestUrl).not.toBeNull();
@@ -81,7 +73,7 @@ describe('TaskListCloudService', () => {
it('should concat the sorting to append as parameters', (done) => { it('should concat the sorting to append as parameters', (done) => {
const taskRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service', const taskRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service',
sorting: [{ orderBy: 'NAME', direction: 'DESC'}, { orderBy: 'TITLE', direction: 'ASC'}] } as TaskQueryCloudRequestModel; sorting: [{ orderBy: 'NAME', direction: 'DESC'}, { orderBy: 'TITLE', direction: 'ASC'}] } as TaskQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallQueryParameters); requestSpy.and.callFake(returnCallQueryParameters);
service.getTaskByRequest(taskRequest).subscribe((res) => { service.getTaskByRequest(taskRequest).subscribe((res) => {
expect(res).toBeDefined(); expect(res).toBeDefined();
expect(res).not.toBeNull(); expect(res).not.toBeNull();
@@ -92,7 +84,7 @@ describe('TaskListCloudService', () => {
it('should return an error when app name is not specified', (done) => { it('should return an error when app name is not specified', (done) => {
const taskRequest = { appName: null } as TaskQueryCloudRequestModel; const taskRequest = { appName: null } as TaskQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallUrl); requestSpy.and.callFake(returnCallUrl);
service.getTaskByRequest(taskRequest).subscribe( service.getTaskByRequest(taskRequest).subscribe(
() => { }, () => { },
(error) => { (error) => {

14130
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -84,8 +84,8 @@
"dotenv-expand": "^5.1.0", "dotenv-expand": "^5.1.0",
"editorjs-html": "3.4.2", "editorjs-html": "3.4.2",
"editorjs-paragraph-with-alignment": "3.0.0", "editorjs-paragraph-with-alignment": "3.0.0",
"event-emitter": "^0.3.5",
"material-icons": "^1.13.8", "material-icons": "^1.13.8",
"minimatch": "^9.0.0",
"minimatch-browser": "1.0.0", "minimatch-browser": "1.0.0",
"monaco-editor": "^0.33.0", "monaco-editor": "^0.33.0",
"ng2-charts": "^4.1.1", "ng2-charts": "^4.1.1",
@@ -121,6 +121,7 @@
"@storybook/angular": "6.5.16", "@storybook/angular": "6.5.16",
"@storybook/builder-webpack5": "6.5.10", "@storybook/builder-webpack5": "6.5.10",
"@storybook/manager-webpack5": "6.5.10", "@storybook/manager-webpack5": "6.5.10",
"@types/event-emitter": "^0.3.3",
"@types/jasmine": "4.0.3", "@types/jasmine": "4.0.3",
"@types/jasminewd2": "~2.0.2", "@types/jasminewd2": "~2.0.2",
"@types/minimatch": "^3.0.3", "@types/minimatch": "^3.0.3",