WIP: Permissions

This commit is contained in:
aditya.chandel
2025-02-16 09:39:04 -07:00
parent 8a4da1997b
commit 80681e1757
29 changed files with 267 additions and 122 deletions
@@ -9,9 +9,11 @@
<p *ngIf="entityType === EntityType.ALL_BOOKS" class="text-2xl whitespace-nowrap overflow-hidden text-ellipsis">
All Books
</p>
<div *ngIf="entityType !== EntityType.ALL_BOOKS">
<p-button icon="pi pi-ellipsis-v" [rounded]="true" [text]="true" severity="info" (click)="entitymenu.toggle($event)"></p-button>
<p-menu #entitymenu [model]="entityOptions" [popup]="true" appendTo="body"></p-menu>
<div *ngIf="userService.userData$ | async as userData">
<div *ngIf="entityType !== EntityType.ALL_BOOKS && userData.permissions.canManipulateLibrary">
<p-button icon="pi pi-ellipsis-v" [rounded]="true" [text]="true" severity="info" (click)="entitymenu.toggle($event)"></p-button>
<p-menu #entitymenu [model]="entityOptions" [popup]="true" appendTo="body"></p-menu>
</div>
</div>
</ng-container>
</div>
@@ -134,11 +136,13 @@
severity="info"
(click)="unshelfBooks()">
</p-button>
<p-button
label="Refresh Metadata"
severity="info"
(click)="updateMetadata()">
</p-button>
<div *ngIf="userService.userData$ | async as userData">
<p-button *ngIf="userData.permissions.canEditMetadata"
label="Refresh Metadata"
severity="info"
(click)="updateMetadata()">
</p-button>
</div>
<p-button
label="Deselect All"
severity="warn"
@@ -30,6 +30,7 @@ import {FormsModule} from '@angular/forms';
import {BookFilterComponent} from './book-filter/book-filter.component';
import {Tooltip} from 'primeng/tooltip';
import {Fluid} from 'primeng/fluid';
import {UserService} from '../../../user.service';
export enum EntityType {
LIBRARY = 'Library',
@@ -89,6 +90,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
private shelfService = inject(ShelfService);
private dialogService = inject(DialogService);
private sortService = inject(SortService);
protected userService = inject(UserService);
private libraryShelfMenuService = inject(LibraryShelfMenuService);
sortOptions: any[] = [
@@ -249,7 +251,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
default:
break;
}
return { ...bookState, books: filteredBooks };
return {...bookState, books: filteredBooks};
})
);
}
@@ -15,13 +15,13 @@ import {MetadataRefreshRequest} from '../../../../metadata/model/request/metadat
import {UrlHelperService} from '../../../../utilities/service/url-helper.service';
import {AsyncPipe, NgIf} from '@angular/common';
import {SecurePipe} from '../../../../secure-pipe';
import {UserService} from '../../../../user.service';
@Component({
selector: 'app-book-card',
templateUrl: './book-card.component.html',
styleUrls: ['./book-card.component.scss'],
imports: [Button, MenuModule, CheckboxModule, FormsModule, NgIf, AsyncPipe, SecurePipe],
imports: [Button, MenuModule, CheckboxModule, FormsModule, NgIf, SecurePipe, AsyncPipe],
standalone: true
})
export class BookCardComponent implements OnInit {
@@ -37,9 +37,15 @@ export class BookCardComponent implements OnInit {
private dialogService = inject(DialogService);
private metadataDialogService = inject(MetadataDialogService);
protected urlHelper = inject(UrlHelperService);
private userService = inject(UserService);
private userPermissions: any;
ngOnInit(): void {
this.initMenu();
this.userService.userData$.subscribe((userData) => {
this.userPermissions = userData?.permissions;
});
}
readBook(book: Book): void {
@@ -63,7 +69,7 @@ export class BookCardComponent implements OnInit {
{
label: 'Assign Shelves',
icon: 'pi pi-folder',
command: () => this.openShelfDialog(this.book),
command: () => this.openShelfDialog()
},
{
label: 'View Details',
@@ -74,6 +80,7 @@ export class BookCardComponent implements OnInit {
label: 'Match Book',
icon: 'pi pi-sparkles',
command: () => this.metadataDialogService.openBookMetadataCenterDialog(this.book.id, 'match'),
disabled: !this.hasEditMetadataPermission()
},
{
label: 'Quick Refresh',
@@ -82,10 +89,11 @@ export class BookCardComponent implements OnInit {
const metadataRefreshRequest: MetadataRefreshRequest = {
quick: true,
refreshType: MetadataRefreshType.BOOKS,
bookIds: [this.book.id]
bookIds: [this.book.id],
};
this.bookService.autoRefreshMetadata(metadataRefreshRequest).subscribe();
},
disabled: !this.hasEditMetadataPermission()
},
{
label: 'Granular Refresh',
@@ -97,24 +105,26 @@ export class BookCardComponent implements OnInit {
closable: true,
data: {
bookIds: [this.book!.id],
metadataRefreshType: MetadataRefreshType.BOOKS
}
})
metadataRefreshType: MetadataRefreshType.BOOKS,
},
});
},
disabled: !this.hasEditMetadataPermission()
},
{
label: 'Download',
icon: 'pi pi-download',
command: () => {
this.bookService.downloadFile(this.book.id)
this.bookService.downloadFile(this.book.id);
},
disabled: !this.hasDownloadPermission()
},
],
},
];
}
private openShelfDialog(book: Book): void {
private openShelfDialog(): void {
this.dialogService.open(ShelfAssignerComponent, {
header: `Update Book's Shelves`,
modal: true,
@@ -126,7 +136,7 @@ export class BookCardComponent implements OnInit {
top: '15%',
},
data: {
book: this.book
book: this.book,
},
});
}
@@ -134,4 +144,12 @@ export class BookCardComponent implements OnInit {
openBookInfo(book: Book): void {
this.metadataDialogService.openBookMetadataCenterDialog(book.id, 'view');
}
private hasEditMetadataPermission(): boolean {
return this.userPermissions?.canEditMetadata ?? false;
}
private hasDownloadPermission(): boolean {
return this.userPermissions?.canDownload ?? false;
}
}
@@ -1,4 +1,4 @@
<div class="w-full h-[calc(100vh-6.6rem)] overflow-y-auto border rounded-lg p-4 enclosing-container">
<div class="w-full h-[calc(100vh-12.1rem)] overflow-y-auto border rounded-lg p-4 enclosing-container">
<p class="text-3xl font-semibold">Preferences</p>
<p-divider></p-divider>
@@ -65,7 +65,6 @@ export class BookPreferences implements OnInit {
if (settings) {
this.populateSettings(settings);
this.currentMetadataOptions = settings.metadataRefreshOptions;
console.log(this.currentMetadataOptions)
}
});
}
@@ -1,17 +1,22 @@
<div class="card">
<div class="card" *ngIf="userService.userData$ | async as userData">
<p-tabs value="0">
<p-tablist>
<p-tab value="0">Book Preferences</p-tab>
<p-tab value="1">Admin</p-tab>
<ng-container *ngIf="userData.permissions.isAdmin">
<p-tab value="1">Admin</p-tab>
</ng-container>
</p-tablist>
<p-tabpanels>
<p-tabpanel value="0">
<app-book-preferences></app-book-preferences>
</p-tabpanel>
<p-tabpanel value="1">
<app-admin></app-admin>
</p-tabpanel>
<ng-container *ngIf="userData.permissions.isAdmin">
<p-tabpanel value="1">
<app-admin></app-admin>
</p-tabpanel>
</ng-container>
</p-tabpanels>
</p-tabs>
</div>
@@ -1,7 +1,9 @@
import { Component } from '@angular/core';
import {Component, inject} from '@angular/core';
import {Tab, TabList, TabPanel, TabPanels, Tabs} from 'primeng/tabs';
import {BookPreferences} from './book-preferences/book-preferences.component';
import {AdminComponent} from './admin/admin.component';
import {UserService} from '../../../user.service';
import {AsyncPipe, NgIf} from '@angular/common';
@Component({
selector: 'app-settings',
@@ -12,11 +14,15 @@ import {AdminComponent} from './admin/admin.component';
TabPanels,
TabPanel,
BookPreferences,
AdminComponent
AdminComponent,
NgIf,
AsyncPipe
],
templateUrl: './settings.component.html',
styleUrl: './settings.component.scss'
})
export class SettingsComponent {
protected userService = inject(UserService);
}
@@ -1,8 +1,7 @@
import { Injectable, Injector } from '@angular/core';
import { inject, Injectable, Injector } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, tap } from 'rxjs';
import { RxStompService } from '../../shared/websocket/rx-stomp.service';
import { createRxStompConfig } from '../../shared/websocket/rx-stomp.config';
@Injectable({
providedIn: 'root',
@@ -11,14 +10,15 @@ export class AuthService {
private apiUrl = 'http://localhost:7050/api/v1/auth/login';
private rxStompService?: RxStompService;
constructor(private http: HttpClient, private injector: Injector) {}
private http = inject(HttpClient);
private injector = inject(Injector);
login(credentials: { username: string; password: string }): Observable<any> {
return this.http.post<{ token: string }>(this.apiUrl, credentials).pipe(
tap((response) => {
if (response.token) {
this.saveToken(response.token);
this.startWebSocket();
this.getRxStompService().activate();
}
})
);
@@ -37,15 +37,6 @@ export class AuthService {
this.getRxStompService().deactivate();
}
private startWebSocket(): void {
const token = this.getToken();
if (token) {
const rxStompService = this.getRxStompService();
rxStompService.configure(createRxStompConfig(this));
rxStompService.activate();
}
}
private getRxStompService(): RxStompService {
if (!this.rxStompService) {
this.rxStompService = this.injector.get(RxStompService);
@@ -1,5 +1,4 @@
<ng-container>
<div *ngIf="root && item.visible !== false" class="layout-menuitem-root-text">{{ item.label }}</div>
<a *ngIf="(!item.routerLink || item.items) && item.visible !== false" [attr.href]="item.url"
@@ -16,7 +15,7 @@
<a *ngIf="(item.routerLink && !item.items) && item.visible !== false" (click)="itemClick($event)"
[ngClass]="item.class"
[routerLink]="item.routerLink" routerLinkActive="active-route"
[routerLinkActiveOptions]="item.routerLinkActiveOptions||{ paths: 'exact', queryParams: 'ignored', matrixParams: 'ignored', fragment: 'ignored' }"
[routerLinkActiveOptions]="item.routerLinkActiveOptions || { paths: 'exact', queryParams: 'ignored', matrixParams: 'ignored', fragment: 'ignored' }"
[fragment]="item.fragment" [queryParamsHandling]="item.queryParamsHandling"
[preserveFragment]="item.preserveFragment"
[skipLocationChange]="item.skipLocationChange" [replaceUrl]="item.replaceUrl" [state]="item.state"
@@ -29,7 +28,7 @@
<i class="pi pi-fw pi-angle-down layout-submenu-toggler" *ngIf="item.items"></i>
</a>
<span *ngIf="(item.routerLink && !item.items) && item.visible !== false">
<ng-container *ngIf="item.type === 'Library' || item.type === 'Shelf'">
<ng-container *ngIf="(item.type === 'Library' || item.type === 'Shelf') && canManipulateLibrary">
<p-button
(click)="entitymenu.toggle($event)"
(mouseover)="hovered = true"
@@ -46,9 +45,14 @@
<p-menu #entitymenu [model]="item.menu" [popup]="true" appendTo="body"></p-menu>
</ng-container>
<ng-container *ngIf="item.type === 'Library' && !canManipulateLibrary">
<p class="text-[var(--primary-color)] pr-1">
{{ (item.bookCount$ | async)?.toString() || '0' }}
</p>
</ng-container>
<ng-container *ngIf="item.type === 'All Books'">
<p
class="text-[var(--primary-color)] pr-1">
<p class="text-[var(--primary-color)] pr-1">
{{ (item.bookCount$ | async)?.toString() || '0' }}
</p>
</ng-container>
@@ -9,11 +9,12 @@ import {Ripple} from 'primeng/ripple';
import {Button} from 'primeng/button';
import {Menu} from 'primeng/menu';
import {MenuItem} from 'primeng/api';
import {UserService} from '../../../user.service';
@Component({
selector: '[app-menuitem]',
templateUrl: './app.menuitem.component.html',
styleUrl: './app.menuitem.component.scss',
styleUrls: ['./app.menuitem.component.scss'],
imports: [
RouterLink,
RouterLinkActive,
@@ -44,13 +45,20 @@ export class AppMenuitemComponent implements OnInit, OnDestroy {
@Input() parentKey!: string;
hovered = false;
active = false;
menuSourceSubscription: Subscription;
menuResetSubscription: Subscription;
key: string = "";
constructor(public router: Router, private menuService: MenuService) {
canManipulateLibrary: boolean = false;
menuSourceSubscription: Subscription;
menuResetSubscription: Subscription;
constructor(public router: Router, private menuService: MenuService, private userService: UserService) {
this.userService.userData$.subscribe(userData => {
if (userData) {
this.canManipulateLibrary = userData.permissions.canManipulateLibrary;
}
});
this.menuSourceSubscription = this.menuService.menuSource$.subscribe(value => {
Promise.resolve(null).then(() => {
if (value.routeEvent) {
@@ -21,14 +21,14 @@
<app-book-searcher></app-book-searcher>
<ul class="topbar-items pl-6">
<div class="flex gap-6">
<li>
<a class="topbar-item">
<li *ngIf="userService.userData$ | async as userData">
<a class="topbar-item" *ngIf="userData.permissions.canManipulateLibrary">
<i class="pi pi-plus-circle text-surface-700 dark:text-surface-100" (click)="openLibraryCreatorDialog()"
pTooltip="Create New Library" tooltipPosition="top"></i>
</a>
</li>
<li>
<a class="topbar-item">
<li *ngIf="userService.userData$ | async as userData">
<a class="topbar-item" *ngIf="userData.permissions.canUpload">
<i class="pi pi-upload text-surface-700 dark:text-surface-100" (click)="openFileUploadDialog()"
pTooltip="Upload Book" tooltipPosition="top"></i>
</a>
@@ -8,7 +8,7 @@ import {TooltipModule} from 'primeng/tooltip';
import {FormsModule} from '@angular/forms';
import {InputTextModule} from 'primeng/inputtext';
import {BookSearcherComponent} from '../../../book/components/book-searcher/book-searcher.component';
import {NgClass, NgIf} from '@angular/common';
import {AsyncPipe, NgClass, NgIf} from '@angular/common';
import {EventService} from '../../../shared/websocket/event.service';
import {Button} from 'primeng/button';
import {StyleClass} from 'primeng/styleclass';
@@ -17,6 +17,7 @@ import {ThemeConfiguratorComponent} from '../theme-configurator/theme-configurat
import {LiveNotificationBoxComponent} from '../../../core/component/live-notification-box/live-notification-box.component';
import {BookUploaderComponent} from '../../../utilities/component/book-uploader/book-uploader.component';
import {AuthService} from '../../../core/service/auth.service';
import {UserService} from '../../../user.service';
@Component({
selector: 'app-topbar',
@@ -34,7 +35,8 @@ import {AuthService} from '../../../core/service/auth.service';
NgClass,
Divider,
LiveNotificationBoxComponent,
NgIf
NgIf,
AsyncPipe
],
})
export class AppTopBarComponent implements OnDestroy {
@@ -50,7 +52,8 @@ export class AppTopBarComponent implements OnDestroy {
@ViewChild('topbarmenu') menu!: ElementRef;
constructor(public layoutService: LayoutService, public dialogService: PrimeDialogService,
private eventService: EventService, private router: Router, private authService: AuthService) {
private eventService: EventService, private router: Router, private authService: AuthService,
protected userService: UserService) {
this.eventService.eventHighlight$.subscribe(highlight => {
this.eventHighlight = highlight;
});
@@ -1,19 +1,18 @@
<p-tabs [value]="tab" lazy="true" style="height: 100%; overflow: hidden;">
<p-tablist>
<p-tab value="view">Book Details</p-tab>
<p-tab value="edit">Edit Details</p-tab>
<p-tab value="match">Match Book</p-tab>
<p-tab *ngIf="canEditMetadata" value="edit">Edit Details</p-tab>
<p-tab *ngIf="canEditMetadata" value="match">Match Book</p-tab>
</p-tablist>
<p-tabpanels style="height: 100%; overflow: hidden; padding-bottom: 0">
<p-tabpanel value="view" style="height: 100%; overflow: hidden;">
<app-metadata-viewer></app-metadata-viewer>
</p-tabpanel>
<p-tabpanel value="edit" style="height: 100%; overflow: hidden;">
<p-tabpanel *ngIf="canEditMetadata" value="edit" style="height: 100%; overflow: hidden;">
<app-metadata-editor></app-metadata-editor>
</p-tabpanel>
<p-tabpanel value="match" style="height: 100%; overflow: hidden;">
<p-tabpanel *ngIf="canEditMetadata" value="match" style="height: 100%; overflow: hidden;">
<app-metadata-searcher></app-metadata-searcher>
</p-tabpanel>
</p-tabpanels>
</p-tabs>
@@ -1,36 +1,57 @@
import {Component, inject, OnInit} from '@angular/core';
import {Component, inject, OnInit, OnDestroy} from '@angular/core';
import {Tab, TabList, TabPanel, TabPanels, Tabs} from 'primeng/tabs';
import {MetadataEditorComponent} from './metadata-editor/metadata-editor.component';
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
import {MetadataSearcherComponent} from './metadata-searcher/metadata-searcher.component';
import {BookMetadataCenterService} from './book-metadata-center.service';
import {MetadataViewerComponent} from './metadata-viewer/metadata-viewer.component';
import {UserService} from '../../user.service';
import {Subscription} from 'rxjs';
import {NgIf} from '@angular/common';
@Component({
selector: 'app-book-metadata-center',
standalone: true,
templateUrl: './book-metadata-center.component.html',
styleUrl: './book-metadata-center.component.scss',
imports: [Tabs, TabList, Tab, TabPanels, MetadataEditorComponent, TabPanel, MetadataSearcherComponent, MetadataViewerComponent],
imports: [Tabs, TabList, Tab, TabPanels, MetadataEditorComponent, TabPanel, MetadataSearcherComponent, MetadataViewerComponent, NgIf],
})
export class BookMetadataCenterComponent implements OnInit {
export class BookMetadataCenterComponent implements OnInit, OnDestroy {
private dynamicDialogConfig = inject(DynamicDialogConfig);
private dynamicDialogRef = inject(DynamicDialogRef);
private metadataCenterService = inject(BookMetadataCenterService);
private userService = inject(UserService);
tab = 'view';
canEditMetadata: boolean = false;
private userSubscription: Subscription = Subscription.EMPTY;
ngOnInit(): void {
const book = this.dynamicDialogConfig.data.book;
this.tab = this.dynamicDialogConfig.data.tab;
if (book?.metadata) {
this.metadataCenterService.emit(book.metadata);
}
this.userSubscription = this.userService.userData$.subscribe(userData => {
const userPermissions = userData?.permissions;
this.canEditMetadata = userPermissions?.canEditMetadata ?? false;
});
this.metadataCenterService.dialogClose$.subscribe((close) => {
if (close) {
this.metadataCenterService.closeDialog(false);
this.dynamicDialogRef.close();
}
})
});
}
ngOnDestroy(): void {
// Clean up subscription to prevent memory leaks
if (this.userSubscription) {
this.userSubscription.unsubscribe();
}
}
}
+58 -27
View File
@@ -1,27 +1,9 @@
import {inject, Injectable} from '@angular/core';
import {inject, Injectable, Injector} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {BehaviorSubject, Observable} from 'rxjs';
import {API_CONFIG} from './config/api-config';
interface UserCreateRequest {
username: string;
password: string;
name: string;
email: string;
permissionUpload: boolean;
permissionDownload: boolean;
permissionEditMetadata: boolean;
}
interface UserUpdateRequest {
name: string;
email: string;
permissions: {
canUpload: boolean;
canDownload: boolean;
canEditMetadata: boolean;
};
}
import {jwtDecode} from 'jwt-decode';
import {RxStompService} from './shared/websocket/rx-stomp.service';
export interface User {
id: number;
@@ -29,23 +11,54 @@ export interface User {
name: string;
email: string;
permissions: {
isAdmin: boolean;
canUpload: boolean;
canDownload: boolean;
canEditMetadata: boolean;
canManipulateLibrary: boolean;
};
isEditing?: boolean;
}
interface JwtPayload {
sub: string;
userId: number;
}
@Injectable({
providedIn: 'root'
})
export class UserService {
private http = inject(HttpClient);
private readonly apiUrl = `${API_CONFIG.BASE_URL}/api/v1/auth/register`;
private readonly userUrl = `${API_CONFIG.BASE_URL}/api/v1/users`;
createUser(userData: UserCreateRequest): Observable<{ message: string }> {
private http = inject(HttpClient);
private injector = inject(Injector);
private rxStompService?: RxStompService;
private userDataSubject = new BehaviorSubject<User | null>(null);
userData$ = this.userDataSubject.asObservable();
constructor() {
this.loadUserFromToken();
}
private loadUserFromToken(): void {
const token = localStorage.getItem('token');
if (token) {
const decoded: JwtPayload = jwtDecode(token);
this.fetchUser(decoded.userId);
}
}
fetchUser(userId: number): void {
this.http.get<User>(`${this.userUrl}/${userId}`).subscribe(user => {
this.userDataSubject.next(user);
this.startWebSocket(); // Start WebSocket after user data is loaded
});
}
createUser(userData: Omit<User, 'id'>): Observable<{ message: string }> {
return this.http.post<{ message: string }>(this.apiUrl, userData);
}
@@ -53,7 +66,7 @@ export class UserService {
return this.http.get<User[]>(this.userUrl);
}
updateUser(userId: number, updateData: UserUpdateRequest): Observable<{ message: string }> {
updateUser(userId: number, updateData: Partial<User>): Observable<{ message: string }> {
return this.http.put<{ message: string }>(`${this.userUrl}/${userId}`, updateData);
}
@@ -61,4 +74,22 @@ export class UserService {
return this.http.delete<void>(`${this.userUrl}/${userId}`);
}
private startWebSocket(): void {
const token = this.getToken();
if (token) {
const rxStompService = this.getRxStompService();
rxStompService.activate();
}
}
private getRxStompService(): RxStompService {
if (!this.rxStompService) {
this.rxStompService = this.injector.get(RxStompService);
}
return this.rxStompService;
}
getToken(): string | null {
return localStorage.getItem('token');
}
}