[AAE-2718] List available roles for a group (#5954)

* oath2 api service, cleanup identity users service

* cleanup groups service

* get awailable role mappings

* cleanup tests and mocks

* fix lint
This commit is contained in:
Denys Vuika
2020-08-06 11:01:03 +01:00
committed by GitHub
parent 700c06521b
commit 486a002023
5 changed files with 229 additions and 549 deletions

View File

@@ -18,55 +18,39 @@
import { IdentityGroupModel, IdentityGroupCountModel } from '../models/identity-group.model'; import { IdentityGroupModel, IdentityGroupCountModel } from '../models/identity-group.model';
import { IdentityRoleModel } from '../models/identity-role.model'; import { IdentityRoleModel } from '../models/identity-role.model';
export let mockIdentityGroup1 = <IdentityGroupModel> { export const mockIdentityGroup1 = <IdentityGroupModel> {
id: 'mock-group-id-1', name: 'Mock Group 1', path: '/mock', subGroups: [] id: 'mock-group-id-1', name: 'Mock Group 1', path: '/mock', subGroups: []
}; };
export let mockIdentityGroup2 = <IdentityGroupModel> { export const mockIdentityGroup2 = <IdentityGroupModel> {
id: 'mock-group-id-2', name: 'Mock Group 2', path: '', subGroups: [] id: 'mock-group-id-2', name: 'Mock Group 2', path: '', subGroups: []
}; };
export let mockIdentityGroup3 = <IdentityGroupModel> { export const mockIdentityGroup3 = <IdentityGroupModel> {
id: 'mock-group-id-3', name: 'Mock Group 3', path: '', subGroups: [] id: 'mock-group-id-3', name: 'Mock Group 3', path: '', subGroups: []
}; };
export let mockIdentityGroup4 = <IdentityGroupModel> { export const mockIdentityGroup4 = <IdentityGroupModel> {
id: 'mock-group-id-4', name: 'Mock Group 4', path: '', subGroups: [] id: 'mock-group-id-4', name: 'Mock Group 4', path: '', subGroups: []
}; };
export let mockIdentityGroup5 = <IdentityGroupModel> { export const mockIdentityGroup5 = <IdentityGroupModel> {
id: 'mock-group-id-5', name: 'Mock Group 5', path: '', subGroups: [] id: 'mock-group-id-5', name: 'Mock Group 5', path: '', subGroups: []
}; };
export let mockIdentityGroupsCount = <IdentityGroupCountModel> { count: 10 }; export const mockIdentityGroupsCount = <IdentityGroupCountModel> { count: 10 };
export let mockIdentityGroups = [ export const mockIdentityGroups = [
mockIdentityGroup1, mockIdentityGroup2, mockIdentityGroup3, mockIdentityGroup4, mockIdentityGroup5 mockIdentityGroup1, mockIdentityGroup2, mockIdentityGroup3, mockIdentityGroup4, mockIdentityGroup5
]; ];
export let mockApplicationDetails = {id: 'mock-app-id', name: 'mock-app-name'}; export const mockApplicationDetails = {id: 'mock-app-id', name: 'mock-app-name'};
export let groupAPIMockError = { export const roleMappingMock = [
error: {
errorKey: 'failed',
statusCode: 400,
stackTrace: 'For security reasons the stack trace is no longer displayed, but the property is kept for previous versions.'
}
};
export let mockApiError = {
oauth2Auth: {
callCustomApi: () => {
return Promise.reject(groupAPIMockError);
}
}
};
export let roleMappingMock = [
{ id: 'role-id-1', name: 'role-name-1' }, { id: 'role-id-2', name: 'role-name-2' } { id: 'role-id-1', name: 'role-name-1' }, { id: 'role-id-2', name: 'role-name-2' }
]; ];
export let roleMappingApi = { export const roleMappingApi = {
oauth2Auth: { oauth2Auth: {
callCustomApi: () => { callCustomApi: () => {
return Promise.resolve(roleMappingMock); return Promise.resolve(roleMappingMock);
@@ -74,7 +58,7 @@ export let roleMappingApi = {
} }
}; };
export let noRoleMappingApi = { export const noRoleMappingApi = {
oauth2Auth: { oauth2Auth: {
callCustomApi: () => { callCustomApi: () => {
return Promise.resolve([]); return Promise.resolve([]);
@@ -82,7 +66,7 @@ export let noRoleMappingApi = {
} }
}; };
export let groupsMockApi = { export const groupsMockApi = {
oauth2Auth: { oauth2Auth: {
callCustomApi: () => { callCustomApi: () => {
return Promise.resolve(mockIdentityGroups); return Promise.resolve(mockIdentityGroups);
@@ -90,23 +74,7 @@ export let groupsMockApi = {
} }
}; };
export let getGroupsCountMockApi = { export const createGroupMappingApi = {
oauth2Auth: {
callCustomApi: () => {
return Promise.resolve(10);
}
}
};
export let queryGroupsMockApi = {
oauth2Auth: {
callCustomApi: () => {
return Promise.resolve(mockIdentityGroups);
}
}
};
export let createGroupMappingApi = {
oauth2Auth: { oauth2Auth: {
callCustomApi: () => { callCustomApi: () => {
return Promise.resolve(); return Promise.resolve();
@@ -114,7 +82,7 @@ export let createGroupMappingApi = {
} }
}; };
export let updateGroupMappingApi = { export const updateGroupMappingApi = {
oauth2Auth: { oauth2Auth: {
callCustomApi: () => { callCustomApi: () => {
return Promise.resolve(); return Promise.resolve();
@@ -122,7 +90,7 @@ export let updateGroupMappingApi = {
} }
}; };
export let deleteGroupMappingApi = { export const deleteGroupMappingApi = {
oauth2Auth: { oauth2Auth: {
callCustomApi: () => { callCustomApi: () => {
return Promise.resolve(); return Promise.resolve();
@@ -130,23 +98,7 @@ export let deleteGroupMappingApi = {
} }
}; };
export let returnCallQueryParameters = { export const applicationDetailsMockApi = {
oauth2Auth: {
callCustomApi: (_queryUrl, _operation, _context, queryParams) => {
return Promise.resolve(queryParams);
}
}
};
export let returnCallUrl = {
oauth2Auth: {
callCustomApi: (queryUrl) => {
return Promise.resolve(queryUrl);
}
}
};
export let applicationDetailsMockApi = {
oauth2Auth: { oauth2Auth: {
callCustomApi: () => { callCustomApi: () => {
return Promise.resolve([mockApplicationDetails]); return Promise.resolve([mockApplicationDetails]);
@@ -154,10 +106,10 @@ export let applicationDetailsMockApi = {
} }
}; };
export let mockIdentityRoles = [ export const mockIdentityRoles = [
new IdentityRoleModel({id: 'mock-role-id', name: 'MOCK-ADMIN-ROLE'}), new IdentityRoleModel({id: 'mock-role-id', name: 'MOCK-ADMIN-ROLE'}),
new IdentityRoleModel({id: 'mock-role-id', name: 'MOCK-USER-ROLE'}), new IdentityRoleModel({id: 'mock-role-id', name: 'MOCK-USER-ROLE'}),
new IdentityRoleModel({id: 'mock-role-id', name: 'MOCK-ROLE-1'}) new IdentityRoleModel({id: 'mock-role-id', name: 'MOCK-ROLE-1'})
]; ];
export let clientRoles = [ 'MOCK-ADMIN-ROLE', 'MOCK-USER-ROLE']; export const clientRoles = [ 'MOCK-ADMIN-ROLE', 'MOCK-USER-ROLE'];

View File

@@ -16,14 +16,7 @@
*/ */
import { async, TestBed } from '@angular/core/testing'; import { async, TestBed } from '@angular/core/testing';
import { import { setupTestBed, AlfrescoApiService, IdentityGroupService, IdentityGroupSearchParam } from '@alfresco/adf-core';
setupTestBed,
AlfrescoApiService,
LogService,
IdentityGroupService,
IdentityGroupSearchParam,
groupAPIMockError
} from '@alfresco/adf-core';
import { HttpErrorResponse } from '@angular/common/http'; import { HttpErrorResponse } from '@angular/common/http';
import { throwError, of } from 'rxjs'; import { throwError, of } from 'rxjs';
import { import {
@@ -33,7 +26,6 @@ import {
roleMappingApi, roleMappingApi,
clientRoles, clientRoles,
applicationDetailsMockApi, applicationDetailsMockApi,
mockApiError,
mockIdentityGroup1, mockIdentityGroup1,
createGroupMappingApi, createGroupMappingApi,
updateGroupMappingApi, updateGroupMappingApi,
@@ -46,7 +38,6 @@ import { TranslateModule } from '@ngx-translate/core';
describe('IdentityGroupService', () => { describe('IdentityGroupService', () => {
let service: IdentityGroupService; let service: IdentityGroupService;
let apiService: AlfrescoApiService; let apiService: AlfrescoApiService;
let logService: LogService;
setupTestBed({ setupTestBed({
imports: [ imports: [
@@ -58,7 +49,6 @@ describe('IdentityGroupService', () => {
beforeEach(async(() => { beforeEach(async(() => {
service = TestBed.inject(IdentityGroupService); service = TestBed.inject(IdentityGroupService);
apiService = TestBed.inject(AlfrescoApiService); apiService = TestBed.inject(AlfrescoApiService);
logService = TestBed.inject(LogService);
})); }));
it('should be able to fetch groups based on group name', (done) => { it('should be able to fetch groups based on group name', (done) => {
@@ -231,18 +221,6 @@ describe('IdentityGroupService', () => {
); );
}); });
it('should return only the properties of IdentityGroupSearchParam', (done) => {
spyOn(apiService, 'getInstance').and.returnValue(groupsMockApi);
service.findGroupsByName(<IdentityGroupSearchParam> {name: 'mock'}).subscribe((groups) => {
expect(groups).toBeDefined();
expect(groups).toBeDefined();
expect(groups[0].id).toEqual('mock-group-id-1');
expect(groups[0].name).toEqual('Mock Group 1');
expect(groups[0]['subGroups']).not.toBeDefined();
done();
});
});
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); spyOn(apiService, 'getInstance').and.returnValue(applicationDetailsMockApi);
service.getClientIdByApplicationName('mock-app-name').subscribe((clientId) => { service.getClientIdByApplicationName('mock-app-name').subscribe((clientId) => {
@@ -253,25 +231,9 @@ describe('IdentityGroupService', () => {
}); });
}); });
it('should notify errors returned from the API', (done) => {
const logServiceSpy = spyOn(logService, 'error').and.callThrough();
spyOn(apiService, 'getInstance').and.returnValue(mockApiError);
service.findGroupsByName(<IdentityGroupSearchParam> {name: 'mock'}).subscribe(
() => {},
(res: any) => {
expect(res).toBeDefined();
expect(res).toEqual(groupAPIMockError);
expect(logServiceSpy).toHaveBeenCalled();
done();
}
);
});
it('should be able to all fetch groups', (done) => { it('should be able to all fetch groups', (done) => {
spyOn(apiService, 'getInstance').and.returnValue(groupsMockApi); spyOn(apiService, 'getInstance').and.returnValue(groupsMockApi);
service.getGroups().subscribe((res) => { service.getGroups().subscribe((res) => {
expect(res).toBeDefined();
expect(res).not.toBeNull();
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');
expect(res[0].name).toBe('Mock Group 1'); expect(res[0].name).toBe('Mock Group 1');

View File

@@ -16,11 +16,9 @@
*/ */
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { Observable, of, from, throwError } from 'rxjs'; import { Observable, of } from 'rxjs';
import { catchError, map, switchMap } from 'rxjs/operators'; import { map, switchMap } from 'rxjs/operators';
import { AppConfigService } from '../app-config/app-config.service'; import { AppConfigService } from '../app-config/app-config.service';
import { AlfrescoApiService } from './alfresco-api.service';
import { LogService } from './log.service';
import { import {
IdentityGroupSearchParam, IdentityGroupSearchParam,
IdentityGroupQueryCloudRequestModel, IdentityGroupQueryCloudRequestModel,
@@ -29,35 +27,37 @@ import {
IdentityGroupCountModel IdentityGroupCountModel
} from '../models/identity-group.model'; } from '../models/identity-group.model';
import { IdentityRoleModel } from '../models/identity-role.model'; import { IdentityRoleModel } from '../models/identity-role.model';
import { OAuth2Service } from './oauth2.service';
@Injectable({ @Injectable({ providedIn: 'root' })
providedIn: 'root'
})
export class IdentityGroupService { export class IdentityGroupService {
constructor( constructor(
private alfrescoApiService: AlfrescoApiService, private oAuth2Service: OAuth2Service,
private appConfigService: AppConfigService, private appConfigService: AppConfigService
private logService: LogService
) {} ) {}
private get identityHost(): string {
return `${this.appConfigService.get('identityHost')}`;
}
/** /**
* Gets all groups. * Gets all groups.
* @returns Array of group information objects * @returns Array of group information objects
*/ */
getGroups(): Observable<IdentityGroupModel[]> { getGroups(): Observable<IdentityGroupModel[]> {
const url = this.getGroupsApi(); const url = `${this.identityHost}/groups`;
const httpMethod = 'GET', pathParams = {}, return this.oAuth2Service.get({ url });
queryParams = {}, bodyParam = {}, headerParams = {}, }
formParams = {}, authNames = [], contentTypes = ['application/json'];
return from(this.alfrescoApiService.getInstance().oauth2Auth.callCustomApi( /**
url, httpMethod, pathParams, queryParams, * Gets available roles
headerParams, formParams, bodyParam, authNames, * @param groupId Id of the group.
contentTypes, null, null, null * @returns Array of available roles information objects
)).pipe( */
catchError((error) => this.handleError(error)) getAvailableRoles(groupId: string): Observable<IdentityRoleModel[]> {
); const url = `${this.identityHost}/groups/${groupId}/role-mappings/realm/available`;
return this.oAuth2Service.get({ url });
} }
/** /**
@@ -65,18 +65,13 @@ export class IdentityGroupService {
* @returns Array of user information objects * @returns Array of user information objects
*/ */
queryGroups(requestQuery: IdentityGroupQueryCloudRequestModel): Observable<IdentityGroupQueryResponse> { queryGroups(requestQuery: IdentityGroupQueryCloudRequestModel): Observable<IdentityGroupQueryResponse> {
const url = this.getGroupsApi(); const url = `${this.identityHost}/groups`;
const httpMethod = 'GET', pathParams = {}, const queryParams = { first: requestQuery.first || 0, max: requestQuery.max || 5 };
queryParams = { first: requestQuery.first || 0, max: requestQuery.max || 5 }, bodyParam = {}, headerParams = {},
formParams = {}, authNames = [], contentTypes = ['application/json'];
return this.getTotalGroupsCount().pipe( return this.getTotalGroupsCount().pipe(
switchMap((totalCount: IdentityGroupCountModel) => switchMap((totalCount: IdentityGroupCountModel) =>
from(this.alfrescoApiService.getInstance().oauth2Auth.callCustomApi( this.oAuth2Service.get<any[]>({ url, queryParams }).pipe(
url, httpMethod, pathParams, queryParams, map((response) => {
headerParams, formParams, bodyParam, authNames,
contentTypes, null, null, null)
).pipe(
map((response: any[]) => {
return <IdentityGroupQueryResponse> { return <IdentityGroupQueryResponse> {
entries: response, entries: response,
pagination: { pagination: {
@@ -87,8 +82,7 @@ export class IdentityGroupService {
totalItems: totalCount.count totalItems: totalCount.count
} }
}; };
}), })
catchError((error) => this.handleError(error))
)) ))
); );
} }
@@ -98,15 +92,8 @@ export class IdentityGroupService {
* @returns Number of groups count. * @returns Number of groups count.
*/ */
getTotalGroupsCount(): Observable<IdentityGroupCountModel> { getTotalGroupsCount(): Observable<IdentityGroupCountModel> {
const url = this.getGroupsApi() + `/count`; const url = `${this.identityHost}/groups/count`;
const contentTypes = ['application/json'], accepts = ['application/json']; return this.oAuth2Service.get({ url });
return from(this.alfrescoApiService.getInstance()
.oauth2Auth.callCustomApi(url, 'GET',
null, null, null,
null, null, contentTypes,
accepts, null, null, null)).pipe(
catchError((error) => this.handleError(error))
);
} }
/** /**
@@ -115,17 +102,10 @@ export class IdentityGroupService {
* @returns Empty response when the group created. * @returns Empty response when the group created.
*/ */
createGroup(newGroup: IdentityGroupModel): Observable<any> { createGroup(newGroup: IdentityGroupModel): Observable<any> {
const url = this.getGroupsApi(); const url = `${this.identityHost}/groups`;
const httpMethod = 'POST', pathParams = {}, queryParams = {}, bodyParam = newGroup, headerParams = {}, const bodyParam = newGroup;
formParams = {}, contentTypes = ['application/json'], accepts = ['application/json'];
return from(this.alfrescoApiService.getInstance().oauth2Auth.callCustomApi( return this.oAuth2Service.post({ url, bodyParam });
url, httpMethod, pathParams, queryParams,
headerParams, formParams, bodyParam,
contentTypes, accepts, null, null, null
)).pipe(
catchError((error) => this.handleError(error))
);
} }
/** /**
@@ -135,18 +115,10 @@ export class IdentityGroupService {
* @returns Empty response when the group updated. * @returns Empty response when the group updated.
*/ */
updateGroup(groupId: string, updatedGroup: IdentityGroupModel): Observable<any> { updateGroup(groupId: string, updatedGroup: IdentityGroupModel): Observable<any> {
const url = this.getGroupsApi() + `/${groupId}`; const url = `${this.identityHost}/groups/${groupId}`;
const request = JSON.stringify(updatedGroup); const bodyParam = JSON.stringify(updatedGroup);
const httpMethod = 'PUT', pathParams = {} , queryParams = {}, bodyParam = request, headerParams = {},
formParams = {}, contentTypes = ['application/json'], accepts = ['application/json'];
return from(this.alfrescoApiService.getInstance().oauth2Auth.callCustomApi( return this.oAuth2Service.put({ url, bodyParam });
url, httpMethod, pathParams, queryParams,
headerParams, formParams, bodyParam,
contentTypes, accepts, null, null, null
)).pipe(
catchError((error) => this.handleError(error))
);
} }
/** /**
@@ -155,17 +127,8 @@ export class IdentityGroupService {
* @returns Empty response when the group deleted. * @returns Empty response when the group deleted.
*/ */
deleteGroup(groupId: string): Observable<any> { deleteGroup(groupId: string): Observable<any> {
const url = this.getGroupsApi() + `/${groupId}`; const url = `${this.identityHost}/groups/${groupId}`;
const httpMethod = 'DELETE', pathParams = {} , queryParams = {}, bodyParam = {}, headerParams = {}, return this.oAuth2Service.delete({ url });
formParams = {}, contentTypes = ['application/json'], accepts = ['application/json'];
return from(this.alfrescoApiService.getInstance().oauth2Auth.callCustomApi(
url, httpMethod, pathParams, queryParams,
headerParams, formParams, bodyParam,
contentTypes, accepts, null, null, null
)).pipe(
catchError((error) => this.handleError(error))
);
} }
/** /**
@@ -177,22 +140,10 @@ export class IdentityGroupService {
if (searchParams.name === '') { if (searchParams.name === '') {
return of([]); return of([]);
} }
const url = this.getGroupsApi(); const url = `${this.identityHost}/groups`;
const httpMethod = 'GET', pathParams = {}, queryParams = {search: searchParams.name}, bodyParam = {}, headerParams = {}, const queryParams = { search: searchParams.name };
formParams = {}, contentTypes = ['application/json'], accepts = ['application/json'];
return from(this.alfrescoApiService.getInstance().oauth2Auth.callCustomApi( return this.oAuth2Service.get({ url, queryParams });
url, httpMethod, pathParams, queryParams,
headerParams, formParams, bodyParam,
contentTypes, accepts, Object, null, null)
).pipe(
map((response: []) => {
return response.map( (group: IdentityGroupModel) => {
return {id: group.id, name: group.name};
});
}),
catchError((err) => this.handleError(err))
);
} }
/** /**
@@ -202,16 +153,7 @@ export class IdentityGroupService {
*/ */
getGroupRoles(groupId: string): Observable<IdentityRoleModel[]> { getGroupRoles(groupId: string): Observable<IdentityRoleModel[]> {
const url = this.buildRolesUrl(groupId); const url = this.buildRolesUrl(groupId);
const httpMethod = 'GET', pathParams = {}, queryParams = {}, bodyParam = {}, headerParams = {}, return this.oAuth2Service.get({ url });
formParams = {}, contentTypes = ['application/json'], accepts = ['application/json'];
return (from(this.alfrescoApiService.getInstance().oauth2Auth.callCustomApi(
url, httpMethod, pathParams, queryParams,
headerParams, formParams, bodyParam,
contentTypes, accepts, Object, null, null)
)).pipe(
catchError((error) => this.handleError(error))
);
} }
/** /**
@@ -221,13 +163,11 @@ export class IdentityGroupService {
* @returns True if the group has one or more of the roles, false otherwise * @returns True if the group has one or more of the roles, false otherwise
*/ */
checkGroupHasRole(groupId: string, roleNames: string[]): Observable<boolean> { checkGroupHasRole(groupId: string, roleNames: string[]): Observable<boolean> {
return this.getGroupRoles(groupId).pipe(map((groupRoles: IdentityRoleModel[]) => { return this.getGroupRoles(groupId).pipe(map((groupRoles) => {
let hasRole = false; let hasRole = false;
if (groupRoles && groupRoles.length > 0) { if (groupRoles && groupRoles.length > 0) {
roleNames.forEach((roleName: string) => { roleNames.forEach((roleName: string) => {
const role = groupRoles.find((groupRole) => { const role = groupRoles.find(({ name }) => roleName === name);
return roleName === groupRole.name;
});
if (role) { if (role) {
hasRole = true; hasRole = true;
return; return;
@@ -244,19 +184,11 @@ export class IdentityGroupService {
* @returns client Id string * @returns client Id string
*/ */
getClientIdByApplicationName(applicationName: string): Observable<string> { getClientIdByApplicationName(applicationName: string): Observable<string> {
const url = this.getApplicationIdApi(); const url = `${this.identityHost}/clients`;
const httpMethod = 'GET', pathParams = {}, queryParams = {clientId: applicationName}, bodyParam = {}, headerParams = {}, formParams = {}, const queryParams = {clientId: applicationName};
contentTypes = ['application/json'], accepts = ['application/json'];
return from(this.alfrescoApiService.getInstance() return this.oAuth2Service.get<any[]>({ url, queryParams }).pipe(
.oauth2Auth.callCustomApi(url, httpMethod, pathParams, queryParams, headerParams, map((response) => response && response.length > 0 ? response[0].id : '')
formParams, bodyParam, contentTypes,
accepts, Object, null, null)
).pipe(
map((response: any[]) => {
const clientId = response && response.length > 0 ? response[0].id : '';
return clientId;
}),
catchError((error) => this.handleError(error))
); );
} }
@@ -267,15 +199,8 @@ export class IdentityGroupService {
* @returns List of roles * @returns List of roles
*/ */
getClientRoles(groupId: string, clientId: string): Observable<IdentityRoleModel[]> { getClientRoles(groupId: string, clientId: string): Observable<IdentityRoleModel[]> {
const url = this.groupClientRoleMappingApi(groupId, clientId); const url = `${this.identityHost}/groups/${groupId}/role-mappings/clients/${clientId}`;
const httpMethod = 'GET', pathParams = {}, queryParams = {}, bodyParam = {}, headerParams = {}, return this.oAuth2Service.get({ url });
formParams = {}, contentTypes = ['application/json'], accepts = ['application/json'];
return from(this.alfrescoApiService.getInstance().oauth2Auth.callCustomApi(
url, httpMethod, pathParams, queryParams,
headerParams, formParams, bodyParam,
contentTypes, accepts, Object, null, null)
);
} }
/** /**
@@ -286,10 +211,7 @@ export class IdentityGroupService {
*/ */
checkGroupHasClientApp(groupId: string, clientId: string): Observable<boolean> { checkGroupHasClientApp(groupId: string, clientId: string): Observable<boolean> {
return this.getClientRoles(groupId, clientId).pipe( return this.getClientRoles(groupId, clientId).pipe(
map((response: any[]) => { map((response) => response && response.length > 0)
return response && response.length > 0;
}),
catchError((error) => this.handleError(error))
); );
} }
@@ -306,9 +228,7 @@ export class IdentityGroupService {
let hasRole = false; let hasRole = false;
if (clientRoles.length > 0) { if (clientRoles.length > 0) {
roleNames.forEach((roleName) => { roleNames.forEach((roleName) => {
const role = clientRoles.find((availableRole) => { const role = clientRoles.find(({ name }) => name === roleName);
return availableRole.name === roleName;
});
if (role) { if (role) {
hasRole = true; hasRole = true;
@@ -317,33 +237,11 @@ export class IdentityGroupService {
}); });
} }
return hasRole; return hasRole;
}), })
catchError((error) => this.handleError(error))
); );
} }
private groupClientRoleMappingApi(groupId: string, clientId: string): string {
return `${this.appConfigService.get('identityHost')}/groups/${groupId}/role-mappings/clients/${clientId}`;
}
private getApplicationIdApi(): string {
return `${this.appConfigService.get('identityHost')}/clients`;
}
private getGroupsApi(): string {
return `${this.appConfigService.get('identityHost')}/groups`;
}
private buildRolesUrl(groupId: string): string { private buildRolesUrl(groupId: string): string {
return `${this.appConfigService.get('identityHost')}/groups/${groupId}/role-mappings/realm/composite`; return `${this.identityHost}/groups/${groupId}/role-mappings/realm/composite`;
}
/**
* Throw the error
* @param error
*/
private handleError(error: Response) {
this.logService.error(error);
return throwError(error || 'Server error');
} }
} }

View File

@@ -17,15 +17,14 @@
import { Pagination } from '@alfresco/js-api'; import { Pagination } from '@alfresco/js-api';
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { from, Observable, of, throwError } from 'rxjs'; import { Observable, of } from 'rxjs';
import { catchError, map, switchMap } from 'rxjs/operators'; import { map, switchMap } from 'rxjs/operators';
import { AppConfigService } from '../app-config/app-config.service'; import { AppConfigService } from '../app-config/app-config.service';
import { IdentityGroupModel } from '../models/identity-group.model'; import { IdentityGroupModel } from '../models/identity-group.model';
import { IdentityRoleModel } from '../models/identity-role.model'; import { IdentityRoleModel } from '../models/identity-role.model';
import { IdentityUserModel } from '../models/identity-user.model'; import { IdentityUserModel } from '../models/identity-user.model';
import { AlfrescoApiService } from './alfresco-api.service';
import { JwtHelperService } from './jwt-helper.service'; import { JwtHelperService } from './jwt-helper.service';
import { LogService } from './log.service'; import { OAuth2Service } from './oauth2.service';
export interface IdentityUserQueryResponse { export interface IdentityUserQueryResponse {
@@ -57,9 +56,16 @@ export class IdentityUserService {
constructor( constructor(
private jwtHelperService: JwtHelperService, private jwtHelperService: JwtHelperService,
private alfrescoApiService: AlfrescoApiService, private oAuth2Service: OAuth2Service,
private appConfigService: AppConfigService, private appConfigService: AppConfigService) { }
private logService: LogService) { }
private get identityHost(): string {
return `${this.appConfigService.get('identityHost')}`;
}
private buildUserUrl(): string {
return `${this.identityHost}/users`;
}
/** /**
* Gets the name and other basic details of the current user. * Gets the name and other basic details of the current user.
@@ -83,21 +89,9 @@ export class IdentityUserService {
return of([]); return of([]);
} }
const url = this.buildUserUrl(); const url = this.buildUserUrl();
const httpMethod = 'GET', pathParams = {}, queryParams = { search: search }, bodyParam = {}, headerParams = {}, const queryParams = { search: search };
formParams = {}, contentTypes = ['application/json'], accepts = ['application/json'];
return from(this.alfrescoApiService.getInstance().oauth2Auth.callCustomApi( return this.oAuth2Service.get({ url, queryParams });
url, httpMethod, pathParams, queryParams,
headerParams, formParams, bodyParam,
contentTypes, accepts, Object, null, null)
).pipe(
map((response: []) => {
return response.map( (user: IdentityUserModel) => {
return {id: user.id, firstName: user.firstName, lastName: user.lastName, email: user.email, username: user.username};
});
}),
catchError((err) => this.handleError(err))
);
} }
/** /**
@@ -110,21 +104,9 @@ export class IdentityUserService {
return of([]); return of([]);
} }
const url = this.buildUserUrl(); const url = this.buildUserUrl();
const httpMethod = 'GET', pathParams = {}, queryParams = { username: username }, bodyParam = {}, headerParams = {}, const queryParams = { username: username };
formParams = {}, contentTypes = ['application/json'], accepts = ['application/json'];
return from(this.alfrescoApiService.getInstance().oauth2Auth.callCustomApi( return this.oAuth2Service.get({url, queryParams });
url, httpMethod, pathParams, queryParams,
headerParams, formParams, bodyParam,
contentTypes, accepts, Object, null, null)
).pipe(
map((response: []) => {
return response.map( (user: IdentityUserModel) => {
return {id: user.id, firstName: user.firstName, lastName: user.lastName, email: user.email, username: user.username};
});
}),
catchError((err) => this.handleError(err))
);
} }
/** /**
@@ -137,21 +119,9 @@ export class IdentityUserService {
return of([]); return of([]);
} }
const url = this.buildUserUrl(); const url = this.buildUserUrl();
const httpMethod = 'GET', pathParams = {}, queryParams = { email: email }, bodyParam = {}, headerParams = {}, const queryParams = { email: email };
formParams = {}, contentTypes = ['application/json'], accepts = ['application/json'];
return from(this.alfrescoApiService.getInstance().oauth2Auth.callCustomApi( return this.oAuth2Service.get({ url, queryParams });
url, httpMethod, pathParams, queryParams,
headerParams, formParams, bodyParam,
contentTypes, accepts, Object, null, null)
).pipe(
map((response: []) => {
return response.map( (user: IdentityUserModel) => {
return {id: user.id, firstName: user.firstName, lastName: user.lastName, email: user.email, username: user.username};
});
}),
catchError((err) => this.handleError(err))
);
} }
/** /**
@@ -164,14 +134,7 @@ export class IdentityUserService {
return of([]); return of([]);
} }
const url = this.buildUserUrl() + '/' + id; const url = this.buildUserUrl() + '/' + id;
const httpMethod = 'GET', pathParams = {}, queryParams = {}, bodyParam = {}, headerParams = {}, return this.oAuth2Service.get({ url });
formParams = {}, contentTypes = ['application/json'], accepts = ['application/json'];
return (from(this.alfrescoApiService.getInstance().oauth2Auth.callCustomApi(
url, httpMethod, pathParams, queryParams,
headerParams, formParams, bodyParam,
contentTypes, accepts, Object, null, null)
));
} }
/** /**
@@ -181,15 +144,8 @@ export class IdentityUserService {
* @returns List of client roles * @returns List of client roles
*/ */
getClientRoles(userId: string, clientId: string): Observable<any[]> { getClientRoles(userId: string, clientId: string): Observable<any[]> {
const url = this.buildUserClientRoleMapping(userId, clientId); const url = `${this.identityHost}/users/${userId}/role-mappings/clients/${clientId}/composite`;
const httpMethod = 'GET', pathParams = {}, queryParams = {}, bodyParam = {}, headerParams = {}, return this.oAuth2Service.get({ url });
formParams = {}, contentTypes = ['application/json'], accepts = ['application/json'];
return from(this.alfrescoApiService.getInstance().oauth2Auth.callCustomApi(
url, httpMethod, pathParams, queryParams,
headerParams, formParams, bodyParam,
contentTypes, accepts, Object, null, null)
);
} }
/** /**
@@ -200,9 +156,7 @@ export class IdentityUserService {
*/ */
checkUserHasClientApp(userId: string, clientId: string): Observable<boolean> { checkUserHasClientApp(userId: string, clientId: string): Observable<boolean> {
return this.getClientRoles(userId, clientId).pipe( return this.getClientRoles(userId, clientId).pipe(
map((clientRoles: any[]) => { map((clientRoles) => clientRoles.length > 0)
return clientRoles.length > 0;
})
); );
} }
@@ -219,9 +173,7 @@ export class IdentityUserService {
let hasRole = false; let hasRole = false;
if (clientRoles.length > 0) { if (clientRoles.length > 0) {
roleNames.forEach((roleName) => { roleNames.forEach((roleName) => {
const role = clientRoles.find((availableRole) => { const role = clientRoles.find(({ name }) => name === roleName);
return availableRole.name === roleName;
});
if (role) { if (role) {
hasRole = true; hasRole = true;
@@ -240,18 +192,13 @@ export class IdentityUserService {
* @returns Client ID string * @returns Client ID string
*/ */
getClientIdByApplicationName(applicationName: string): Observable<string> { getClientIdByApplicationName(applicationName: string): Observable<string> {
const url = this.buildGetClientsUrl(); const url = `${this.identityHost}/clients`;
const httpMethod = 'GET', pathParams = {}, queryParams = { clientId: applicationName }, bodyParam = {}, headerParams = {}, formParams = {}, const queryParams = { clientId: applicationName };
contentTypes = ['application/json'], accepts = ['application/json'];
return from(this.alfrescoApiService.getInstance() return this.oAuth2Service
.oauth2Auth.callCustomApi(url, httpMethod, pathParams, queryParams, headerParams, .get<any[]>({url, queryParams })
formParams, bodyParam, contentTypes, .pipe(
accepts, Object, null, null) map((response) => response && response.length > 0 ? response[0].id : '')
).pipe(
map((response: any[]) => {
const clientId = response && response.length > 0 ? response[0].id : '';
return clientId;
})
); );
} }
@@ -290,18 +237,7 @@ export class IdentityUserService {
*/ */
getUsers(): Observable<IdentityUserModel[]> { getUsers(): Observable<IdentityUserModel[]> {
const url = this.buildUserUrl(); const url = this.buildUserUrl();
const httpMethod = 'GET', pathParams = {}, queryParams = {}, bodyParam = {}, headerParams = {}, return this.oAuth2Service.get({ url });
formParams = {}, authNames = [], contentTypes = ['application/json'], accepts = ['application/json'];
return from(this.alfrescoApiService.getInstance().oauth2Auth.callCustomApi(
url, httpMethod, pathParams, queryParams,
headerParams, formParams, bodyParam, authNames,
contentTypes, accepts, null, null)
).pipe(
map((response: IdentityUserModel[]) => {
return response;
})
);
} }
/** /**
@@ -310,19 +246,8 @@ export class IdentityUserService {
* @returns Array of role info objects * @returns Array of role info objects
*/ */
getUserRoles(userId: string): Observable<IdentityRoleModel[]> { getUserRoles(userId: string): Observable<IdentityRoleModel[]> {
const url = this.buildRolesUrl(userId); const url = `${this.identityHost}/users/${userId}/role-mappings/realm/composite`;
const httpMethod = 'GET', pathParams = {}, queryParams = {}, bodyParam = {}, headerParams = {}, return this.oAuth2Service.get({ url });
formParams = {}, contentTypes = ['application/json'], accepts = ['application/json'];
return from(this.alfrescoApiService.getInstance().oauth2Auth.callCustomApi(
url, httpMethod, pathParams, queryParams,
headerParams, formParams, bodyParam,
contentTypes, accepts, Object, null, null)
).pipe(
map((response: IdentityRoleModel[]) => {
return response;
})
);
} }
/** /**
@@ -357,7 +282,7 @@ export class IdentityUserService {
const currentUser = this.getCurrentUserInfo(); const currentUser = this.getCurrentUserInfo();
let users = await this.getUsers().toPromise(); let users = await this.getUsers().toPromise();
users = users.filter((user) => { return user.username !== currentUser.username; }); users = users.filter(({ username }) => username !== currentUser.username);
for (let i = 0; i < users.length; i++) { for (let i = 0; i < users.length; i++) {
const hasAnyRole = await this.userHasAnyRole(users[i].id, roleNames); const hasAnyRole = await this.userHasAnyRole(users[i].id, roleNames);
@@ -394,9 +319,7 @@ export class IdentityUserService {
let hasRole = false; let hasRole = false;
if (userRoles && userRoles.length > 0) { if (userRoles && userRoles.length > 0) {
roleNames.forEach((roleName: string) => { roleNames.forEach((roleName: string) => {
const role = userRoles.find((userRole) => { const role = userRoles.find(({ name }) => roleName === name);
return roleName === userRole.name;
});
if (role) { if (role) {
hasRole = true; hasRole = true;
return; return;
@@ -413,18 +336,12 @@ export class IdentityUserService {
*/ */
queryUsers(requestQuery: IdentityUserQueryCloudRequestModel): Observable<IdentityUserQueryResponse> { queryUsers(requestQuery: IdentityUserQueryCloudRequestModel): Observable<IdentityUserQueryResponse> {
const url = this.buildUserUrl(); const url = this.buildUserUrl();
const httpMethod = 'GET', pathParams = {}, const queryParams = { first: requestQuery.first, max: requestQuery.max };
queryParams = { first: requestQuery.first, max: requestQuery.max }, bodyParam = {}, headerParams = {},
formParams = {}, authNames = [], contentTypes = ['application/json'];
return this.getTotalUsersCount().pipe( return this.getTotalUsersCount().pipe(
switchMap((totalCount: any) => switchMap((totalCount) =>
from(this.alfrescoApiService.getInstance().oauth2Auth.callCustomApi( this.oAuth2Service.get<IdentityUserModel[]>({ url, queryParams }).pipe(
url, httpMethod, pathParams, queryParams, map((response) => {
headerParams, formParams, bodyParam, authNames,
contentTypes, null, null, null)
).pipe(
map((response: IdentityUserModel[]) => {
return <IdentityUserQueryResponse> { return <IdentityUserQueryResponse> {
entries: response, entries: response,
pagination: { pagination: {
@@ -435,9 +352,9 @@ export class IdentityUserService {
totalItems: totalCount totalItems: totalCount
} }
}; };
}), })
catchError((error) => this.handleError(error)) )
)) )
); );
} }
@@ -447,15 +364,7 @@ export class IdentityUserService {
*/ */
getTotalUsersCount(): Observable<number> { getTotalUsersCount(): Observable<number> {
const url = this.buildUserUrl() + `/count`; const url = this.buildUserUrl() + `/count`;
const contentTypes = ['application/json'], accepts = ['application/json']; return this.oAuth2Service.get({ url });
return from(this.alfrescoApiService.getInstance()
.oauth2Auth.callCustomApi(url, 'GET',
null, null, null,
null, null, contentTypes,
accepts, null, null, null
)).pipe(
catchError((error) => this.handleError(error))
);
} }
/** /**
@@ -465,17 +374,9 @@ export class IdentityUserService {
*/ */
createUser(newUser: IdentityUserModel): Observable<any> { createUser(newUser: IdentityUserModel): Observable<any> {
const url = this.buildUserUrl(); const url = this.buildUserUrl();
const request = JSON.stringify(newUser); const bodyParam = JSON.stringify(newUser);
const httpMethod = 'POST', pathParams = {}, queryParams = {}, bodyParam = request, headerParams = {},
formParams = {}, contentTypes = ['application/json'], accepts = ['application/json'];
return from( return this.oAuth2Service.post({ url, bodyParam });
this.alfrescoApiService.getInstance().oauth2Auth.callCustomApi(
url, httpMethod, pathParams, queryParams,
headerParams, formParams, bodyParam,
contentTypes, accepts, null, null, null
)
).pipe(catchError(error => this.handleError(error)));
} }
/** /**
@@ -486,17 +387,9 @@ export class IdentityUserService {
*/ */
updateUser(userId: string, updatedUser: IdentityUserModel): Observable<any> { updateUser(userId: string, updatedUser: IdentityUserModel): Observable<any> {
const url = this.buildUserUrl() + '/' + userId; const url = this.buildUserUrl() + '/' + userId;
const request = JSON.stringify(updatedUser); const bodyParam = JSON.stringify(updatedUser);
const httpMethod = 'PUT', pathParams = {} , queryParams = {}, bodyParam = request, headerParams = {},
formParams = {}, contentTypes = ['application/json'], accepts = ['application/json'];
return from(this.alfrescoApiService.getInstance().oauth2Auth.callCustomApi( return this.oAuth2Service.put({ url, bodyParam });
url, httpMethod, pathParams, queryParams,
headerParams, formParams, bodyParam,
contentTypes, accepts, null, null, null
)).pipe(
catchError((error) => this.handleError(error))
);
} }
/** /**
@@ -506,16 +399,7 @@ export class IdentityUserService {
*/ */
deleteUser(userId: string): Observable<any> { deleteUser(userId: string): Observable<any> {
const url = this.buildUserUrl() + '/' + userId; const url = this.buildUserUrl() + '/' + userId;
const httpMethod = 'DELETE', pathParams = {} , queryParams = {}, bodyParam = {}, headerParams = {}, return this.oAuth2Service.delete({ url });
formParams = {}, contentTypes = ['application/json'], accepts = ['application/json'];
return from(this.alfrescoApiService.getInstance().oauth2Auth.callCustomApi(
url, httpMethod, pathParams, queryParams,
headerParams, formParams, bodyParam,
contentTypes, accepts, null, null, null
)).pipe(
catchError((error) => this.handleError(error))
);
} }
/** /**
@@ -526,17 +410,9 @@ export class IdentityUserService {
*/ */
changePassword(userId: string, newPassword: IdentityUserPasswordModel): Observable<any> { changePassword(userId: string, newPassword: IdentityUserPasswordModel): Observable<any> {
const url = this.buildUserUrl() + '/' + userId + '/reset-password'; const url = this.buildUserUrl() + '/' + userId + '/reset-password';
const request = JSON.stringify(newPassword); const bodyParam = JSON.stringify(newPassword);
const httpMethod = 'PUT', pathParams = {} , queryParams = {}, bodyParam = request, headerParams = {},
formParams = {}, contentTypes = ['application/json'], accepts = ['application/json'];
return from(this.alfrescoApiService.getInstance().oauth2Auth.callCustomApi( return this.oAuth2Service.put({ url, bodyParam });
url, httpMethod, pathParams, queryParams,
headerParams, formParams, bodyParam,
contentTypes, accepts, null, null, null
)).pipe(
catchError((error) => this.handleError(error))
);
} }
/** /**
@@ -546,17 +422,9 @@ export class IdentityUserService {
*/ */
getInvolvedGroups(userId: string): Observable<IdentityGroupModel[]> { getInvolvedGroups(userId: string): Observable<IdentityGroupModel[]> {
const url = this.buildUserUrl() + '/' + userId + '/groups/'; const url = this.buildUserUrl() + '/' + userId + '/groups/';
const httpMethod = 'GET', pathParams = { id: userId}, const pathParams = { id: userId };
queryParams = {}, bodyParam = {}, headerParams = {},
formParams = {}, authNames = [], contentTypes = ['application/json'];
return from(this.alfrescoApiService.getInstance().oauth2Auth.callCustomApi( return this.oAuth2Service.get({ url, pathParams });
url, httpMethod, pathParams, queryParams,
headerParams, formParams, bodyParam, authNames,
contentTypes, null, null, null
)).pipe(
catchError((error) => this.handleError(error))
);
} }
/** /**
@@ -566,17 +434,9 @@ export class IdentityUserService {
*/ */
joinGroup(joinGroupRequest: IdentityJoinGroupRequestModel): Observable<any> { joinGroup(joinGroupRequest: IdentityJoinGroupRequestModel): Observable<any> {
const url = this.buildUserUrl() + '/' + joinGroupRequest.userId + '/groups/' + joinGroupRequest.groupId; const url = this.buildUserUrl() + '/' + joinGroupRequest.userId + '/groups/' + joinGroupRequest.groupId;
const request = JSON.stringify(joinGroupRequest); const bodyParam = JSON.stringify(joinGroupRequest);
const httpMethod = 'PUT', pathParams = {} , queryParams = {}, bodyParam = request, headerParams = {},
formParams = {}, contentTypes = ['application/json'], accepts = ['application/json'];
return from(this.alfrescoApiService.getInstance().oauth2Auth.callCustomApi( return this.oAuth2Service.put({ url, bodyParam });
url, httpMethod, pathParams, queryParams,
headerParams, formParams, bodyParam,
contentTypes, accepts, null, null, null
)).pipe(
catchError((error) => this.handleError(error))
);
} }
/** /**
@@ -587,16 +447,7 @@ export class IdentityUserService {
*/ */
leaveGroup(userId: any, groupId: string): Observable<any> { leaveGroup(userId: any, groupId: string): Observable<any> {
const url = this.buildUserUrl() + '/' + userId + '/groups/' + groupId; const url = this.buildUserUrl() + '/' + userId + '/groups/' + groupId;
const httpMethod = 'DELETE', pathParams = {} , queryParams = {}, bodyParam = {}, headerParams = {}, return this.oAuth2Service.delete({ url });
formParams = {}, contentTypes = ['application/json'], accepts = ['application/json'];
return from(this.alfrescoApiService.getInstance().oauth2Auth.callCustomApi(
url, httpMethod, pathParams, queryParams,
headerParams, formParams, bodyParam,
contentTypes, accepts, null, null, null
)).pipe(
catchError((error) => this.handleError(error))
);
} }
/** /**
@@ -606,17 +457,7 @@ export class IdentityUserService {
*/ */
getAvailableRoles(userId: string): Observable<IdentityRoleModel[]> { getAvailableRoles(userId: string): Observable<IdentityRoleModel[]> {
const url = this.buildUserUrl() + '/' + userId + '/role-mappings/realm/available'; const url = this.buildUserUrl() + '/' + userId + '/role-mappings/realm/available';
const httpMethod = 'GET', pathParams = {}, return this.oAuth2Service.get({ url });
queryParams = {}, bodyParam = {}, headerParams = {},
formParams = {}, authNames = [], contentTypes = ['application/json'];
return from(this.alfrescoApiService.getInstance().oauth2Auth.callCustomApi(
url, httpMethod, pathParams, queryParams,
headerParams, formParams, bodyParam, authNames,
contentTypes, null, null, null
)).pipe(
catchError((error) => this.handleError(error))
);
} }
/** /**
@@ -626,17 +467,9 @@ export class IdentityUserService {
*/ */
getAssignedRoles(userId: string): Observable<IdentityRoleModel[]> { getAssignedRoles(userId: string): Observable<IdentityRoleModel[]> {
const url = this.buildUserUrl() + '/' + userId + '/role-mappings/realm'; const url = this.buildUserUrl() + '/' + userId + '/role-mappings/realm';
const httpMethod = 'GET', pathParams = { id: userId}, const pathParams = { id: userId };
queryParams = {}, bodyParam = {}, headerParams = {},
formParams = {}, authNames = [], contentTypes = ['application/json'];
return from(this.alfrescoApiService.getInstance().oauth2Auth.callCustomApi( return this.oAuth2Service.get({ url, pathParams });
url, httpMethod, pathParams, queryParams,
headerParams, formParams, bodyParam, authNames,
contentTypes, null, null, null
)).pipe(
catchError((error) => this.handleError(error))
);
} }
/** /**
@@ -646,17 +479,9 @@ export class IdentityUserService {
*/ */
getEffectiveRoles(userId: string): Observable<IdentityRoleModel[]> { getEffectiveRoles(userId: string): Observable<IdentityRoleModel[]> {
const url = this.buildUserUrl() + '/' + userId + '/role-mappings/realm/composite'; const url = this.buildUserUrl() + '/' + userId + '/role-mappings/realm/composite';
const httpMethod = 'GET', pathParams = { id: userId}, const pathParams = { id: userId };
queryParams = {}, bodyParam = {}, headerParams = {},
formParams = {}, authNames = [], contentTypes = ['application/json'];
return from(this.alfrescoApiService.getInstance().oauth2Auth.callCustomApi( return this.oAuth2Service.get({ url, pathParams });
url, httpMethod, pathParams, queryParams,
headerParams, formParams, bodyParam, authNames,
contentTypes, null, null, null
)).pipe(
catchError((error) => this.handleError(error))
);
} }
/** /**
@@ -667,17 +492,9 @@ export class IdentityUserService {
*/ */
assignRoles(userId: string, roles: IdentityRoleModel[]): Observable<any> { assignRoles(userId: string, roles: IdentityRoleModel[]): Observable<any> {
const url = this.buildUserUrl() + '/' + userId + '/role-mappings/realm'; const url = this.buildUserUrl() + '/' + userId + '/role-mappings/realm';
const request = JSON.stringify(roles); const bodyParam = JSON.stringify(roles);
const httpMethod = 'POST', pathParams = {} , queryParams = {}, bodyParam = request, headerParams = {},
formParams = {}, contentTypes = ['application/json'], accepts = ['application/json'];
return from(this.alfrescoApiService.getInstance().oauth2Auth.callCustomApi( return this.oAuth2Service.post({ url, bodyParam });
url, httpMethod, pathParams, queryParams,
headerParams, formParams, bodyParam,
contentTypes, accepts, null, null, null
)).pipe(
catchError((error) => this.handleError(error))
);
} }
/** /**
@@ -688,41 +505,8 @@ export class IdentityUserService {
*/ */
removeRoles(userId: string, removedRoles: IdentityRoleModel[]): Observable<any> { removeRoles(userId: string, removedRoles: IdentityRoleModel[]): Observable<any> {
const url = this.buildUserUrl() + '/' + userId + '/role-mappings/realm'; const url = this.buildUserUrl() + '/' + userId + '/role-mappings/realm';
const request = JSON.stringify(removedRoles); const bodyParam = JSON.stringify(removedRoles);
const httpMethod = 'DELETE', pathParams = {} , queryParams = {}, bodyParam = request, headerParams = {},
formParams = {}, contentTypes = ['application/json'], accepts = ['application/json'];
return from(this.alfrescoApiService.getInstance().oauth2Auth.callCustomApi( return this.oAuth2Service.delete({ url, bodyParam });
url, httpMethod, pathParams, queryParams,
headerParams, formParams, bodyParam,
contentTypes, accepts, null, null, null
)).pipe(
catchError((error) => this.handleError(error))
);
}
private buildUserUrl(): string {
return `${this.appConfigService.get('identityHost')}/users`;
}
private buildUserClientRoleMapping(userId: string, clientId: string): string {
return `${this.appConfigService.get('identityHost')}/users/${userId}/role-mappings/clients/${clientId}/composite`;
}
private buildRolesUrl(userId: string): string {
return `${this.appConfigService.get('identityHost')}/users/${userId}/role-mappings/realm/composite`;
}
private buildGetClientsUrl(): string {
return `${this.appConfigService.get('identityHost')}/clients`;
}
/**
* Throw the error
* @param error
*/
private handleError(error: Response) {
this.logService.error(error);
return throwError(error || 'Server error');
} }
} }

View File

@@ -0,0 +1,84 @@
/*!
* @license
* Copyright 2019 Alfresco Software, Ltd.
*
* 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 { Injectable } from '@angular/core';
import { AlfrescoApiService } from './alfresco-api.service';
import { Observable, from } from 'rxjs';
export const JSON_TYPE = ['application/json'];
export interface OAuth2RequestParams {
url: string;
httpMethod?: string;
pathParams?: any;
queryParams?: any;
bodyParam?: any;
}
@Injectable({ providedIn: 'root' })
export class OAuth2Service {
constructor(private alfrescoApiService: AlfrescoApiService) {}
get apiClient() {
return this.alfrescoApiService.getInstance().oauth2Auth;
}
request<T>(opts: OAuth2RequestParams): Observable<T> {
return from(
this.apiClient.callCustomApi(
opts.url,
opts.httpMethod,
opts.pathParams,
opts.queryParams,
{},
{},
opts.bodyParam,
JSON_TYPE,
JSON_TYPE,
Object
)
);
}
get<T>(opts: OAuth2RequestParams): Observable<T> {
return this.request({
...opts,
httpMethod: 'GET'
});
}
put<T>(opts: OAuth2RequestParams): Observable<T> {
return this.request({
...opts,
httpMethod: 'PUT'
});
}
post<T>(opts: OAuth2RequestParams): Observable<T> {
return this.request({
...opts,
httpMethod: 'PUT'
});
}
delete<T>(opts: OAuth2RequestParams): Observable<T> {
return this.request({
...opts,
httpMethod: 'DELETE'
});
}
}