Skip to content

OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub

Improve the current user service API (#9201)

Benjamin Bädorf221aa16c5edb
diff --git a/frontend/src/app/modules/apiv3/paths/apiv3-list-resource.interface.ts b/frontend/src/app/modules/apiv3/paths/apiv3-list-resource.interface.ts
index 2a4ead2d9c7..14c33ebfbf7 100644
--- a/frontend/src/app/modules/apiv3/paths/apiv3-list-resource.interface.ts
+++ b/frontend/src/app/modules/apiv3/paths/apiv3-list-resource.interface.ts
@@ -34,6 +34,7 @@ export interface Apiv3ListParameters {
filters?:[string, FilterOperator, string[]][];
sortBy?:[string, string][];
pageSize?:number;
+ offset?:number;
}
export interface Apiv3ListResourceInterface<T> {
@@ -52,6 +53,11 @@ export function listParamsString(params?:Apiv3ListParameters):string {
queryProps.push(`pageSize=${params.pageSize}`);
}
+ // 0 should not be treated as false
+ if (params && params.offset !== undefined) {
+ queryProps.push(`offset=${params.offset}`);
+ }
+
if (params && params.filters) {
const filters = new ApiV3FilterBuilder();
diff --git a/frontend/src/app/modules/current-user/current-user.query.ts b/frontend/src/app/modules/current-user/current-user.query.ts
index f8f0931f02b..b022a6217ff 100644
--- a/frontend/src/app/modules/current-user/current-user.query.ts
+++ b/frontend/src/app/modules/current-user/current-user.query.ts
@@ -1,5 +1,5 @@
import { Injectable } from '@angular/core';
-import { Query } from '@datorama/akita';
+import { filterNilValue, Query } from '@datorama/akita';
import { Observable, combineLatest } from 'rxjs';
import { map } from 'rxjs/operators';
import {
@@ -17,5 +17,5 @@ export class CurrentUserQuery extends Query<CurrentUserState> {
isLoggedIn$ = this.select(state => !!state.id);
user$ = this.select(({ id, name, mail }) => ({ id, name, mail }));
- capabilities$ = this.select('capabilities');
+ capabilities$ = this.select('capabilities').pipe(filterNilValue());
}
diff --git a/frontend/src/app/modules/current-user/current-user.service.spec.ts b/frontend/src/app/modules/current-user/current-user.service.spec.ts
new file mode 100644
index 00000000000..9e5408bae3c
--- /dev/null
+++ b/frontend/src/app/modules/current-user/current-user.service.spec.ts
@@ -0,0 +1,269 @@
+//-- copyright
+// OpenProject is an open source project management software.
+// Copyright (C) 2012-2021 the OpenProject GmbH
+//
+// This program is free software; you can redistribute it and/or
+// modify it under the terms of the GNU General Public License version 3.
+//
+// OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+// Copyright (C) 2006-2013 Jean-Philippe Lang
+// Copyright (C) 2010-2013 the ChiliProject Team
+//
+// This program is free software; you can redistribute it and/or
+// modify it under the terms of the GNU General Public License
+// as published by the Free Software Foundation; either version 2
+// of the License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with this program; if not, write to the Free Software
+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+//
+// See docs/COPYRIGHT.rdoc for more details.
+//++
+
+/*jshint expr: true*/
+
+import { TestBed, getTestBed } from '@angular/core/testing';
+import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
+import { States } from "core-components/states.service";
+import { HalResourceService } from 'core-app/modules/hal/services/hal-resource.service';
+import { ConfigurationService } from 'core-app/modules/common/config/configuration.service';
+import { CurrentUserService } from './current-user.service';
+import { CurrentUserStore } from "./current-user.store";
+import { CurrentUserQuery } from "./current-user.query";
+import { CurrentUser } from './current-user.store';
+
+const globalCapability = {
+ _type: 'Capability',
+ id: 'placeholder_users/read/g-3',
+ _links: {
+ self: {
+ href: '/api/v3/capabilities/placeholder_users/read/g-3',
+ },
+ action: {
+ href: '/api/v3/actions/placeholder_users/read',
+ },
+ context: {
+ href: '/api/v3/capabilities/contexts/global',
+ title: 'Global',
+ },
+ principal: {
+ href: '/api/v3/users/1',
+ title: 'OpenProject Admin',
+ },
+ },
+};
+
+const projectCapabilityp63Update = {
+ _type: 'Capability',
+ id: 'memberships/update/p6-3',
+ _links: {
+ self: {
+ href: '/api/v3/capabilities/memberships/update/p6-3',
+ },
+ action: {
+ href: '/api/v3/actions/memberships/update',
+ },
+ context: {
+ href: '/api/v3/projects/6',
+ title: 'Project 6',
+ },
+ principal: {
+ href: '/api/v3/users/1',
+ title: 'OpenProject Admin',
+ },
+ },
+};
+
+const projectCapabilityp63Read = {
+ _type: 'Capability',
+ id: 'memberships/read/p6-3',
+ _links: {
+ self: {
+ href: '/api/v3/capabilities/memberships/read/p6-3',
+ },
+ action: {
+ href: '/api/v3/actions/memberships/read',
+ },
+ context: {
+ href: '/api/v3/projects/6',
+ title: 'Project 6',
+ },
+ principal: {
+ href: '/api/v3/users/1',
+ title: 'OpenProject Admin',
+ },
+ },
+};
+
+const projectCapabilityp53Update = {
+ _type: 'Capability',
+ id: 'memberships/update/p5-3',
+ _links: {
+ self: {
+ href: '/api/v3/capabilities/memberships/update/p5-3',
+ },
+ action: {
+ href: '/api/v3/actions/memberships/update',
+ },
+ context: {
+ href: '/api/v3/projects/5',
+ title: 'Project 5',
+ },
+ principal: {
+ href: '/api/v3/users/1',
+ title: 'OpenProject Admin',
+ },
+ },
+};
+
+describe('CurrentUserService', function () {
+ let injector:TestBed;
+ let currentUserService:CurrentUserService;
+ let httpMock:HttpTestingController;
+
+ const compile = (user:CurrentUser) => {
+ const ConfigurationServiceStub = {};
+
+ TestBed.configureTestingModule({
+ imports: [
+ HttpClientTestingModule,
+ ],
+ providers: [
+ HalResourceService,
+ CurrentUserStore,
+ CurrentUserQuery,
+ { provide: ConfigurationService, useValue: ConfigurationServiceStub },
+ { provide: States, useValue: new States() },
+ ],
+ });
+
+ injector = getTestBed();
+ currentUserService = TestBed.inject(CurrentUserService);
+ httpMock = TestBed.inject(HttpTestingController);
+
+ currentUserService.setUser(user);
+ };
+
+ const mockRequest = () => {
+ httpMock
+ .match((req) => req.url.includes('/api/v3/capabilities'))
+ .forEach((req) => {
+ expect(req.request.method).toBe('GET');
+ req.flush({
+ _type: 'Collection',
+ count: 4,
+ total: 4,
+ pageSize: 1000,
+ offset: 1,
+ _embedded: {
+ elements: [
+ globalCapability,
+ projectCapabilityp63Update,
+ projectCapabilityp63Read,
+ projectCapabilityp53Update,
+ ],
+ },
+ });
+ });
+ }
+
+
+ afterEach(() => {
+ httpMock.verify();
+ });
+
+ describe('When not logged in', () => {
+ beforeEach(() => compile({ id: null, name: null, mail: null }));
+
+ it('Should have no capabilities', () => {
+ currentUserService.capabilities$.subscribe((caps) => {
+ console.log(caps);
+ expect(caps.length).toEqual(0);
+ });
+
+ mockRequest();
+ });
+
+ it('Should not think it is', () => {
+ currentUserService.isLoggedIn$.subscribe((loggedIn) => {
+ expect(loggedIn).toEqual(false);
+ });
+
+ mockRequest();
+ });
+ });
+
+ describe('When logged in', () => {
+ beforeEach(() => compile({ id: '1', name: 'Admin', mail: '[email protected]' }));
+
+ it('Should know it is', () => {
+ currentUserService.isLoggedIn$.subscribe((loggedIn) => {
+ expect(loggedIn).toEqual(true);
+ });
+
+ mockRequest();
+ });
+
+ it('Should have all capabilities', () => {
+ currentUserService.capabilities$.subscribe((caps) => {
+ expect(caps.length).toEqual(4);
+ });
+
+ mockRequest();
+ });
+
+ it('Should filter by context', () => {
+ currentUserService.capabilitiesForContext$('global').subscribe((caps) => {
+ expect(caps.length).toEqual(1);
+ });
+ currentUserService.capabilitiesForContext$('6').subscribe((caps) => {
+ expect(caps.length).toEqual(2);
+ });
+ currentUserService.capabilitiesForContext$('5').subscribe((caps) => {
+ expect(caps.length).toEqual(1);
+ });
+
+ mockRequest();
+ });
+
+ it('Should filter by context and all actions', () => {
+ currentUserService.hasCapabilities$('asdf/asdf').subscribe((hasCaps) => {
+ expect(hasCaps).toEqual(false);
+ });
+ currentUserService.hasCapabilities$('placeholder_users/read').subscribe((hasCaps) => {
+ expect(hasCaps).toEqual(true);
+ });
+ currentUserService.hasCapabilities$(['memberships/update', 'memberships/read'], '6').subscribe((hasCaps) => {
+ expect(hasCaps).toEqual(true);
+ });
+ currentUserService.hasCapabilities$(['memberships/update', 'memberships/nonexistent'], '6').subscribe((hasCaps) => {
+ expect(hasCaps).toEqual(false);
+ });
+
+ mockRequest();
+ });
+
+ it('Should filter by context and any of the actions', () => {
+ currentUserService.hasAnyCapabilityOf$('memberships/update', '6').subscribe((hasCaps) => {
+ expect(hasCaps).toEqual(true);
+ });
+ currentUserService.hasAnyCapabilityOf$(['memberships/update', 'memberships/read'], '6').subscribe((hasCaps) => {
+ expect(hasCaps).toEqual(true);
+ });
+ currentUserService.hasAnyCapabilityOf$(['memberships/update', 'memberships/nonexistent'], '6').subscribe((hasCaps) => {
+ expect(hasCaps).toEqual(true);
+ });
+ currentUserService.hasAnyCapabilityOf$('memberships/nonexistent', '6').subscribe((hasCaps) => {
+ expect(hasCaps).toEqual(false);
+ });
+
+ mockRequest();
+ });
+ });
+});
diff --git a/frontend/src/app/modules/current-user/current-user.service.ts b/frontend/src/app/modules/current-user/current-user.service.ts
index e569bd8f049..9e9dd064189 100644
--- a/frontend/src/app/modules/current-user/current-user.service.ts
+++ b/frontend/src/app/modules/current-user/current-user.service.ts
@@ -27,15 +27,19 @@
//++
import { Injectable } from "@angular/core";
+import { of, forkJoin } from 'rxjs';
+import { take, map, mergeMap, distinctUntilChanged, tap } from 'rxjs/operators';
import { APIV3Service } from "core-app/modules/apiv3/api-v3.service";
-import { take } from 'rxjs/operators';
-import { CurrentUserStore, CurrentUser } from "./current-user.store";
+import { FilterOperator } from 'core-components/api/api-v3/api-v3-filter-builder';
import { CapabilityResource } from "core-app/modules/hal/resources/capability-resource";
+import { CollectionResource } from "core-app/modules/hal/resources/collection-resource";
+import { CurrentUserStore, CurrentUser } from "./current-user.store";
import { CurrentUserQuery } from "./current-user.query";
-
@Injectable({ providedIn: 'root' })
export class CurrentUserService {
+ private PAGE_FETCH_SIZE = 1000;
+
constructor(
private apiV3Service: APIV3Service,
private currentUserStore: CurrentUserStore,
@@ -48,16 +52,24 @@ export class CurrentUserService {
public isLoggedIn$ = this.currentUserQuery.isLoggedIn$;
public user$ = this.currentUserQuery.user$;
+ /**
+ * Set the current user object
+ *
+ * This refetches the global and current project capabilities
+ */
public setUser(user: CurrentUser) {
this.currentUserStore.update(state => ({
...state,
...user,
}));
- this.getCapabilities();
+ this.fetchCapabilities([]);
}
- public getCapabilities() {
+ /**
+ * Fetch all capabilities for certain contexts
+ */
+ public fetchCapabilities(contexts:string[] = []) {
this.user$.pipe(take(1)).subscribe((user) => {
if (!user.id) {
this.currentUserStore.update(state => ({
@@ -68,13 +80,54 @@ export class CurrentUserService {
return;
}
+ const filters: [string, FilterOperator, string[]][] = [ ['principal', '=', [user.id]] ];
+ if (contexts.length) {
+ filters.push([ 'context', '=', contexts.map(context => context === 'global' ? 'g' : `p${context}`) ]);
+ }
+
this.apiV3Service.capabilities.list({
- filters: [ ['principal', '=', [user.id]], ],
- pageSize: 1000,
- }).subscribe((data) => {
+ pageSize: this.PAGE_FETCH_SIZE,
+ filters,
+ })
+ .pipe(
+ mergeMap((data: CollectionResource<CapabilityResource>) => {
+ // The data we've loaded might not contain all capabilities. Some responses might have thousands of
+ // capabilites, and our page size is restricted. If this is the case, we branch out and sent out parallel
+ // requests for each of the other pages.
+ if (data.total > this.PAGE_FETCH_SIZE) {
+ const remaining = data.total - this.PAGE_FETCH_SIZE;
+ const pagesRemaining = Math.ceil(remaining / this.PAGE_FETCH_SIZE);
+ const calls = (new Array(pagesRemaining))
+ .fill(null)
+ .map((_, i) => this.apiV3Service.capabilities.list({
+ pageSize: this.PAGE_FETCH_SIZE,
+ offset: this.PAGE_FETCH_SIZE * (i + 1),
+ filters,
+ }));
+
+ // Branch out and fetch all remaining pages in parallel.
+ // Afterwards, merge the resulting list
+ return forkJoin(...calls).pipe(
+ map(
+ (results: CollectionResource<CapabilityResource>[]) => results.reduce(
+ (acc, next) => acc.concat(next.elements),
+ data.elements,
+ ),
+ ),
+ );
+ }
+
+ // The current page is the only page, return the results.
+ return of(data.elements);
+ }),
+ )
+ .subscribe((capabilities) => {
this.currentUserStore.update(state => ({
...state,
- capabilities: data.elements,
+ capabilities: [
+ ...capabilities,
+ ...(state.capabilities || []).filter(cap => !!capabilities.find(newCap => newCap.id === cap.id)),
+ ],
}));
});
});
@@ -82,6 +135,46 @@ export class CurrentUserService {
return this.currentUserQuery.capabilities$;
}
+ /**
+ * Returns the users' capabilities filtered by context
+ */
+ public capabilitiesForContext$(contextId: string) {
+ return this.capabilities$.pipe(
+ map((capabilities) => capabilities.filter(cap => cap.context.href.endsWith(`/${contextId}`))),
+ distinctUntilChanged(),
+ );
+ }
+
+ /**
+ * Returns an Observable<boolean> indicating whether the user has the required capabilities in the provided context.
+ */
+ public hasCapabilities$(action: string|string[], contextId: string = 'global') {
+ const actions = _.castArray(action);
+ return this.capabilitiesForContext$(contextId).pipe(
+ map((capabilities) => actions.reduce(
+ (acc, action) => {
+ return acc && !!capabilities.find(cap => cap.action.href === `/api/v3/actions/${action}`);
+ },
+ capabilities.length > 0,
+ )),
+ distinctUntilChanged()
+ );
+ }
+
+ /**
+ * Returns an Observable<boolean> indicating whether the user has any of the required capabilities in the provided context.
+ */
+ public hasAnyCapabilityOf$(actions: string|string[], contextId: string = 'global') {
+ const actionsToFilter = _.castArray(actions);
+ return this.capabilitiesForContext$(contextId).pipe(
+ map((capabilities) => capabilities.reduce(
+ (acc, cap) => acc || !!actionsToFilter.find(action => cap.action.href === `/api/v3/actions/${action}`),
+ false,
+ )),
+ distinctUntilChanged(),
+ );
+ }
+
// Everything below this is deprecated legacy interfacing and should not be used
diff --git a/frontend/src/app/modules/current-user/current-user.store.ts b/frontend/src/app/modules/current-user/current-user.store.ts
index 39f11807b51..a82028051c4 100644
--- a/frontend/src/app/modules/current-user/current-user.store.ts
+++ b/frontend/src/app/modules/current-user/current-user.store.ts
@@ -37,7 +37,7 @@ export interface CurrentUser {
}
export interface CurrentUserState extends CurrentUser {
- capabilities: CapabilityResource[];
+ capabilities: CapabilityResource[]|null;
}
export function createInitialState(): CurrentUserState {
@@ -45,7 +45,7 @@ export function createInitialState(): CurrentUserState {
id: null,
name: null,
mail: null,
- capabilities: [],
+ capabilities: null,
};
}
diff --git a/frontend/src/app/modules/invite-user-modal/principal/principal-search.component.html b/frontend/src/app/modules/invite-user-modal/principal/principal-search.component.html
index 4ff4ab9da36..2eb48719826 100644
--- a/frontend/src/app/modules/invite-user-modal/principal/principal-search.component.html
+++ b/frontend/src/app/modules/invite-user-modal/principal/principal-search.component.html
@@ -13,7 +13,7 @@
#ngselect
>
<ng-template ng-label-tmp let-item="item">
- {{ item.principal.name || item.name }}
+ {{ item.principal?.name || item.name }}
</ng-template>
<ng-template ng-option-tmp let-item="item" let-search="searchTerm">
diff --git a/frontend/src/app/modules/invite-user-modal/principal/principal-search.component.ts b/frontend/src/app/modules/invite-user-modal/principal/principal-search.component.ts
index 1f68823120e..f19a39c9775 100644
--- a/frontend/src/app/modules/invite-user-modal/principal/principal-search.component.ts
+++ b/frontend/src/app/modules/invite-user-modal/principal/principal-search.component.ts
@@ -48,10 +48,7 @@ export class PrincipalSearchComponent extends UntilDestroyedMixin implements OnI
public canInviteByEmail$ = combineLatest(
this.items$,
this.input$,
- this.currentUserService.capabilities$.pipe(
- map(capabilities => !!capabilities.find(c => c.action.href.endsWith('/users/create'))),
- distinctUntilChanged(),
- ),
+ this.currentUserService.hasCapabilities$('users/create'),
).pipe(
map(([elements, input, canCreateUsers]) =>
canCreateUsers
@@ -64,10 +61,7 @@ export class PrincipalSearchComponent extends UntilDestroyedMixin implements OnI
public canCreateNewPlaceholder$ = combineLatest(
this.items$,
this.input$,
- this.currentUserService.capabilities$.pipe(
- map(capabilities => !!capabilities.find(c => c.action.href.endsWith('/placeholder_users/create'))),
- distinctUntilChanged(),
- ),
+ this.currentUserService.hasCapabilities$('placeholder_users/create'),
).pipe(
map(([elements, input, hasCapability]) => {
if (!hasCapability) {
diff --git a/spec/features/users/invite_user_modal_spec.rb b/spec/features/users/invite_user_modal_spec.rb
index 4ee9990b621..eb9b673b279 100644
--- a/spec/features/users/invite_user_modal_spec.rb
+++ b/spec/features/users/invite_user_modal_spec.rb
@@ -34,10 +34,12 @@ feature 'Invite user modal', type: :feature, js: true do
shared_let(:work_package) { FactoryBot.create :work_package, project: project }
let(:permissions) { %i[view_work_packages edit_work_packages manage_members] }
+ let(:global_permissions) { %i[] }
current_user do
FactoryBot.create :user,
member_in_project: project,
- member_through_role: role
+ member_through_role: role,
+ global_permissions: global_permissions
end
let!(:role) do
@@ -100,7 +102,8 @@ feature 'Invite user modal', type: :feature, js: true do
let(:principal) { FactoryBot.build :invited_user }
context 'when the current user has permissions to create a user' do
- let(:permissions) { %i[view_work_packages edit_work_packages manage_members manage_user] }
+ let(:permissions) { %i[view_work_packages edit_work_packages manage_members] }
+ let(:global_permissions) { %i[manage_user] }
it_behaves_like 'invites the principal to the project' do
let(:added_principal) { User.find_by!(mail: principal.mail) }
@@ -118,7 +121,8 @@ feature 'Invite user modal', type: :feature, js: true do
end
context 'when the current user does not have permissions to invite a user in this project' do
- let(:permissions) { %i[view_work_packages edit_work_packages manage_members manage_user] }
+ let(:permissions) { %i[view_work_packages edit_work_packages manage_members] }
+ let(:global_permissions) { %i[manage_user] }
let(:project_no_permissions) { FactoryBot.create :project }
let(:role_no_permissions) { FactoryBot.create :role,
@@ -144,7 +148,8 @@ feature 'Invite user modal', type: :feature, js: true do
context 'an enterprise system', with_ee: %i[placeholder_users] do
describe 'create a new placeholder' do
context 'with permissions to manage placeholders' do
- let(:permissions) { %i[view_work_packages edit_work_packages manage_members manage_placeholder_user] }
+ let(:permissions) { %i[view_work_packages edit_work_packages manage_members] }
+ let(:global_permissions) { %i[manage_placeholder_user] }
it_behaves_like 'invites the principal to the project' do
let(:added_principal) { PlaceholderUser.find_by!(name: 'MY NEW PLACEHOLDER') }
@@ -163,7 +168,8 @@ feature 'Invite user modal', type: :feature, js: true do
context 'with an existing placeholder' do
let(:principal) { FactoryBot.create :placeholder_user, name: 'EXISTING PLACEHOLDER' }
- let(:permissions) { %i[view_work_packages edit_work_packages manage_members manage_placeholder_user] }
+ let(:permissions) { %i[view_work_packages edit_work_packages manage_members] }
+ let(:global_permissions) { %i[manage_placeholder_user] }
it_behaves_like 'invites the principal to the project' do
let(:added_principal) { principal }