Skip to content

Open Source Wealth Management Software. Angular + NestJS + Prisma + Nx + TypeScript 🤍

Feature/add support to update granted access (#5566)

Germán Martín20a756a37606
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d3b1fa120b..a595800e18 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- Added support to edit a granted access (experimental)
- Added support for a date range query parameter in the data gathering endpoint
- Added a _Storybook_ story for the activities table component
diff --git a/apps/api/src/app/access/access.controller.ts b/apps/api/src/app/access/access.controller.ts
index bc2d22e518..cb1e2d4afc 100644
--- a/apps/api/src/app/access/access.controller.ts
+++ b/apps/api/src/app/access/access.controller.ts
@@ -14,6 +14,7 @@ import {
Inject,
Param,
Post,
+ Put,
UseGuards
} from '@nestjs/common';
import { REQUEST } from '@nestjs/core';
@@ -23,6 +24,7 @@ import { StatusCodes, getReasonPhrase } from 'http-status-codes';
import { AccessService } from './access.service';
import { CreateAccessDto } from './create-access.dto';
+import { UpdateAccessDto } from './update-access.dto';
@Controller('access')
export class AccessController {
@@ -39,7 +41,7 @@ export class AccessController {
include: {
granteeUser: true
},
- orderBy: { granteeUserId: 'asc' },
+ orderBy: [{ granteeUserId: 'desc' }, { createdAt: 'asc' }],
where: { userId: this.request.user.id }
});
@@ -103,9 +105,12 @@ export class AccessController {
@HasPermission(permissions.deleteAccess)
@UseGuards(AuthGuard('jwt'), HasPermissionGuard)
public async deleteAccess(@Param('id') id: string): Promise<AccessModel> {
- const access = await this.accessService.access({ id });
+ const originalAccess = await this.accessService.access({
+ id,
+ userId: this.request.user.id
+ });
- if (!access || access.userId !== this.request.user.id) {
+ if (!originalAccess) {
throw new HttpException(
getReasonPhrase(StatusCodes.FORBIDDEN),
StatusCodes.FORBIDDEN
@@ -116,4 +121,52 @@ export class AccessController {
id
});
}
+
+ @HasPermission(permissions.updateAccess)
+ @Put(':id')
+ @UseGuards(AuthGuard('jwt'), HasPermissionGuard)
+ public async updateAccess(
+ @Body() data: UpdateAccessDto,
+ @Param('id') id: string
+ ): Promise<AccessModel> {
+ if (
+ this.configurationService.get('ENABLE_FEATURE_SUBSCRIPTION') &&
+ this.request.user.subscription.type === 'Basic'
+ ) {
+ throw new HttpException(
+ getReasonPhrase(StatusCodes.FORBIDDEN),
+ StatusCodes.FORBIDDEN
+ );
+ }
+
+ const originalAccess = await this.accessService.access({
+ id,
+ userId: this.request.user.id
+ });
+
+ if (!originalAccess) {
+ throw new HttpException(
+ getReasonPhrase(StatusCodes.FORBIDDEN),
+ StatusCodes.FORBIDDEN
+ );
+ }
+
+ try {
+ return this.accessService.updateAccess({
+ data: {
+ alias: data.alias,
+ granteeUser: data.granteeUserId
+ ? { connect: { id: data.granteeUserId } }
+ : { disconnect: true },
+ permissions: data.permissions
+ },
+ where: { id }
+ });
+ } catch {
+ throw new HttpException(
+ getReasonPhrase(StatusCodes.BAD_REQUEST),
+ StatusCodes.BAD_REQUEST
+ );
+ }
+ }
}
diff --git a/apps/api/src/app/access/access.service.ts b/apps/api/src/app/access/access.service.ts
index 8403cdc09f..70e46dc369 100644
--- a/apps/api/src/app/access/access.service.ts
+++ b/apps/api/src/app/access/access.service.ts
@@ -20,14 +20,14 @@ export class AccessService {
}
public async accesses(params: {
+ cursor?: Prisma.AccessWhereUniqueInput;
include?: Prisma.AccessInclude;
+ orderBy?: Prisma.Enumerable<Prisma.AccessOrderByWithRelationInput>;
skip?: number;
take?: number;
- cursor?: Prisma.AccessWhereUniqueInput;
where?: Prisma.AccessWhereInput;
- orderBy?: Prisma.AccessOrderByWithRelationInput;
}): Promise<AccessWithGranteeUser[]> {
- const { include, skip, take, cursor, where, orderBy } = params;
+ const { cursor, include, orderBy, skip, take, where } = params;
return this.prismaService.access.findMany({
cursor,
@@ -52,4 +52,17 @@ export class AccessService {
where
});
}
+
+ public async updateAccess({
+ data,
+ where
+ }: {
+ data: Prisma.AccessUpdateInput;
+ where: Prisma.AccessWhereUniqueInput;
+ }): Promise<Access> {
+ return this.prismaService.access.update({
+ data,
+ where
+ });
+ }
}
diff --git a/apps/api/src/app/access/update-access.dto.ts b/apps/api/src/app/access/update-access.dto.ts
new file mode 100644
index 0000000000..2850186f9b
--- /dev/null
+++ b/apps/api/src/app/access/update-access.dto.ts
@@ -0,0 +1,19 @@
+import { AccessPermission } from '@prisma/client';
+import { IsEnum, IsOptional, IsString, IsUUID } from 'class-validator';
+
+export class UpdateAccessDto {
+ @IsOptional()
+ @IsString()
+ alias?: string;
+
+ @IsOptional()
+ @IsUUID()
+ granteeUserId?: string;
+
+ @IsString()
+ id: string;
+
+ @IsEnum(AccessPermission, { each: true })
+ @IsOptional()
+ permissions?: AccessPermission[];
+}
diff --git a/apps/client/src/app/components/access-table/access-table.component.html b/apps/client/src/app/components/access-table/access-table.component.html
index be374db9cb..e61ee0c9e6 100644
--- a/apps/client/src/app/components/access-table/access-table.component.html
+++ b/apps/client/src/app/components/access-table/access-table.component.html
@@ -65,6 +65,14 @@
<ion-icon name="ellipsis-horizontal" />
</button>
<mat-menu #transactionMenu="matMenu" xPosition="before">
+ @if (user?.settings?.isExperimentalFeatures) {
+ <button mat-menu-item (click)="onUpdateAccess(element.id)">
+ <span class="align-items-center d-flex">
+ <ion-icon class="mr-2" name="create-outline" />
+ <span i18n>Edit</span>
+ </span>
+ </button>
+ }
@if (element.type === 'PUBLIC') {
<button mat-menu-item (click)="onCopyUrlToClipboard(element.id)">
<span class="align-items-center d-flex">
@@ -72,6 +80,10 @@
<span i18n>Copy link to clipboard</span>
</span>
</button>
+ }
+ @if (
+ user?.settings?.isExperimentalFeatures || element.type === 'PUBLIC'
+ ) {
<hr class="my-0" />
}
<button mat-menu-item (click)="onDeleteAccess(element.id)">
diff --git a/apps/client/src/app/components/access-table/access-table.component.ts b/apps/client/src/app/components/access-table/access-table.component.ts
index 9f32be650a..645d43253b 100644
--- a/apps/client/src/app/components/access-table/access-table.component.ts
+++ b/apps/client/src/app/components/access-table/access-table.component.ts
@@ -23,6 +23,7 @@ import { IonIcon } from '@ionic/angular/standalone';
import { addIcons } from 'ionicons';
import {
copyOutline,
+ createOutline,
ellipsisHorizontal,
linkOutline,
lockClosedOutline,
@@ -53,6 +54,7 @@ export class GfAccessTableComponent implements OnChanges {
@Input() user: User;
@Output() accessDeleted = new EventEmitter<string>();
+ @Output() accessToUpdate = new EventEmitter<string>();
public baseUrl = window.location.origin;
public dataSource: MatTableDataSource<Access>;
@@ -65,6 +67,7 @@ export class GfAccessTableComponent implements OnChanges {
) {
addIcons({
copyOutline,
+ createOutline,
ellipsisHorizontal,
linkOutline,
lockClosedOutline,
@@ -112,4 +115,8 @@ export class GfAccessTableComponent implements OnChanges {
title: $localize`Do you really want to revoke this granted access?`
});
}
+
+ public onUpdateAccess(aId: string) {
+ this.accessToUpdate.emit(aId);
+ }
}
diff --git a/apps/client/src/app/components/user-account-access/create-or-update-access-dialog/create-or-update-access-dialog.component.ts b/apps/client/src/app/components/user-account-access/create-or-update-access-dialog/create-or-update-access-dialog.component.ts
index 067eb2d59a..315f86244b 100644
--- a/apps/client/src/app/components/user-account-access/create-or-update-access-dialog/create-or-update-access-dialog.component.ts
+++ b/apps/client/src/app/components/user-account-access/create-or-update-access-dialog/create-or-update-access-dialog.component.ts
@@ -1,4 +1,5 @@
import { CreateAccessDto } from '@ghostfolio/api/app/access/create-access.dto';
+import { UpdateAccessDto } from '@ghostfolio/api/app/access/update-access.dto';
import { NotificationService } from '@ghostfolio/client/core/notification/notification.service';
import { DataService } from '@ghostfolio/client/services/data.service';
import { validateObjectForForm } from '@ghostfolio/client/util/form.util';
@@ -8,7 +9,8 @@ import {
ChangeDetectorRef,
Component,
Inject,
- OnDestroy
+ OnDestroy,
+ OnInit
} from '@angular/core';
import {
FormBuilder,
@@ -47,8 +49,11 @@ import { CreateOrUpdateAccessDialogParams } from './interfaces/interfaces';
styleUrls: ['./create-or-update-access-dialog.scss'],
templateUrl: 'create-or-update-access-dialog.html'
})
-export class GfCreateOrUpdateAccessDialogComponent implements OnDestroy {
+export class GfCreateOrUpdateAccessDialogComponent
+ implements OnDestroy, OnInit
+{
public accessForm: FormGroup;
+ public mode: 'create' | 'update';
private unsubscribeSubject = new Subject<void>();
@@ -59,14 +64,24 @@ export class GfCreateOrUpdateAccessDialogComponent implements OnDestroy {
private dataService: DataService,
private formBuilder: FormBuilder,
private notificationService: NotificationService
- ) {}
+ ) {
+ this.mode = this.data.access?.id ? 'update' : 'create';
+ }
public ngOnInit() {
+ const isPublic = this.data.access.type === 'PUBLIC';
+
this.accessForm = this.formBuilder.group({
alias: [this.data.access.alias],
+ granteeUserId: [
+ this.data.access.grantee,
+ isPublic ? null : Validators.required
+ ],
permissions: [this.data.access.permissions[0], Validators.required],
- type: [this.data.access.type, Validators.required],
- granteeUserId: [this.data.access.grantee, Validators.required]
+ type: [
+ { disabled: this.mode === 'update', value: this.data.access.type },
+ Validators.required
+ ]
});
this.accessForm.get('type').valueChanges.subscribe((accessType) => {
@@ -77,6 +92,7 @@ export class GfCreateOrUpdateAccessDialogComponent implements OnDestroy {
granteeUserIdControl.setValidators(Validators.required);
} else {
granteeUserIdControl.clearValidators();
+ granteeUserIdControl.setValue(null);
permissionsControl.setValue(this.data.access.permissions[0]);
}
@@ -91,6 +107,19 @@ export class GfCreateOrUpdateAccessDialogComponent implements OnDestroy {
}
public async onSubmit() {
+ if (this.mode === 'create') {
+ await this.createAccess();
+ } else {
+ await this.updateAccess();
+ }
+ }
+
+ public ngOnDestroy() {
+ this.unsubscribeSubject.next();
+ this.unsubscribeSubject.complete();
+ }
+
+ private async createAccess() {
const access: CreateAccessDto = {
alias: this.accessForm.get('alias').value,
granteeUserId: this.accessForm.get('granteeUserId').value,
@@ -126,8 +155,40 @@ export class GfCreateOrUpdateAccessDialogComponent implements OnDestroy {
}
}
- public ngOnDestroy() {
- this.unsubscribeSubject.next();
- this.unsubscribeSubject.complete();
+ private async updateAccess() {
+ const access: UpdateAccessDto = {
+ alias: this.accessForm.get('alias').value,
+ granteeUserId: this.accessForm.get('granteeUserId').value,
+ id: this.data.access.id,
+ permissions: [this.accessForm.get('permissions').value]
+ };
+
+ try {
+ await validateObjectForForm({
+ classDto: UpdateAccessDto,
+ form: this.accessForm,
+ object: access
+ });
+
+ this.dataService
+ .putAccess(access)
+ .pipe(
+ catchError(({ status }) => {
+ if (status.status === StatusCodes.BAD_REQUEST) {
+ this.notificationService.alert({
+ title: $localize`Oops! Could not update access.`
+ });
+ }
+
+ return EMPTY;
+ }),
+ takeUntil(this.unsubscribeSubject)
+ )
+ .subscribe(() => {
+ this.dialogRef.close(access);
+ });
+ } catch (error) {
+ console.error(error);
+ }
}
}
diff --git a/apps/client/src/app/components/user-account-access/create-or-update-access-dialog/create-or-update-access-dialog.html b/apps/client/src/app/components/user-account-access/create-or-update-access-dialog/create-or-update-access-dialog.html
index 210933d616..4a7f624abd 100644
--- a/apps/client/src/app/components/user-account-access/create-or-update-access-dialog/create-or-update-access-dialog.html
+++ b/apps/client/src/app/components/user-account-access/create-or-update-access-dialog/create-or-update-access-dialog.html
@@ -4,7 +4,13 @@
(keyup.enter)="accessForm.valid && onSubmit()"
(ngSubmit)="onSubmit()"
>
- <h1 i18n mat-dialog-title>Grant access</h1>
+ <h1 mat-dialog-title>
+ @if (mode === 'create') {
+ <span i18n>Grant access</span>
+ } @else {
+ <span i18n>Edit access</span>
+ }
+ </h1>
<div class="flex-grow-1 py-3" mat-dialog-content>
<div>
<mat-form-field appearance="outline" class="w-100">
@@ -66,9 +72,17 @@
color="primary"
mat-flat-button
type="submit"
- [disabled]="!(accessForm.dirty && accessForm.valid)"
+ [disabled]="
+ mode === 'create'
+ ? !(accessForm.dirty && accessForm.valid)
+ : !accessForm.valid
+ "
>
- <ng-container i18n>Save</ng-container>
+ @if (mode === 'create') {
+ <ng-container i18n>Save</ng-container>
+ } @else {
+ <ng-container i18n>Update</ng-container>
+ }
</button>
</div>
</form>
diff --git a/apps/client/src/app/components/user-account-access/user-account-access.component.ts b/apps/client/src/app/components/user-account-access/user-account-access.component.ts
index 178df374de..bdb9af6ed2 100644
--- a/apps/client/src/app/components/user-account-access/user-account-access.component.ts
+++ b/apps/client/src/app/components/user-account-access/user-account-access.component.ts
@@ -115,6 +115,8 @@ export class GfUserAccountAccessComponent implements OnDestroy, OnInit {
.subscribe((params) => {
if (params['createDialog']) {
this.openCreateAccessDialog();
+ } else if (params['editDialog'] && params['accessId']) {
+ this.openUpdateAccessDialog(params['accessId']);
}
});
@@ -173,6 +175,12 @@ export class GfUserAccountAccessComponent implements OnDestroy, OnInit {
});
}
+ public onUpdateAccess(aId: string) {
+ this.router.navigate([], {
+ queryParams: { accessId: aId, editDialog: true }
+ });
+ }
+
public ngOnDestroy() {
this.unsubscribeSubject.next();
this.unsubscribeSubject.complete();
@@ -200,6 +208,40 @@ export class GfUserAccountAccessComponent implements OnDestroy, OnInit {
});
}
+ private openUpdateAccessDialog(accessId: string) {
+ const access = this.accessesGive?.find(({ id }) => {
+ return id === accessId;
+ });
+
+ if (!access) {
+ console.log('Could not find access.');
+
+ return;
+ }
+
+ const dialogRef = this.dialog.open(GfCreateOrUpdateAccessDialogComponent, {
+ data: {
+ access: {
+ alias: access.alias,
+ id: access.id,
+ grantee: access.grantee === 'Public' ? null : access.grantee,
+ permissions: access.permissions,
+ type: access.type
+ }
+ },
+ height: this.deviceType === 'mobile' ? '98vh' : undefined,
+ width: this.deviceType === 'mobile' ? '100vw' : '50rem'
+ });
+
+ dialogRef.afterClosed().subscribe((result) => {
+ if (result) {
+ this.update();
+ }
+
+ this.router.navigate(['.'], { relativeTo: this.route });
+ });
+ }
+
private update() {
this.accessesGet = this.user.access.map(({ alias, id, permissions }) => {
return {
diff --git a/apps/client/src/app/components/user-account-access/user-account-access.html b/apps/client/src/app/components/user-account-access/user-account-access.html
index 2979fd6fa0..8160c2c8e9 100644
--- a/apps/client/src/app/components/user-account-access/user-account-access.html
+++ b/apps/client/src/app/components/user-account-access/user-account-access.html
@@ -64,6 +64,7 @@
[showActions]="hasPermissionToDeleteAccess"
[user]="user"
(accessDeleted)="onDeleteAccess($event)"
+ (accessToUpdate)="onUpdateAccess($event)"
/>
@if (hasPermissionToCreateAccess) {
<div class="fab-container">
diff --git a/apps/client/src/app/services/data.service.ts b/apps/client/src/app/services/data.service.ts
index 6ab370399f..c2678924b8 100644
--- a/apps/client/src/app/services/data.service.ts
+++ b/apps/client/src/app/services/data.service.ts
@@ -1,4 +1,5 @@
import { CreateAccessDto } from '@ghostfolio/api/app/access/create-access.dto';
+import { UpdateAccessDto } from '@ghostfolio/api/app/access/update-access.dto';
import { CreateAccountBalanceDto } from '@ghostfolio/api/app/account-balance/create-account-balance.dto';
import { CreateAccountDto } from '@ghostfolio/api/app/account/create-account.dto';
import { TransferBalanceDto } from '@ghostfolio/api/app/account/transfer-balance.dto';
@@ -792,6 +793,10 @@ export class DataService {
return this.http.post('/api/v1/watchlist', watchlistItem);
}
+ public putAccess(aAccess: UpdateAccessDto) {
+ return this.http.put<Access>(`/api/v1/access/${aAccess.id}`, aAccess);
+ }
+
public putAccount(aAccount: UpdateAccountDto) {
return this.http.put<UserItem>(`/api/v1/account/${aAccount.id}`, aAccount);
}
diff --git a/libs/common/src/lib/permissions.ts b/libs/common/src/lib/permissions.ts
index 52794f7dcb..51f327d32f 100644
--- a/libs/common/src/lib/permissions.ts
+++ b/libs/common/src/lib/permissions.ts
@@ -49,6 +49,7 @@ export const permissions = {
syncDemoUserAccount: 'syncDemoUserAccount',
toggleReadOnlyMode: 'toggleReadOnlyMode',
updateAccount: 'updateAccount',
+ updateAccess: 'updateAccess',
updateAuthDevice: 'updateAuthDevice',
updateMarketData: 'updateMarketData',
updateMarketDataOfOwnAssetProfile: 'updateMarketDataOfOwnAssetProfile',
@@ -93,6 +94,7 @@ export function getPermissions(aRole: Role): string[] {
permissions.readTags,
permissions.readWatchlist,
permissions.updateAccount,
+ permissions.updateAccess,
permissions.updateAuthDevice,
permissions.updateMarketData,
permissions.updateMarketDataOfOwnAssetProfile,
@@ -133,6 +135,7 @@ export function getPermissions(aRole: Role): string[] {
permissions.readMarketDataOfOwnAssetProfile,
permissions.readWatchlist,
permissions.updateAccount,
+ permissions.updateAccess,
permissions.updateAuthDevice,
permissions.updateMarketDataOfOwnAssetProfile,
permissions.updateOrder,