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
@@ -30,6 +30,7 @@ public class ApplicationStartupRunner implements CommandLineRunner {
permissions.setUser(admin);
permissions.setPermissionUpload(true);
permissions.setPermissionDownload(true);
permissions.setPermissionManipulateLibrary(true);
permissions.setPermissionEditMetadata(true);
permissions.setPermissionAdmin(true);
@@ -68,6 +68,12 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
if (permissions.isPermissionEditMetadata()) {
authorities.add(new SimpleGrantedAuthority("ROLE_EDIT_METADATA"));
}
if (permissions.isPermissionManipulateLibrary()) {
authorities.add(new SimpleGrantedAuthority("ROLE_MANIPULATE_LIBRARY"));
}
if (permissions.isPermissionAdmin()) {
authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
}
return authorities;
}
}
@@ -1,25 +1,32 @@
package com.adityachandel.booklore.config.security;
import io.jsonwebtoken.*;
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
import io.jsonwebtoken.security.Keys;
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
import org.springframework.stereotype.Component;
import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Component
public class JwtUtils {
private final String secretKey = "G6u4m3g7M/b93k7m9a1h1Kw4l3D+5WqXldpl4nTjl4s=";
private SecretKey getSigningKey() {
return Keys.hmacShaKeyFor(secretKey.getBytes(StandardCharsets.UTF_8));
}
public String generateToken(BookLoreUserEntity user) {
SecretKey key = Keys.hmacShaKeyFor(secretKey.getBytes(StandardCharsets.UTF_8));
SecretKey key = getSigningKey();
Date now = new Date();
Date expirationDate = new Date(now.getTime() + 1000 * 60 * 60 * 10);
return Jwts.builder()
.claim("sub", user.getUsername())
.subject(user.getUsername())
.claim("userId", user.getId())
.issuedAt(now)
.expiration(expirationDate)
.signWith(key, Jwts.SIG.HS256)
@@ -27,27 +34,26 @@ public class JwtUtils {
}
public boolean validateToken(String token) {
return !isTokenExpired(token);
try {
return !isTokenExpired(token);
} catch (JwtException e) {
return false;
}
}
public Claims extractClaims(String token) {
return Jwts.parser()
.verifyWith(getSigningKey())
.build()
.parseSignedClaims(token)
.getPayload();
}
public String extractUsername(String token) {
SecretKey key = Keys.hmacShaKeyFor(secretKey.getBytes(StandardCharsets.UTF_8));
return Jwts.parser()
.verifyWith(key)
.build()
.parseSignedClaims(token)
.getPayload()
.getSubject();
return extractClaims(token).getSubject();
}
private boolean isTokenExpired(String token) {
SecretKey key = Keys.hmacShaKeyFor(secretKey.getBytes(StandardCharsets.UTF_8));
return Jwts.parser()
.verifyWith(key)
.build()
.parseSignedClaims(token)
.getPayload()
.getExpiration()
.before(new Date());
return extractClaims(token).getExpiration().before(new Date());
}
}
}
@@ -3,6 +3,7 @@ package com.adityachandel.booklore.config.security;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
@@ -17,6 +18,7 @@ import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import java.util.List;
@AllArgsConstructor
@EnableMethodSecurity
@Configuration
public class SecurityConfig {
@@ -22,12 +22,19 @@ public class UserController {
private final UserService userService;
@GetMapping("/{id}")
public ResponseEntity<BookLoreUser> getUser(@PathVariable Long id) {
return ResponseEntity.ok(userService.getBookLoreUser(id));
}
@GetMapping
@PreAuthorize("hasRole('ADMIN')")
public ResponseEntity<List<BookLoreUser>> getAllUsers() {
return ResponseEntity.ok(userService.getBookLoreUsers());
}
@PutMapping("/{id}")
@PreAuthorize("hasRole('ADMIN')")
public ResponseEntity<BookLoreUser> updateUser(@PathVariable Long id, @Valid @RequestBody UserUpdateRequest updateRequest) {
BookLoreUser updatedUser = userService.updateUser(id, updateRequest);
return ResponseEntity.ok(updatedUser);
@@ -5,6 +5,7 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@@ -51,6 +52,12 @@ public class GlobalExceptionHandler {
return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(AccessDeniedException.class)
public ResponseEntity<ErrorResponse> handleAccessDeniedException(AccessDeniedException ex) {
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.FORBIDDEN.value(), "Access Denied: " + ex.getMessage());
return new ResponseEntity<>(errorResponse, HttpStatus.FORBIDDEN);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleGenericException(Exception ex) {
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), "An unexpected error occurred.");
@@ -17,8 +17,11 @@ public interface BookLoreUserMapper {
return null;
}
BookLoreUser.UserPermissions dto = new BookLoreUser.UserPermissions();
dto.setAdmin(permissions.isPermissionAdmin());
dto.setCanUpload(permissions.isPermissionUpload());
dto.setCanDownload(permissions.isPermissionDownload());
dto.setCanManipulateLibrary(permissions.isPermissionManipulateLibrary());
dto.setCanEditMetadata(permissions.isPermissionEditMetadata());
dto.setCanEditMetadata(permissions.isPermissionEditMetadata());
return dto;
}
@@ -12,8 +12,10 @@ public class BookLoreUser {
@Data
public static class UserPermissions {
private boolean isAdmin;
private boolean canUpload;
private boolean canDownload;
private boolean canEditMetadata;
private boolean canManipulateLibrary;
}
}
@@ -12,4 +12,5 @@ public class UserCreateRequest {
private boolean permissionUpload;
private boolean permissionDownload;
private boolean permissionEditMetadata;
private boolean permissionManipulateLibrary;
}
@@ -29,6 +29,9 @@ public class UserPermissionsEntity {
@Column(name = "permission_edit_metadata", nullable = false)
private boolean permissionEditMetadata = false;
@Column(name = "permission_manipulate_library", nullable = false)
private boolean permissionManipulateLibrary = false;
@Column(name = "permission_admin", nullable = false)
private boolean permissionAdmin;
}
@@ -50,6 +50,7 @@ public class UserService {
permissions.setPermissionUpload(request.isPermissionUpload());
permissions.setPermissionDownload(request.isPermissionDownload());
permissions.setPermissionEditMetadata(request.isPermissionEditMetadata());
permissions.setPermissionEditMetadata(request.isPermissionManipulateLibrary());
bookLoreUserEntity.setPermissions(permissions);
@@ -64,8 +65,7 @@ public class UserService {
}
public ResponseEntity<Map<String, String>> loginUser(UserLoginRequest loginRequest) {
BookLoreUserEntity user = userRepository.findByUsername(loginRequest.getUsername())
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(loginRequest.getUsername()));
BookLoreUserEntity user = userRepository.findByUsername(loginRequest.getUsername()).orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(loginRequest.getUsername()));
if (!passwordEncoder.matches(loginRequest.getPassword(), user.getPasswordHash())) {
throw ApiError.INVALID_CREDENTIALS.createException();
@@ -111,4 +111,8 @@ public class UserService {
}
public BookLoreUser getBookLoreUser(Long id) {
BookLoreUserEntity user = userRepository.findById(id).orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(id));
return bookLoreUserMapper.toDto(user);
}
}
@@ -181,12 +181,13 @@ CREATE TABLE IF NOT EXISTS users
CREATE TABLE IF NOT EXISTS user_permissions
(
id BIGINT AUTO_INCREMENT PRIMARY KEY,
user_id BIGINT NOT NULL,
permission_upload BOOLEAN NOT NULL DEFAULT FALSE,
permission_download BOOLEAN NOT NULL DEFAULT FALSE,
permission_edit_metadata BOOLEAN NOT NULL DEFAULT FALSE,
permission_admin BOOLEAN NOT NULL DEFAULT FALSE,
id BIGINT AUTO_INCREMENT PRIMARY KEY,
user_id BIGINT NOT NULL,
permission_upload BOOLEAN NOT NULL DEFAULT FALSE,
permission_download BOOLEAN NOT NULL DEFAULT FALSE,
permission_edit_metadata BOOLEAN NOT NULL DEFAULT FALSE,
permission_manipulate_library BOOLEAN NOT NULL DEFAULT FALSE,
permission_admin BOOLEAN NOT NULL DEFAULT FALSE,
CONSTRAINT fk_user_permissions_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
);
+10
View File
@@ -21,6 +21,7 @@
"@stomp/rx-stomp": "^2.0.0",
"@stomp/stompjs": "^7.0.0",
"epubjs": "^0.3.93",
"jwt-decode": "^4.0.0",
"ng-lazyload-image": "^9.1.3",
"ngx-extended-pdf-viewer": "23.0.0-alpha.1",
"ngx-infinite-scroll": "^19.0.0",
@@ -10737,6 +10738,15 @@
"safe-buffer": "~5.1.0"
}
},
"node_modules/jwt-decode": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/jwt-decode/-/jwt-decode-4.0.0.tgz",
"integrity": "sha512-+KJGIyHgkGuIq3IEBNftfhW/LfWhXUIY6OmyVWjliu5KH1y0fw7VQ8YndE2O4qZdMSd9SqbnC8GOcZEy0Om7sA==",
"license": "MIT",
"engines": {
"node": ">=18"
}
},
"node_modules/karma": {
"version": "6.4.4",
"resolved": "https://registry.npmjs.org/karma/-/karma-6.4.4.tgz",
+1
View File
@@ -24,6 +24,7 @@
"@stomp/rx-stomp": "^2.0.0",
"@stomp/stompjs": "^7.0.0",
"epubjs": "^0.3.93",
"jwt-decode": "^4.0.0",
"ng-lazyload-image": "^9.1.3",
"ngx-extended-pdf-viewer": "23.0.0-alpha.1",
"ngx-infinite-scroll": "^19.0.0",
@@ -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');
}
}