diff --git a/docs/core/services/user-access.service.md b/docs/core/services/user-access.service.md
new file mode 100644
index 0000000000..41514d3603
--- /dev/null
+++ b/docs/core/services/user-access.service.md
@@ -0,0 +1,27 @@
+---
+Title: User access service
+Added: v1.0.0
+Status: Active
+Last reviewed: 2022-06-05
+---
+
+# [User access service](../../../lib/core/services/user-access.service.ts "Defined in user-access.service.ts")
+
+Checks the global and application access of a user
+
+## Class members
+
+### Methods
+- **fetchUserAccess**()
+ Fetches the global and application access of the user
+- **hasApplicationAccess**(appName: `string`, rolesToCheck: string[]): `boolean`
+ Checks if the user has at least one of the roles to check for a given app.
+ - appName: `string` - The name of the app
+ - rolesToCheck: `string[]` - The roles to check
+ - **Returns** `boolean` - True if it contains at least one of the given roles to check for the given app, false otherwise
+- **hasGlobalAccess**(rolesToCheck: string[]): `boolean`
+ Checks if the user has at least one of the given roles to check in the global roles.
+ - rolesToCheck: `string[]` - The roles to check
+ - **Returns** `boolean` - True if it contains at least one of the given roles to check, false otherwise
+- **resetAccess**()
+ Resets the cached access of the user
diff --git a/e2e/core/login/login-component.e2e.ts b/e2e/core/login/login-component.e2e.ts
index 05fcc506e7..28b4cc16bd 100644
--- a/e2e/core/login/login-component.e2e.ts
+++ b/e2e/core/login/login-component.e2e.ts
@@ -17,7 +17,6 @@
import { createApiService,
BrowserActions,
- ErrorPage,
LocalStorageUtil,
UserInfoPage,
UserModel,
@@ -34,7 +33,6 @@ describe('Login component', () => {
const userInfoPage = new UserInfoPage();
const contentServicesPage = new ContentServicesPage();
const loginPage = new LoginShellPage();
- const errorPage = new ErrorPage();
const userA = new UserModel();
const userB = new UserModel();
@@ -75,14 +73,6 @@ describe('Login component', () => {
await expect(await userInfoPage.getContentHeaderTitle()).toEqual(`${userB.firstName} ${userB.lastName}`);
});
- it('[C299206] Should redirect the user without the right access role on a forbidden page', async () => {
- await loginPage.login(userA.username, userA.password);
- await navigationBarPage.navigateToProcessServicesCloudPage();
- await expect(await errorPage.getErrorCode()).toBe('403');
- await expect(await errorPage.getErrorTitle()).toBe('You don\'t have permission to access this server.');
- await expect(await errorPage.getErrorDescription()).toBe('You\'re not allowed access to this resource on the server.');
- });
-
it('[C260036] Should require username', async () => {
await loginPage.goToLoginPage();
await loginPage.checkUsernameInactive();
diff --git a/e2e/process-services-cloud/access/user-access-cloud.e2e.ts b/e2e/process-services-cloud/access/user-access-cloud.e2e.ts
new file mode 100644
index 0000000000..8f685aef9e
--- /dev/null
+++ b/e2e/process-services-cloud/access/user-access-cloud.e2e.ts
@@ -0,0 +1,50 @@
+/*!
+ * @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 { createApiService, ErrorPage, IdentityService, LoginPage } from '@alfresco/adf-testing';
+import { NavigationBarPage } from '../../core/pages/navigation-bar.page';
+
+describe('User Access Cloud', () => {
+ const loginSSOPage = new LoginPage();
+ const navigationBarPage = new NavigationBarPage();
+ const errorPage = new ErrorPage();
+
+ const apiService = createApiService();
+ const identityService = new IdentityService(apiService);
+
+ let testUser;
+
+ beforeAll( async () => {
+ await apiService.loginWithProfile('identityAdmin');
+ testUser = await identityService.createIdentityUserWithRole([identityService.ROLES.ACTIVITI_DEVOPS]);
+
+ await loginSSOPage.login(testUser.username, testUser.password);
+ await apiService.login(testUser.username, testUser.password);
+ });
+
+ afterAll(async () => {
+ await apiService.loginWithProfile('identityAdmin');
+ await identityService.deleteIdentityUser(testUser.idIdentityService);
+ });
+
+ it('[C299206] Should redirect the user without the right access role on a forbidden page', async () => {
+ await navigationBarPage.navigateToProcessServicesCloudPage();
+ await expect(await errorPage.getErrorCode()).toBe('403');
+ await expect(await errorPage.getErrorTitle()).toBe('You don\'t have permission to access this server.');
+ await expect(await errorPage.getErrorDescription()).toBe('You\'re not allowed access to this resource on the server.');
+ });
+});
diff --git a/lib/core/mock/user-access.mock.ts b/lib/core/mock/user-access.mock.ts
new file mode 100644
index 0000000000..b90fe8b9cc
--- /dev/null
+++ b/lib/core/mock/user-access.mock.ts
@@ -0,0 +1,45 @@
+/*!
+ * @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.
+ */
+
+export const userAccessMock = {
+ globalAccess: {
+ roles: [
+ 'MOCK_GLOBAL_USER_ROLE'
+ ]
+ },
+ applicationAccess: [
+ {
+ name: 'mockApp1',
+ roles: [
+ 'MOCK_USER_ROLE_APP_1'
+ ]
+ },
+ {
+ name: 'mockApp2',
+ roles: [
+ 'MOCK_USER_ROLE_APP_2'
+ ]
+ },
+ {
+ name: 'mockApp3',
+ roles: [
+ 'MOCK_USER_ROLE_APP_3',
+ 'MOCK_ADMIN_ROLE_APP_3'
+ ]
+ }
+ ]
+};
diff --git a/lib/core/models/application-access.model.ts b/lib/core/models/application-access.model.ts
new file mode 100644
index 0000000000..5662a9a49d
--- /dev/null
+++ b/lib/core/models/application-access.model.ts
@@ -0,0 +1,21 @@
+/*!
+ * @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.
+ */
+
+export interface ApplicationAccessModel {
+ name: string;
+ roles: string[];
+}
diff --git a/lib/core/models/public-api.ts b/lib/core/models/public-api.ts
index 0516710427..c7d0eff903 100644
--- a/lib/core/models/public-api.ts
+++ b/lib/core/models/public-api.ts
@@ -35,3 +35,5 @@ export * from './identity-role.model';
export * from './identity-group.model';
export * from './search-text-input.model';
export * from './node-metadata.model';
+export * from './application-access.model';
+export * from './user-access.model';
diff --git a/lib/core/models/user-access.model.ts b/lib/core/models/user-access.model.ts
new file mode 100644
index 0000000000..21e739c54e
--- /dev/null
+++ b/lib/core/models/user-access.model.ts
@@ -0,0 +1,23 @@
+/*!
+ * @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 { ApplicationAccessModel } from './application-access.model';
+
+export interface UserAccessModel {
+ globalAccess: { roles: string[] };
+ applicationAccess: ApplicationAccessModel[];
+}
diff --git a/lib/core/services/auth-guard-sso-role.service.spec.ts b/lib/core/services/auth-guard-sso-role.service.spec.ts
index 1640ce620f..74f42ecde2 100644
--- a/lib/core/services/auth-guard-sso-role.service.spec.ts
+++ b/lib/core/services/auth-guard-sso-role.service.spec.ts
@@ -26,6 +26,7 @@ import { TranslateModule } from '@ngx-translate/core';
import { PeopleContentService } from './people-content.service';
import { of } from 'rxjs';
import { getFakeUserWithContentAdminCapability, getFakeUserWithContentUserCapability } from '../mock/ecm-user.service.mock';
+import { UserAccessService } from './user-access.service';
describe('Auth Guard SSO role service', () => {
@@ -33,6 +34,7 @@ describe('Auth Guard SSO role service', () => {
let jwtHelperService: JwtHelperService;
let routerService: Router;
let peopleContentService: PeopleContentService;
+ let userAccessService: UserAccessService;
setupTestBed({
imports: [
@@ -47,19 +49,28 @@ describe('Auth Guard SSO role service', () => {
jwtHelperService = TestBed.inject(JwtHelperService);
routerService = TestBed.inject(Router);
peopleContentService = TestBed.inject(PeopleContentService);
+ userAccessService = TestBed.inject(UserAccessService);
+ userAccessService.resetAccess();
});
- it('Should canActivate be true if the Role is present int the JWT token', async () => {
+ function spyUserAccess(realmRoles: string[], resourceAccess: any) {
spyOn(jwtHelperService, 'getAccessToken').and.returnValue('my-access_token');
- spyOn(jwtHelperService, 'decodeToken').and.returnValue({ realm_access: { roles: ['role1'] } });
+ spyOn(jwtHelperService, 'decodeToken').and.returnValue({
+ realm_access: { roles: realmRoles },
+ resource_access: resourceAccess
+ });
+ }
+ it('Should canActivate be true if the Role is present int the JWT token', async () => {
+ spyUserAccess(['MOCK_USER_ROLE'], {});
const router: ActivatedRouteSnapshot = new ActivatedRouteSnapshot();
- router.data = { roles: ['role1', 'role2'] };
+ router.data = { roles: ['MOCK_USER_ROLE', 'MOCK_ADMIN_ROLE'] };
expect(await authGuard.canActivate(router)).toBeTruthy();
});
it('Should canActivate be true if case of empty roles to check', async () => {
+ spyUserAccess([], {});
const router: ActivatedRouteSnapshot = new ActivatedRouteSnapshot();
router.data = { roles: [] };
@@ -67,64 +78,48 @@ describe('Auth Guard SSO role service', () => {
});
it('Should canActivate be false if the Role is not present int the JWT token', async () => {
- spyOn(jwtHelperService, 'getAccessToken').and.returnValue('my-access_token');
- spyOn(jwtHelperService, 'decodeToken').and.returnValue({ realm_access: { roles: ['role3'] } });
-
+ spyUserAccess(['MOCK_ROOT_USER_ROLE'], {});
const router: ActivatedRouteSnapshot = new ActivatedRouteSnapshot();
- router.data = { roles: ['role1', 'role2'] };
+ router.data = { roles: ['MOCK_USER_ROLE', 'MOCK_ADMIN_ROLE'] };
expect(await authGuard.canActivate(router)).toBeFalsy();
});
it('Should not redirect if canActivate is', async () => {
- spyOn(jwtHelperService, 'getAccessToken').and.returnValue('my-access_token');
- spyOn(jwtHelperService, 'decodeToken').and.returnValue({ realm_access: { roles: ['role1'] } });
+ spyUserAccess(['MOCK_USER_ROLE'], {});
spyOn(routerService, 'navigate').and.stub();
const router: ActivatedRouteSnapshot = new ActivatedRouteSnapshot();
- router.data = { roles: ['role1', 'role2'] };
+ router.data = { roles: ['MOCK_USER_ROLE', 'MOCK_ADMIN_ROLE'] };
expect(await authGuard.canActivate(router)).toBeTruthy();
expect(routerService.navigate).not.toHaveBeenCalled();
});
it('Should canActivate return false if the data Role to check is empty', async () => {
- spyOn(jwtHelperService, 'getAccessToken').and.returnValue('my-access_token');
- spyOn(jwtHelperService, 'decodeToken').and.returnValue({ realm_access: { roles: ['role1', 'role3'] } });
-
- const router: ActivatedRouteSnapshot = new ActivatedRouteSnapshot();
-
- expect(await authGuard.canActivate(router)).toBeFalsy();
- });
-
- it('Should canActivate return false if the realm_access is not present', async () => {
- spyOn(jwtHelperService, 'getAccessToken').and.returnValue('my-access_token');
- spyOn(jwtHelperService, 'decodeToken').and.returnValue({});
-
+ spyUserAccess(['MOCK_USER_ROLE', 'MOCK_ROOT_USER_ROLE'], {});
const router: ActivatedRouteSnapshot = new ActivatedRouteSnapshot();
expect(await authGuard.canActivate(router)).toBeFalsy();
});
it('Should redirect to the redirectURL if canActivate is false and redirectUrl is in data', async () => {
- spyOn(jwtHelperService, 'getAccessToken').and.returnValue('my-access_token');
- spyOn(jwtHelperService, 'decodeToken').and.returnValue({});
+ spyUserAccess([], {});
spyOn(routerService, 'navigate').and.stub();
const router: ActivatedRouteSnapshot = new ActivatedRouteSnapshot();
- router.data = { roles: ['role1', 'role2'], redirectUrl: 'no-role-url' };
+ router.data = { roles: ['MOCK_USER_ROLE', 'MOCK_ADMIN_ROLE'], redirectUrl: 'no-role-url' };
expect(await authGuard.canActivate(router)).toBeFalsy();
expect(routerService.navigate).toHaveBeenCalledWith(['/no-role-url']);
});
it('Should not redirect if canActivate is false and redirectUrl is not in data', async () => {
- spyOn(jwtHelperService, 'getAccessToken').and.returnValue('my-access_token');
- spyOn(jwtHelperService, 'decodeToken').and.returnValue({});
+ spyUserAccess([], {});
spyOn(routerService, 'navigate').and.stub();
const router: ActivatedRouteSnapshot = new ActivatedRouteSnapshot();
- router.data = { roles: ['role1', 'role2'] };
+ router.data = { roles: ['MOCK_USER_ROLE', 'MOCK_ADMIN_ROLE'] };
expect(await authGuard.canActivate(router)).toBeFalsy();
expect(routerService.navigate).not.toHaveBeenCalled();
@@ -132,52 +127,40 @@ describe('Auth Guard SSO role service', () => {
it('Should canActivate be false hasRealm is true and hasClientRole is false', async () => {
const route: ActivatedRouteSnapshot = new ActivatedRouteSnapshot();
- spyOn(jwtHelperService, 'hasRealmRoles').and.returnValue(true);
- spyOn(jwtHelperService, 'hasRealmRolesForClientRole').and.returnValue(false);
+ spyUserAccess([], {});
- route.params = { appName: 'fakeapp' };
- route.data = { clientRoles: ['appName'], roles: ['role1', 'role2'] };
+ route.params = { appName: 'mockApp' };
+ route.data = { clientRoles: ['appName'], roles: ['MOCK_USER_ROLE', 'MOCK_ADMIN_ROLE'] };
expect(await authGuard.canActivate(route)).toBeFalsy();
});
it('Should canActivate be false if hasRealm is false and hasClientRole is true', async () => {
const route: ActivatedRouteSnapshot = new ActivatedRouteSnapshot();
- spyOn(jwtHelperService, 'hasRealmRoles').and.returnValue(false);
- spyOn(jwtHelperService, 'hasRealmRolesForClientRole').and.returnValue(true);
+ spyUserAccess([], {});
- route.params = { appName: 'fakeapp' };
- route.data = { clientRoles: ['fakeapp'], roles: ['role1', 'role2'] };
+ route.params = { appName: 'mockApp' };
+ route.data = { clientRoles: ['mockApp'], roles: ['MOCK_USER_ROLE', 'MOCK_ADMIN_ROLE'] };
expect(await authGuard.canActivate(route)).toBeFalsy();
});
it('Should canActivate be true if both Real Role and Client Role are present int the JWT token', async () => {
const route: ActivatedRouteSnapshot = new ActivatedRouteSnapshot();
- spyOn(jwtHelperService, 'getAccessToken').and.returnValue('my-access_token');
+ spyUserAccess(['MOCK_USER_ROLE'], { mockApp: { roles: ['MOCK_ADMIN_ROLE'] } });
- spyOn(jwtHelperService, 'decodeToken').and.returnValue({
- realm_access: { roles: ['role1'] },
- resource_access: { fakeapp: { roles: ['role2'] } }
- });
-
- route.params = { appName: 'fakeapp' };
- route.data = { clientRoles: ['appName'], roles: ['role1', 'role2'] };
+ route.params = { appName: 'mockApp' };
+ route.data = { clientRoles: ['appName'], roles: ['MOCK_USER_ROLE', 'MOCK_ADMIN_ROLE'] };
expect(await authGuard.canActivate(route)).toBeTruthy();
});
it('Should canActivate be false if the Client Role is not present int the JWT token with the correct role', async () => {
const route: ActivatedRouteSnapshot = new ActivatedRouteSnapshot();
- spyOn(jwtHelperService, 'getAccessToken').and.returnValue('my-access_token');
+ spyUserAccess(['MOCK_USER_ROLE'], { mockApp: { roles: ['MOCK_ROOT_USER_ROLE'] } });
- spyOn(jwtHelperService, 'decodeToken').and.returnValue({
- realm_access: { roles: ['role1'] },
- resource_access: { fakeapp: { roles: ['role3'] } }
- });
-
- route.params = { appName: 'fakeapp' };
- route.data = { clientRoles: ['appName'], roles: ['role1', 'role2'] };
+ route.params = { appName: 'mockApp' };
+ route.data = { clientRoles: ['appName'], roles: ['MOCK_USER_ROLE', 'MOCK_ADMIN_ROLE'] };
expect(await authGuard.canActivate(route)).toBeFalsy();
});
@@ -188,11 +171,10 @@ describe('Auth Guard SSO role service', () => {
spyOn(materialDialog, 'closeAll');
const route: ActivatedRouteSnapshot = new ActivatedRouteSnapshot();
- spyOn(jwtHelperService, 'hasRealmRoles').and.returnValue(true);
- spyOn(jwtHelperService, 'hasRealmRolesForClientRole').and.returnValue(false);
+ spyUserAccess([], {});
- route.params = { appName: 'fakeapp' };
- route.data = { clientRoles: ['appName'], roles: ['role1', 'role2'] };
+ route.params = { appName: 'mockApp' };
+ route.data = { clientRoles: ['appName'], roles: ['MOCK_USER_ROLE', 'MOCK_ADMIN_ROLE'] };
expect(await authGuard.canActivate(route)).toBeFalsy();
expect(materialDialog.closeAll).toHaveBeenCalled();
@@ -206,7 +188,7 @@ describe('Auth Guard SSO role service', () => {
it('Should give access to a content section (ALFRESCO_ADMINISTRATORS) when the user has content admin capability', async () => {
spyOn(peopleContentService, 'getCurrentPerson').and.returnValue(of(getFakeUserWithContentAdminCapability()));
-
+ spyUserAccess([], {});
const router: ActivatedRouteSnapshot = new ActivatedRouteSnapshot();
router.data = { roles: ['ALFRESCO_ADMINISTRATORS'] };
@@ -215,7 +197,7 @@ describe('Auth Guard SSO role service', () => {
it('Should not give access to a content section (ALFRESCO_ADMINISTRATORS) when the user does not have content admin capability', async () => {
spyOn(peopleContentService, 'getCurrentPerson').and.returnValue(of(getFakeUserWithContentUserCapability()));
-
+ spyUserAccess([], {});
const router: ActivatedRouteSnapshot = new ActivatedRouteSnapshot();
router.data = { roles: ['ALFRESCO_ADMINISTRATORS'] };
@@ -224,6 +206,7 @@ describe('Auth Guard SSO role service', () => {
it('Should not call the service to check if the user has content admin capability when the roles do not contain ALFRESCO_ADMINISTRATORS', async () => {
const getCurrentPersonSpy = spyOn(peopleContentService, 'getCurrentPerson').and.returnValue(of(getFakeUserWithContentAdminCapability()));
+ spyUserAccess([], {});
const router: ActivatedRouteSnapshot = new ActivatedRouteSnapshot();
router.data = { roles: ['fakeRole'] };
@@ -236,32 +219,29 @@ describe('Auth Guard SSO role service', () => {
describe('Excluded Roles', () => {
it('Should canActivate be false when the user has one of the excluded roles', async () => {
spyOn(peopleContentService, 'getCurrentPerson').and.returnValue(of(getFakeUserWithContentAdminCapability()));
- spyOn(jwtHelperService, 'getAccessToken').and.returnValue('my-access_token');
- spyOn(jwtHelperService, 'decodeToken').and.returnValue({ realm_access: { roles: ['role1'] } });
+ spyUserAccess(['MOCK_USER_ROLE'], {});
const router: ActivatedRouteSnapshot = new ActivatedRouteSnapshot();
- router.data = { roles: ['ALFRESCO_ADMINISTRATORS'], excludedRoles: ['role1'] };
+ router.data = { roles: ['ALFRESCO_ADMINISTRATORS'], excludedRoles: ['MOCK_USER_ROLE'] };
expect(await authGuard.canActivate(router)).toBeFalsy();
});
it('Should canActivate be true when the user has none of the excluded roles', async () => {
- spyOn(jwtHelperService, 'getAccessToken').and.returnValue('my-access_token');
- spyOn(jwtHelperService, 'decodeToken').and.returnValue({ realm_access: { roles: ['role2'] } });
+ spyUserAccess(['MOCK_ADMIN_ROLE'], {});
const router: ActivatedRouteSnapshot = new ActivatedRouteSnapshot();
- router.data = { roles: ['role1', 'role2'], excludedRoles: ['role3'] };
+ router.data = { roles: ['MOCK_USER_ROLE', 'MOCK_ADMIN_ROLE'], excludedRoles: ['MOCK_ROOT_USER_ROLE'] };
expect(await authGuard.canActivate(router)).toBeTruthy();
});
it('Should canActivate be false when the user is a content admin and the ALFRESCO_ADMINISTRATORS role is excluded', async () => {
spyOn(peopleContentService, 'getCurrentPerson').and.returnValue(of(getFakeUserWithContentAdminCapability()));
- spyOn(jwtHelperService, 'getAccessToken').and.returnValue('my-access_token');
- spyOn(jwtHelperService, 'decodeToken').and.returnValue({ realm_access: { roles: ['role1'] } });
+ spyUserAccess(['MOCK_USER_ROLE'], {});
const router: ActivatedRouteSnapshot = new ActivatedRouteSnapshot();
- router.data = { roles: ['role1'], excludedRoles: ['ALFRESCO_ADMINISTRATORS'] };
+ router.data = { roles: ['MOCK_USER_ROLE'], excludedRoles: ['ALFRESCO_ADMINISTRATORS'] };
expect(await authGuard.canActivate(router)).toBeFalsy();
});
diff --git a/lib/core/services/auth-guard-sso-role.service.ts b/lib/core/services/auth-guard-sso-role.service.ts
index e07b5f1780..c2669404f3 100644
--- a/lib/core/services/auth-guard-sso-role.service.ts
+++ b/lib/core/services/auth-guard-sso-role.service.ts
@@ -16,22 +16,23 @@
*/
import { Injectable } from '@angular/core';
-import { JwtHelperService } from './jwt-helper.service';
import { ActivatedRouteSnapshot, CanActivate, Router } from '@angular/router';
import { MatDialog } from '@angular/material/dialog';
import { ContentGroups, PeopleContentService } from './people-content.service';
+import { UserAccessService } from './user-access.service';
@Injectable({
providedIn: 'root'
})
export class AuthGuardSsoRoleService implements CanActivate {
- constructor(private jwtHelperService: JwtHelperService,
+ constructor(private userAccessService: UserAccessService,
private router: Router,
private dialog: MatDialog,
private peopleContentService: PeopleContentService) {
}
async canActivate(route: ActivatedRouteSnapshot): Promise {
+ await this.userAccessService.fetchUserAccess();
let hasRealmRole = false;
let hasClientRole = true;
@@ -50,13 +51,13 @@ export class AuthGuardSsoRoleService implements CanActivate {
if (route.data['clientRoles']) {
const clientRoleName = route.params[route.data['clientRoles']];
const rolesToCheck = route.data['roles'];
- hasClientRole = this.jwtHelperService.hasRealmRolesForClientRole(clientRoleName, rolesToCheck);
+ hasClientRole = this.userAccessService.hasApplicationAccess(clientRoleName, rolesToCheck);
}
}
const hasRole = hasRealmRole && hasClientRole;
- if (!hasRole && route.data && route.data['redirectUrl']) {
+ if (!hasRole && route?.data && route.data['redirectUrl']) {
this.router.navigate(['/' + route.data['redirectUrl']]);
}
@@ -72,6 +73,8 @@ export class AuthGuardSsoRoleService implements CanActivate {
}
private hasRoles(rolesToCheck: string[], isContentAdmin: boolean): boolean {
- return rolesToCheck.includes(ContentGroups.ALFRESCO_ADMINISTRATORS) ? this.jwtHelperService.hasRealmRoles(rolesToCheck) || isContentAdmin : this.jwtHelperService.hasRealmRoles(rolesToCheck);
+ return rolesToCheck.includes(ContentGroups.ALFRESCO_ADMINISTRATORS)
+ ? this.userAccessService.hasGlobalAccess(rolesToCheck) || isContentAdmin
+ : this.userAccessService.hasGlobalAccess(rolesToCheck);
}
}
diff --git a/lib/core/services/public-api.ts b/lib/core/services/public-api.ts
index 2b4d8a377b..77aae5da87 100644
--- a/lib/core/services/public-api.ts
+++ b/lib/core/services/public-api.ts
@@ -69,3 +69,4 @@ export * from './identity-user.service.interface';
export * from './identity-group.interface';
export * from './language-item.interface';
export * from './sort-by-category.service';
+export * from './user-access.service';
diff --git a/lib/core/services/user-access.service.spec.ts b/lib/core/services/user-access.service.spec.ts
new file mode 100644
index 0000000000..b4bd6c9b5f
--- /dev/null
+++ b/lib/core/services/user-access.service.spec.ts
@@ -0,0 +1,141 @@
+/*!
+ * @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 { CoreTestingModule, setupTestBed } from '../testing';
+import { TestBed } from '@angular/core/testing';
+import { UserAccessService } from './user-access.service';
+import { JwtHelperService } from './jwt-helper.service';
+import { OAuth2Service } from './oauth2.service';
+import { of } from 'rxjs';
+import { userAccessMock } from '../mock/user-access.mock';
+import { AppConfigService } from '../app-config';
+
+describe('UserAccessService', () => {
+ let userAccessService: UserAccessService;
+ let jwtHelperService: JwtHelperService;
+ let oauth2Service: OAuth2Service;
+ let appConfigService: AppConfigService;
+
+ setupTestBed({
+ imports: [CoreTestingModule],
+ providers: [UserAccessService]
+ });
+
+ beforeEach(() => {
+ userAccessService = TestBed.inject(UserAccessService);
+ userAccessService.resetAccess();
+ jwtHelperService = TestBed.inject(JwtHelperService);
+ oauth2Service = TestBed.inject(OAuth2Service);
+ appConfigService = TestBed.inject(AppConfigService);
+ });
+
+ function spyUserAccess(realmRoles: string[], resourceAccess: any) {
+ spyOn(jwtHelperService, 'getAccessToken').and.returnValue('my-access_token');
+ spyOn(jwtHelperService, 'decodeToken').and.returnValue({
+ realm_access: { roles: realmRoles },
+ resource_access: resourceAccess
+ });
+ }
+
+ describe('Access from JWT token', () => {
+
+ it('should return true when the user has one of the global roles', async () => {
+ spyUserAccess(['MOCK_USER_ROLE', 'MOCK_USER_ROLE_2'], {});
+ await userAccessService.fetchUserAccess();
+ const hasGlobalAccess = userAccessService.hasGlobalAccess(['MOCK_USER_ROLE']);
+
+ expect(hasGlobalAccess).toEqual(true);
+ });
+
+ it('should return true when the user has one of the roles for an application', async () => {
+ spyUserAccess([], { mockApp: { roles: ['MOCK_APP_ROLE', 'MOCK_APP_ROLE_2'] } });
+ await userAccessService.fetchUserAccess();
+ const hasApplicationAccess = userAccessService.hasApplicationAccess('mockApp', ['MOCK_APP_ROLE']);
+
+ expect(hasApplicationAccess).toEqual(true);
+ });
+
+ it('should return false when the user has none of the global roles', async () => {
+ spyUserAccess(['MOCK_USER_ROLE'], {});
+ await userAccessService.fetchUserAccess();
+ const hasGlobalAccess = userAccessService.hasGlobalAccess(['MOCK_USER_ROLE_2']);
+
+ expect(hasGlobalAccess).toEqual(false);
+ });
+
+ it('should return false when the user has none of the roles for an application', async () => {
+ spyUserAccess([], { mockApp: { roles: ['MOCK_APP_ROLE'] } });
+ await userAccessService.fetchUserAccess();
+ const hasApplicationAccess = userAccessService.hasApplicationAccess('mockApp', ['MOCK_APP_ROLE_2']);
+
+ expect(hasApplicationAccess).toEqual(false);
+ });
+ });
+
+ describe('Access from the API', () => {
+ let getAccessFromApiSpy: jasmine.Spy;
+
+ beforeEach(() => {
+ spyOn(jwtHelperService, 'getValueFromLocalToken').and.returnValue(undefined);
+ getAccessFromApiSpy = spyOn(oauth2Service, 'get').and.returnValue(of(userAccessMock));
+ });
+
+ it('should return true when the user has one of the global roles', async () => {
+ await userAccessService.fetchUserAccess();
+ const hasGlobalAccess = userAccessService.hasGlobalAccess(['MOCK_GLOBAL_USER_ROLE']);
+
+ expect(hasGlobalAccess).toEqual(true);
+ });
+
+ it('should return true when the user has one of the roles for an application', async () => {
+ await userAccessService.fetchUserAccess();
+ const hasApplicationAccess = userAccessService.hasApplicationAccess('mockApp1', ['MOCK_USER_ROLE_APP_1']);
+
+ expect(hasApplicationAccess).toEqual(true);
+ });
+
+ it('should return false when the user has none of the global roles', async () => {
+ await userAccessService.fetchUserAccess();
+ const hasGlobalAccess = userAccessService.hasGlobalAccess(['MOCK_USER_ROLE_NOT_EXISTING']);
+
+ expect(hasGlobalAccess).toEqual(false);
+ });
+
+ it('should return false when the user has none of the roles for an application', async () => {
+ await userAccessService.fetchUserAccess();
+ const hasApplicationAccess = userAccessService.hasApplicationAccess('mockApp1', ['MOCK_ROLE_NOT_EXISING_IN_APP']);
+
+ expect(hasApplicationAccess).toEqual(false);
+ });
+
+ it('should not call more than once the api to fetch the user access', async () => {
+ await userAccessService.fetchUserAccess();
+ await userAccessService.fetchUserAccess();
+ await userAccessService.fetchUserAccess();
+
+ expect(getAccessFromApiSpy.calls.count()).toEqual(1);
+ });
+
+ it('should the url be composed from identity host of app.config', async () => {
+ const fakeIdentityHost = 'https://fake-identity-host.fake.com';
+ appConfigService.config.identityHost = fakeIdentityHost;
+ await userAccessService.fetchUserAccess();
+
+ expect(getAccessFromApiSpy).toHaveBeenCalledWith({ url: `${ fakeIdentityHost }/v1/identity/roles` });
+ });
+ });
+});
diff --git a/lib/core/services/user-access.service.ts b/lib/core/services/user-access.service.ts
new file mode 100644
index 0000000000..5a78e7eb9a
--- /dev/null
+++ b/lib/core/services/user-access.service.ts
@@ -0,0 +1,99 @@
+/*!
+ * @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 { JwtHelperService } from './jwt-helper.service';
+import { ApplicationAccessModel } from '../models/application-access.model';
+import { UserAccessModel } from '../models/user-access.model';
+import { AppConfigService } from '../app-config/app-config.service';
+import { OAuth2Service } from './oauth2.service';
+
+@Injectable({
+ providedIn: 'root'
+})
+export class UserAccessService {
+ private globalAccess: string[];
+ private applicationAccess: ApplicationAccessModel[];
+
+ constructor(private jwtHelperService: JwtHelperService,
+ private appConfigService: AppConfigService,
+ private oAuth2Service: OAuth2Service) {
+ }
+
+ async fetchUserAccess() {
+ if (!this.hasFetchedAccess()) {
+ this.hasRolesInJwt() ? this.fetchAccessFromJwt() : await this.fetchAccessFromApi();
+ }
+ }
+
+ private fetchAccessFromJwt() {
+ this.globalAccess = this.jwtHelperService.getValueFromLocalToken(JwtHelperService.REALM_ACCESS).roles;
+ this.applicationAccess = this.jwtHelperService.getValueFromLocalToken(JwtHelperService.RESOURCE_ACCESS);
+ }
+
+ private async fetchAccessFromApi() {
+ const url = `${ this.identityHost }/v1/identity/roles`;
+ await this.oAuth2Service.get({ url })
+ .toPromise()
+ .then((response: UserAccessModel) => {
+ this.globalAccess = response.globalAccess.roles;
+ this.applicationAccess = response.applicationAccess;
+ });
+ }
+
+ private hasRolesInJwt(): boolean {
+ return !!this.jwtHelperService.getValueFromLocalToken(JwtHelperService.REALM_ACCESS);
+ }
+
+ private hasFetchedAccess(): boolean {
+ return !!this.globalAccess && !!this.applicationAccess;
+ }
+
+ private get identityHost(): string {
+ return `${this.appConfigService.get('identityHost')}`;
+ }
+
+ /**
+ * Checks for global roles access.
+ *
+ * @param rolesToCheck List of the roles to check
+ * @returns True if it contains at least one of the given roles, false otherwise
+ */
+ hasGlobalAccess(rolesToCheck: string[]): boolean {
+ return this.globalAccess ? this.globalAccess.some((role: string) => rolesToCheck.includes(role)) : false;
+ }
+
+ /**
+ * Checks for global roles access.
+ *
+ * @param appName The app name
+ * @param rolesToCheck List of the roles to check
+ * @returns True if it contains at least one of the given roles, false otherwise
+ */
+ hasApplicationAccess(appName: string, rolesToCheck: string[]): boolean {
+ const appAccess = this.hasRolesInJwt() ? this.applicationAccess[appName] : this.applicationAccess.find((app: ApplicationAccessModel) => app.name === appName);
+ return appAccess ? appAccess.roles.some(appRole => rolesToCheck.includes(appRole)) : false;
+ }
+
+ /**
+ * Resets the cached user access
+ */
+ resetAccess() {
+ this.globalAccess = undefined;
+ this.applicationAccess = undefined;
+ }
+}