WIP: Permissions
This commit is contained in:
+1
@@ -30,6 +30,7 @@ public class ApplicationStartupRunner implements CommandLineRunner {
|
|||||||
permissions.setUser(admin);
|
permissions.setUser(admin);
|
||||||
permissions.setPermissionUpload(true);
|
permissions.setPermissionUpload(true);
|
||||||
permissions.setPermissionDownload(true);
|
permissions.setPermissionDownload(true);
|
||||||
|
permissions.setPermissionManipulateLibrary(true);
|
||||||
permissions.setPermissionEditMetadata(true);
|
permissions.setPermissionEditMetadata(true);
|
||||||
permissions.setPermissionAdmin(true);
|
permissions.setPermissionAdmin(true);
|
||||||
|
|
||||||
|
|||||||
+6
@@ -68,6 +68,12 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
|||||||
if (permissions.isPermissionEditMetadata()) {
|
if (permissions.isPermissionEditMetadata()) {
|
||||||
authorities.add(new SimpleGrantedAuthority("ROLE_EDIT_METADATA"));
|
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;
|
return authorities;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+25
-19
@@ -1,25 +1,32 @@
|
|||||||
package com.adityachandel.booklore.config.security;
|
package com.adityachandel.booklore.config.security;
|
||||||
|
|
||||||
import io.jsonwebtoken.*;
|
import io.jsonwebtoken.*;
|
||||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
|
||||||
import io.jsonwebtoken.security.Keys;
|
import io.jsonwebtoken.security.Keys;
|
||||||
|
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
import javax.crypto.SecretKey;
|
import javax.crypto.SecretKey;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
@Component
|
@Component
|
||||||
public class JwtUtils {
|
public class JwtUtils {
|
||||||
private final String secretKey = "G6u4m3g7M/b93k7m9a1h1Kw4l3D+5WqXldpl4nTjl4s=";
|
private final String secretKey = "G6u4m3g7M/b93k7m9a1h1Kw4l3D+5WqXldpl4nTjl4s=";
|
||||||
|
|
||||||
|
private SecretKey getSigningKey() {
|
||||||
|
return Keys.hmacShaKeyFor(secretKey.getBytes(StandardCharsets.UTF_8));
|
||||||
|
}
|
||||||
|
|
||||||
public String generateToken(BookLoreUserEntity user) {
|
public String generateToken(BookLoreUserEntity user) {
|
||||||
SecretKey key = Keys.hmacShaKeyFor(secretKey.getBytes(StandardCharsets.UTF_8));
|
SecretKey key = getSigningKey();
|
||||||
Date now = new Date();
|
Date now = new Date();
|
||||||
Date expirationDate = new Date(now.getTime() + 1000 * 60 * 60 * 10);
|
Date expirationDate = new Date(now.getTime() + 1000 * 60 * 60 * 10);
|
||||||
|
|
||||||
return Jwts.builder()
|
return Jwts.builder()
|
||||||
.claim("sub", user.getUsername())
|
.subject(user.getUsername())
|
||||||
|
.claim("userId", user.getId())
|
||||||
.issuedAt(now)
|
.issuedAt(now)
|
||||||
.expiration(expirationDate)
|
.expiration(expirationDate)
|
||||||
.signWith(key, Jwts.SIG.HS256)
|
.signWith(key, Jwts.SIG.HS256)
|
||||||
@@ -27,27 +34,26 @@ public class JwtUtils {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public boolean validateToken(String token) {
|
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) {
|
public String extractUsername(String token) {
|
||||||
SecretKey key = Keys.hmacShaKeyFor(secretKey.getBytes(StandardCharsets.UTF_8));
|
return extractClaims(token).getSubject();
|
||||||
return Jwts.parser()
|
|
||||||
.verifyWith(key)
|
|
||||||
.build()
|
|
||||||
.parseSignedClaims(token)
|
|
||||||
.getPayload()
|
|
||||||
.getSubject();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean isTokenExpired(String token) {
|
private boolean isTokenExpired(String token) {
|
||||||
SecretKey key = Keys.hmacShaKeyFor(secretKey.getBytes(StandardCharsets.UTF_8));
|
return extractClaims(token).getExpiration().before(new Date());
|
||||||
return Jwts.parser()
|
|
||||||
.verifyWith(key)
|
|
||||||
.build()
|
|
||||||
.parseSignedClaims(token)
|
|
||||||
.getPayload()
|
|
||||||
.getExpiration()
|
|
||||||
.before(new Date());
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+2
@@ -3,6 +3,7 @@ package com.adityachandel.booklore.config.security;
|
|||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.Configuration;
|
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.builders.HttpSecurity;
|
||||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||||
@@ -17,6 +18,7 @@ import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
|
@EnableMethodSecurity
|
||||||
@Configuration
|
@Configuration
|
||||||
public class SecurityConfig {
|
public class SecurityConfig {
|
||||||
|
|
||||||
|
|||||||
@@ -22,12 +22,19 @@ public class UserController {
|
|||||||
|
|
||||||
private final UserService userService;
|
private final UserService userService;
|
||||||
|
|
||||||
|
@GetMapping("/{id}")
|
||||||
|
public ResponseEntity<BookLoreUser> getUser(@PathVariable Long id) {
|
||||||
|
return ResponseEntity.ok(userService.getBookLoreUser(id));
|
||||||
|
}
|
||||||
|
|
||||||
@GetMapping
|
@GetMapping
|
||||||
|
@PreAuthorize("hasRole('ADMIN')")
|
||||||
public ResponseEntity<List<BookLoreUser>> getAllUsers() {
|
public ResponseEntity<List<BookLoreUser>> getAllUsers() {
|
||||||
return ResponseEntity.ok(userService.getBookLoreUsers());
|
return ResponseEntity.ok(userService.getBookLoreUsers());
|
||||||
}
|
}
|
||||||
|
|
||||||
@PutMapping("/{id}")
|
@PutMapping("/{id}")
|
||||||
|
@PreAuthorize("hasRole('ADMIN')")
|
||||||
public ResponseEntity<BookLoreUser> updateUser(@PathVariable Long id, @Valid @RequestBody UserUpdateRequest updateRequest) {
|
public ResponseEntity<BookLoreUser> updateUser(@PathVariable Long id, @Valid @RequestBody UserUpdateRequest updateRequest) {
|
||||||
BookLoreUser updatedUser = userService.updateUser(id, updateRequest);
|
BookLoreUser updatedUser = userService.updateUser(id, updateRequest);
|
||||||
return ResponseEntity.ok(updatedUser);
|
return ResponseEntity.ok(updatedUser);
|
||||||
|
|||||||
+7
@@ -5,6 +5,7 @@ import lombok.extern.slf4j.Slf4j;
|
|||||||
import org.springframework.dao.DataIntegrityViolationException;
|
import org.springframework.dao.DataIntegrityViolationException;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.security.access.AccessDeniedException;
|
||||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||||
@@ -51,6 +52,12 @@ public class GlobalExceptionHandler {
|
|||||||
return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
|
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)
|
@ExceptionHandler(Exception.class)
|
||||||
public ResponseEntity<ErrorResponse> handleGenericException(Exception ex) {
|
public ResponseEntity<ErrorResponse> handleGenericException(Exception ex) {
|
||||||
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), "An unexpected error occurred.");
|
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), "An unexpected error occurred.");
|
||||||
|
|||||||
@@ -17,8 +17,11 @@ public interface BookLoreUserMapper {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
BookLoreUser.UserPermissions dto = new BookLoreUser.UserPermissions();
|
BookLoreUser.UserPermissions dto = new BookLoreUser.UserPermissions();
|
||||||
|
dto.setAdmin(permissions.isPermissionAdmin());
|
||||||
dto.setCanUpload(permissions.isPermissionUpload());
|
dto.setCanUpload(permissions.isPermissionUpload());
|
||||||
dto.setCanDownload(permissions.isPermissionDownload());
|
dto.setCanDownload(permissions.isPermissionDownload());
|
||||||
|
dto.setCanManipulateLibrary(permissions.isPermissionManipulateLibrary());
|
||||||
|
dto.setCanEditMetadata(permissions.isPermissionEditMetadata());
|
||||||
dto.setCanEditMetadata(permissions.isPermissionEditMetadata());
|
dto.setCanEditMetadata(permissions.isPermissionEditMetadata());
|
||||||
return dto;
|
return dto;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,8 +12,10 @@ public class BookLoreUser {
|
|||||||
|
|
||||||
@Data
|
@Data
|
||||||
public static class UserPermissions {
|
public static class UserPermissions {
|
||||||
|
private boolean isAdmin;
|
||||||
private boolean canUpload;
|
private boolean canUpload;
|
||||||
private boolean canDownload;
|
private boolean canDownload;
|
||||||
private boolean canEditMetadata;
|
private boolean canEditMetadata;
|
||||||
|
private boolean canManipulateLibrary;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,4 +12,5 @@ public class UserCreateRequest {
|
|||||||
private boolean permissionUpload;
|
private boolean permissionUpload;
|
||||||
private boolean permissionDownload;
|
private boolean permissionDownload;
|
||||||
private boolean permissionEditMetadata;
|
private boolean permissionEditMetadata;
|
||||||
|
private boolean permissionManipulateLibrary;
|
||||||
}
|
}
|
||||||
+3
@@ -29,6 +29,9 @@ public class UserPermissionsEntity {
|
|||||||
@Column(name = "permission_edit_metadata", nullable = false)
|
@Column(name = "permission_edit_metadata", nullable = false)
|
||||||
private boolean permissionEditMetadata = false;
|
private boolean permissionEditMetadata = false;
|
||||||
|
|
||||||
|
@Column(name = "permission_manipulate_library", nullable = false)
|
||||||
|
private boolean permissionManipulateLibrary = false;
|
||||||
|
|
||||||
@Column(name = "permission_admin", nullable = false)
|
@Column(name = "permission_admin", nullable = false)
|
||||||
private boolean permissionAdmin;
|
private boolean permissionAdmin;
|
||||||
}
|
}
|
||||||
@@ -50,6 +50,7 @@ public class UserService {
|
|||||||
permissions.setPermissionUpload(request.isPermissionUpload());
|
permissions.setPermissionUpload(request.isPermissionUpload());
|
||||||
permissions.setPermissionDownload(request.isPermissionDownload());
|
permissions.setPermissionDownload(request.isPermissionDownload());
|
||||||
permissions.setPermissionEditMetadata(request.isPermissionEditMetadata());
|
permissions.setPermissionEditMetadata(request.isPermissionEditMetadata());
|
||||||
|
permissions.setPermissionEditMetadata(request.isPermissionManipulateLibrary());
|
||||||
|
|
||||||
bookLoreUserEntity.setPermissions(permissions);
|
bookLoreUserEntity.setPermissions(permissions);
|
||||||
|
|
||||||
@@ -64,8 +65,7 @@ public class UserService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public ResponseEntity<Map<String, String>> loginUser(UserLoginRequest loginRequest) {
|
public ResponseEntity<Map<String, String>> loginUser(UserLoginRequest loginRequest) {
|
||||||
BookLoreUserEntity user = userRepository.findByUsername(loginRequest.getUsername())
|
BookLoreUserEntity user = userRepository.findByUsername(loginRequest.getUsername()).orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(loginRequest.getUsername()));
|
||||||
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(loginRequest.getUsername()));
|
|
||||||
|
|
||||||
if (!passwordEncoder.matches(loginRequest.getPassword(), user.getPasswordHash())) {
|
if (!passwordEncoder.matches(loginRequest.getPassword(), user.getPasswordHash())) {
|
||||||
throw ApiError.INVALID_CREDENTIALS.createException();
|
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
|
CREATE TABLE IF NOT EXISTS user_permissions
|
||||||
(
|
(
|
||||||
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||||||
user_id BIGINT NOT NULL,
|
user_id BIGINT NOT NULL,
|
||||||
permission_upload BOOLEAN NOT NULL DEFAULT FALSE,
|
permission_upload BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
permission_download BOOLEAN NOT NULL DEFAULT FALSE,
|
permission_download BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
permission_edit_metadata BOOLEAN NOT NULL DEFAULT FALSE,
|
permission_edit_metadata BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
permission_admin 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
|
CONSTRAINT fk_user_permissions_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
Generated
+10
@@ -21,6 +21,7 @@
|
|||||||
"@stomp/rx-stomp": "^2.0.0",
|
"@stomp/rx-stomp": "^2.0.0",
|
||||||
"@stomp/stompjs": "^7.0.0",
|
"@stomp/stompjs": "^7.0.0",
|
||||||
"epubjs": "^0.3.93",
|
"epubjs": "^0.3.93",
|
||||||
|
"jwt-decode": "^4.0.0",
|
||||||
"ng-lazyload-image": "^9.1.3",
|
"ng-lazyload-image": "^9.1.3",
|
||||||
"ngx-extended-pdf-viewer": "23.0.0-alpha.1",
|
"ngx-extended-pdf-viewer": "23.0.0-alpha.1",
|
||||||
"ngx-infinite-scroll": "^19.0.0",
|
"ngx-infinite-scroll": "^19.0.0",
|
||||||
@@ -10737,6 +10738,15 @@
|
|||||||
"safe-buffer": "~5.1.0"
|
"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": {
|
"node_modules/karma": {
|
||||||
"version": "6.4.4",
|
"version": "6.4.4",
|
||||||
"resolved": "https://registry.npmjs.org/karma/-/karma-6.4.4.tgz",
|
"resolved": "https://registry.npmjs.org/karma/-/karma-6.4.4.tgz",
|
||||||
|
|||||||
@@ -24,6 +24,7 @@
|
|||||||
"@stomp/rx-stomp": "^2.0.0",
|
"@stomp/rx-stomp": "^2.0.0",
|
||||||
"@stomp/stompjs": "^7.0.0",
|
"@stomp/stompjs": "^7.0.0",
|
||||||
"epubjs": "^0.3.93",
|
"epubjs": "^0.3.93",
|
||||||
|
"jwt-decode": "^4.0.0",
|
||||||
"ng-lazyload-image": "^9.1.3",
|
"ng-lazyload-image": "^9.1.3",
|
||||||
"ngx-extended-pdf-viewer": "23.0.0-alpha.1",
|
"ngx-extended-pdf-viewer": "23.0.0-alpha.1",
|
||||||
"ngx-infinite-scroll": "^19.0.0",
|
"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">
|
<p *ngIf="entityType === EntityType.ALL_BOOKS" class="text-2xl whitespace-nowrap overflow-hidden text-ellipsis">
|
||||||
All Books
|
All Books
|
||||||
</p>
|
</p>
|
||||||
<div *ngIf="entityType !== EntityType.ALL_BOOKS">
|
<div *ngIf="userService.userData$ | async as userData">
|
||||||
<p-button icon="pi pi-ellipsis-v" [rounded]="true" [text]="true" severity="info" (click)="entitymenu.toggle($event)"></p-button>
|
<div *ngIf="entityType !== EntityType.ALL_BOOKS && userData.permissions.canManipulateLibrary">
|
||||||
<p-menu #entitymenu [model]="entityOptions" [popup]="true" appendTo="body"></p-menu>
|
<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>
|
</div>
|
||||||
</ng-container>
|
</ng-container>
|
||||||
</div>
|
</div>
|
||||||
@@ -134,11 +136,13 @@
|
|||||||
severity="info"
|
severity="info"
|
||||||
(click)="unshelfBooks()">
|
(click)="unshelfBooks()">
|
||||||
</p-button>
|
</p-button>
|
||||||
<p-button
|
<div *ngIf="userService.userData$ | async as userData">
|
||||||
label="Refresh Metadata"
|
<p-button *ngIf="userData.permissions.canEditMetadata"
|
||||||
severity="info"
|
label="Refresh Metadata"
|
||||||
(click)="updateMetadata()">
|
severity="info"
|
||||||
</p-button>
|
(click)="updateMetadata()">
|
||||||
|
</p-button>
|
||||||
|
</div>
|
||||||
<p-button
|
<p-button
|
||||||
label="Deselect All"
|
label="Deselect All"
|
||||||
severity="warn"
|
severity="warn"
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ import {FormsModule} from '@angular/forms';
|
|||||||
import {BookFilterComponent} from './book-filter/book-filter.component';
|
import {BookFilterComponent} from './book-filter/book-filter.component';
|
||||||
import {Tooltip} from 'primeng/tooltip';
|
import {Tooltip} from 'primeng/tooltip';
|
||||||
import {Fluid} from 'primeng/fluid';
|
import {Fluid} from 'primeng/fluid';
|
||||||
|
import {UserService} from '../../../user.service';
|
||||||
|
|
||||||
export enum EntityType {
|
export enum EntityType {
|
||||||
LIBRARY = 'Library',
|
LIBRARY = 'Library',
|
||||||
@@ -89,6 +90,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
|
|||||||
private shelfService = inject(ShelfService);
|
private shelfService = inject(ShelfService);
|
||||||
private dialogService = inject(DialogService);
|
private dialogService = inject(DialogService);
|
||||||
private sortService = inject(SortService);
|
private sortService = inject(SortService);
|
||||||
|
protected userService = inject(UserService);
|
||||||
private libraryShelfMenuService = inject(LibraryShelfMenuService);
|
private libraryShelfMenuService = inject(LibraryShelfMenuService);
|
||||||
|
|
||||||
sortOptions: any[] = [
|
sortOptions: any[] = [
|
||||||
@@ -249,7 +251,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
|
|||||||
default:
|
default:
|
||||||
break;
|
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 {UrlHelperService} from '../../../../utilities/service/url-helper.service';
|
||||||
import {AsyncPipe, NgIf} from '@angular/common';
|
import {AsyncPipe, NgIf} from '@angular/common';
|
||||||
import {SecurePipe} from '../../../../secure-pipe';
|
import {SecurePipe} from '../../../../secure-pipe';
|
||||||
|
import {UserService} from '../../../../user.service';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-book-card',
|
selector: 'app-book-card',
|
||||||
templateUrl: './book-card.component.html',
|
templateUrl: './book-card.component.html',
|
||||||
styleUrls: ['./book-card.component.scss'],
|
styleUrls: ['./book-card.component.scss'],
|
||||||
imports: [Button, MenuModule, CheckboxModule, FormsModule, NgIf, AsyncPipe, SecurePipe],
|
imports: [Button, MenuModule, CheckboxModule, FormsModule, NgIf, SecurePipe, AsyncPipe],
|
||||||
standalone: true
|
standalone: true
|
||||||
})
|
})
|
||||||
export class BookCardComponent implements OnInit {
|
export class BookCardComponent implements OnInit {
|
||||||
@@ -37,9 +37,15 @@ export class BookCardComponent implements OnInit {
|
|||||||
private dialogService = inject(DialogService);
|
private dialogService = inject(DialogService);
|
||||||
private metadataDialogService = inject(MetadataDialogService);
|
private metadataDialogService = inject(MetadataDialogService);
|
||||||
protected urlHelper = inject(UrlHelperService);
|
protected urlHelper = inject(UrlHelperService);
|
||||||
|
private userService = inject(UserService);
|
||||||
|
|
||||||
|
private userPermissions: any;
|
||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
this.initMenu();
|
this.initMenu();
|
||||||
|
this.userService.userData$.subscribe((userData) => {
|
||||||
|
this.userPermissions = userData?.permissions;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
readBook(book: Book): void {
|
readBook(book: Book): void {
|
||||||
@@ -63,7 +69,7 @@ export class BookCardComponent implements OnInit {
|
|||||||
{
|
{
|
||||||
label: 'Assign Shelves',
|
label: 'Assign Shelves',
|
||||||
icon: 'pi pi-folder',
|
icon: 'pi pi-folder',
|
||||||
command: () => this.openShelfDialog(this.book),
|
command: () => this.openShelfDialog()
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: 'View Details',
|
label: 'View Details',
|
||||||
@@ -74,6 +80,7 @@ export class BookCardComponent implements OnInit {
|
|||||||
label: 'Match Book',
|
label: 'Match Book',
|
||||||
icon: 'pi pi-sparkles',
|
icon: 'pi pi-sparkles',
|
||||||
command: () => this.metadataDialogService.openBookMetadataCenterDialog(this.book.id, 'match'),
|
command: () => this.metadataDialogService.openBookMetadataCenterDialog(this.book.id, 'match'),
|
||||||
|
disabled: !this.hasEditMetadataPermission()
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: 'Quick Refresh',
|
label: 'Quick Refresh',
|
||||||
@@ -82,10 +89,11 @@ export class BookCardComponent implements OnInit {
|
|||||||
const metadataRefreshRequest: MetadataRefreshRequest = {
|
const metadataRefreshRequest: MetadataRefreshRequest = {
|
||||||
quick: true,
|
quick: true,
|
||||||
refreshType: MetadataRefreshType.BOOKS,
|
refreshType: MetadataRefreshType.BOOKS,
|
||||||
bookIds: [this.book.id]
|
bookIds: [this.book.id],
|
||||||
};
|
};
|
||||||
this.bookService.autoRefreshMetadata(metadataRefreshRequest).subscribe();
|
this.bookService.autoRefreshMetadata(metadataRefreshRequest).subscribe();
|
||||||
},
|
},
|
||||||
|
disabled: !this.hasEditMetadataPermission()
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: 'Granular Refresh',
|
label: 'Granular Refresh',
|
||||||
@@ -97,24 +105,26 @@ export class BookCardComponent implements OnInit {
|
|||||||
closable: true,
|
closable: true,
|
||||||
data: {
|
data: {
|
||||||
bookIds: [this.book!.id],
|
bookIds: [this.book!.id],
|
||||||
metadataRefreshType: MetadataRefreshType.BOOKS
|
metadataRefreshType: MetadataRefreshType.BOOKS,
|
||||||
}
|
},
|
||||||
})
|
});
|
||||||
},
|
},
|
||||||
|
disabled: !this.hasEditMetadataPermission()
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: 'Download',
|
label: 'Download',
|
||||||
icon: 'pi pi-download',
|
icon: 'pi pi-download',
|
||||||
command: () => {
|
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, {
|
this.dialogService.open(ShelfAssignerComponent, {
|
||||||
header: `Update Book's Shelves`,
|
header: `Update Book's Shelves`,
|
||||||
modal: true,
|
modal: true,
|
||||||
@@ -126,7 +136,7 @@ export class BookCardComponent implements OnInit {
|
|||||||
top: '15%',
|
top: '15%',
|
||||||
},
|
},
|
||||||
data: {
|
data: {
|
||||||
book: this.book
|
book: this.book,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -134,4 +144,12 @@ export class BookCardComponent implements OnInit {
|
|||||||
openBookInfo(book: Book): void {
|
openBookInfo(book: Book): void {
|
||||||
this.metadataDialogService.openBookMetadataCenterDialog(book.id, 'view');
|
this.metadataDialogService.openBookMetadataCenterDialog(book.id, 'view');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private hasEditMetadataPermission(): boolean {
|
||||||
|
return this.userPermissions?.canEditMetadata ?? false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private hasDownloadPermission(): boolean {
|
||||||
|
return this.userPermissions?.canDownload ?? false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -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 class="text-3xl font-semibold">Preferences</p>
|
||||||
<p-divider></p-divider>
|
<p-divider></p-divider>
|
||||||
|
|
||||||
|
|||||||
-1
@@ -65,7 +65,6 @@ export class BookPreferences implements OnInit {
|
|||||||
if (settings) {
|
if (settings) {
|
||||||
this.populateSettings(settings);
|
this.populateSettings(settings);
|
||||||
this.currentMetadataOptions = settings.metadataRefreshOptions;
|
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-tabs value="0">
|
||||||
<p-tablist>
|
<p-tablist>
|
||||||
<p-tab value="0">Book Preferences</p-tab>
|
<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-tablist>
|
||||||
|
|
||||||
<p-tabpanels>
|
<p-tabpanels>
|
||||||
<p-tabpanel value="0">
|
<p-tabpanel value="0">
|
||||||
<app-book-preferences></app-book-preferences>
|
<app-book-preferences></app-book-preferences>
|
||||||
</p-tabpanel>
|
</p-tabpanel>
|
||||||
<p-tabpanel value="1">
|
<ng-container *ngIf="userData.permissions.isAdmin">
|
||||||
<app-admin></app-admin>
|
<p-tabpanel value="1">
|
||||||
</p-tabpanel>
|
<app-admin></app-admin>
|
||||||
|
</p-tabpanel>
|
||||||
|
</ng-container>
|
||||||
</p-tabpanels>
|
</p-tabpanels>
|
||||||
</p-tabs>
|
</p-tabs>
|
||||||
</div>
|
</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 {Tab, TabList, TabPanel, TabPanels, Tabs} from 'primeng/tabs';
|
||||||
import {BookPreferences} from './book-preferences/book-preferences.component';
|
import {BookPreferences} from './book-preferences/book-preferences.component';
|
||||||
import {AdminComponent} from './admin/admin.component';
|
import {AdminComponent} from './admin/admin.component';
|
||||||
|
import {UserService} from '../../../user.service';
|
||||||
|
import {AsyncPipe, NgIf} from '@angular/common';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-settings',
|
selector: 'app-settings',
|
||||||
@@ -12,11 +14,15 @@ import {AdminComponent} from './admin/admin.component';
|
|||||||
TabPanels,
|
TabPanels,
|
||||||
TabPanel,
|
TabPanel,
|
||||||
BookPreferences,
|
BookPreferences,
|
||||||
AdminComponent
|
AdminComponent,
|
||||||
|
NgIf,
|
||||||
|
AsyncPipe
|
||||||
],
|
],
|
||||||
templateUrl: './settings.component.html',
|
templateUrl: './settings.component.html',
|
||||||
styleUrl: './settings.component.scss'
|
styleUrl: './settings.component.scss'
|
||||||
})
|
})
|
||||||
export class SettingsComponent {
|
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 { HttpClient } from '@angular/common/http';
|
||||||
import { Observable, tap } from 'rxjs';
|
import { Observable, tap } from 'rxjs';
|
||||||
import { RxStompService } from '../../shared/websocket/rx-stomp.service';
|
import { RxStompService } from '../../shared/websocket/rx-stomp.service';
|
||||||
import { createRxStompConfig } from '../../shared/websocket/rx-stomp.config';
|
|
||||||
|
|
||||||
@Injectable({
|
@Injectable({
|
||||||
providedIn: 'root',
|
providedIn: 'root',
|
||||||
@@ -11,14 +10,15 @@ export class AuthService {
|
|||||||
private apiUrl = 'http://localhost:7050/api/v1/auth/login';
|
private apiUrl = 'http://localhost:7050/api/v1/auth/login';
|
||||||
private rxStompService?: RxStompService;
|
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> {
|
login(credentials: { username: string; password: string }): Observable<any> {
|
||||||
return this.http.post<{ token: string }>(this.apiUrl, credentials).pipe(
|
return this.http.post<{ token: string }>(this.apiUrl, credentials).pipe(
|
||||||
tap((response) => {
|
tap((response) => {
|
||||||
if (response.token) {
|
if (response.token) {
|
||||||
this.saveToken(response.token);
|
this.saveToken(response.token);
|
||||||
this.startWebSocket();
|
this.getRxStompService().activate();
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
@@ -37,15 +37,6 @@ export class AuthService {
|
|||||||
this.getRxStompService().deactivate();
|
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 {
|
private getRxStompService(): RxStompService {
|
||||||
if (!this.rxStompService) {
|
if (!this.rxStompService) {
|
||||||
this.rxStompService = this.injector.get(RxStompService);
|
this.rxStompService = this.injector.get(RxStompService);
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
<ng-container>
|
<ng-container>
|
||||||
|
|
||||||
<div *ngIf="root && item.visible !== false" class="layout-menuitem-root-text">{{ item.label }}</div>
|
<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"
|
<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)"
|
<a *ngIf="(item.routerLink && !item.items) && item.visible !== false" (click)="itemClick($event)"
|
||||||
[ngClass]="item.class"
|
[ngClass]="item.class"
|
||||||
[routerLink]="item.routerLink" routerLinkActive="active-route"
|
[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"
|
[fragment]="item.fragment" [queryParamsHandling]="item.queryParamsHandling"
|
||||||
[preserveFragment]="item.preserveFragment"
|
[preserveFragment]="item.preserveFragment"
|
||||||
[skipLocationChange]="item.skipLocationChange" [replaceUrl]="item.replaceUrl" [state]="item.state"
|
[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>
|
<i class="pi pi-fw pi-angle-down layout-submenu-toggler" *ngIf="item.items"></i>
|
||||||
</a>
|
</a>
|
||||||
<span *ngIf="(item.routerLink && !item.items) && item.visible !== false">
|
<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
|
<p-button
|
||||||
(click)="entitymenu.toggle($event)"
|
(click)="entitymenu.toggle($event)"
|
||||||
(mouseover)="hovered = true"
|
(mouseover)="hovered = true"
|
||||||
@@ -46,9 +45,14 @@
|
|||||||
<p-menu #entitymenu [model]="item.menu" [popup]="true" appendTo="body"></p-menu>
|
<p-menu #entitymenu [model]="item.menu" [popup]="true" appendTo="body"></p-menu>
|
||||||
</ng-container>
|
</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'">
|
<ng-container *ngIf="item.type === 'All Books'">
|
||||||
<p
|
<p class="text-[var(--primary-color)] pr-1">
|
||||||
class="text-[var(--primary-color)] pr-1">
|
|
||||||
{{ (item.bookCount$ | async)?.toString() || '0' }}
|
{{ (item.bookCount$ | async)?.toString() || '0' }}
|
||||||
</p>
|
</p>
|
||||||
</ng-container>
|
</ng-container>
|
||||||
|
|||||||
@@ -9,11 +9,12 @@ import {Ripple} from 'primeng/ripple';
|
|||||||
import {Button} from 'primeng/button';
|
import {Button} from 'primeng/button';
|
||||||
import {Menu} from 'primeng/menu';
|
import {Menu} from 'primeng/menu';
|
||||||
import {MenuItem} from 'primeng/api';
|
import {MenuItem} from 'primeng/api';
|
||||||
|
import {UserService} from '../../../user.service';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: '[app-menuitem]',
|
selector: '[app-menuitem]',
|
||||||
templateUrl: './app.menuitem.component.html',
|
templateUrl: './app.menuitem.component.html',
|
||||||
styleUrl: './app.menuitem.component.scss',
|
styleUrls: ['./app.menuitem.component.scss'],
|
||||||
imports: [
|
imports: [
|
||||||
RouterLink,
|
RouterLink,
|
||||||
RouterLinkActive,
|
RouterLinkActive,
|
||||||
@@ -44,13 +45,20 @@ export class AppMenuitemComponent implements OnInit, OnDestroy {
|
|||||||
@Input() parentKey!: string;
|
@Input() parentKey!: string;
|
||||||
|
|
||||||
hovered = false;
|
hovered = false;
|
||||||
|
|
||||||
active = false;
|
active = false;
|
||||||
menuSourceSubscription: Subscription;
|
|
||||||
menuResetSubscription: Subscription;
|
|
||||||
key: string = "";
|
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 => {
|
this.menuSourceSubscription = this.menuService.menuSource$.subscribe(value => {
|
||||||
Promise.resolve(null).then(() => {
|
Promise.resolve(null).then(() => {
|
||||||
if (value.routeEvent) {
|
if (value.routeEvent) {
|
||||||
|
|||||||
@@ -21,14 +21,14 @@
|
|||||||
<app-book-searcher></app-book-searcher>
|
<app-book-searcher></app-book-searcher>
|
||||||
<ul class="topbar-items pl-6">
|
<ul class="topbar-items pl-6">
|
||||||
<div class="flex gap-6">
|
<div class="flex gap-6">
|
||||||
<li>
|
<li *ngIf="userService.userData$ | async as userData">
|
||||||
<a class="topbar-item">
|
<a class="topbar-item" *ngIf="userData.permissions.canManipulateLibrary">
|
||||||
<i class="pi pi-plus-circle text-surface-700 dark:text-surface-100" (click)="openLibraryCreatorDialog()"
|
<i class="pi pi-plus-circle text-surface-700 dark:text-surface-100" (click)="openLibraryCreatorDialog()"
|
||||||
pTooltip="Create New Library" tooltipPosition="top"></i>
|
pTooltip="Create New Library" tooltipPosition="top"></i>
|
||||||
</a>
|
</a>
|
||||||
</li>
|
</li>
|
||||||
<li>
|
<li *ngIf="userService.userData$ | async as userData">
|
||||||
<a class="topbar-item">
|
<a class="topbar-item" *ngIf="userData.permissions.canUpload">
|
||||||
<i class="pi pi-upload text-surface-700 dark:text-surface-100" (click)="openFileUploadDialog()"
|
<i class="pi pi-upload text-surface-700 dark:text-surface-100" (click)="openFileUploadDialog()"
|
||||||
pTooltip="Upload Book" tooltipPosition="top"></i>
|
pTooltip="Upload Book" tooltipPosition="top"></i>
|
||||||
</a>
|
</a>
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import {TooltipModule} from 'primeng/tooltip';
|
|||||||
import {FormsModule} from '@angular/forms';
|
import {FormsModule} from '@angular/forms';
|
||||||
import {InputTextModule} from 'primeng/inputtext';
|
import {InputTextModule} from 'primeng/inputtext';
|
||||||
import {BookSearcherComponent} from '../../../book/components/book-searcher/book-searcher.component';
|
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 {EventService} from '../../../shared/websocket/event.service';
|
||||||
import {Button} from 'primeng/button';
|
import {Button} from 'primeng/button';
|
||||||
import {StyleClass} from 'primeng/styleclass';
|
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 {LiveNotificationBoxComponent} from '../../../core/component/live-notification-box/live-notification-box.component';
|
||||||
import {BookUploaderComponent} from '../../../utilities/component/book-uploader/book-uploader.component';
|
import {BookUploaderComponent} from '../../../utilities/component/book-uploader/book-uploader.component';
|
||||||
import {AuthService} from '../../../core/service/auth.service';
|
import {AuthService} from '../../../core/service/auth.service';
|
||||||
|
import {UserService} from '../../../user.service';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-topbar',
|
selector: 'app-topbar',
|
||||||
@@ -34,7 +35,8 @@ import {AuthService} from '../../../core/service/auth.service';
|
|||||||
NgClass,
|
NgClass,
|
||||||
Divider,
|
Divider,
|
||||||
LiveNotificationBoxComponent,
|
LiveNotificationBoxComponent,
|
||||||
NgIf
|
NgIf,
|
||||||
|
AsyncPipe
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
export class AppTopBarComponent implements OnDestroy {
|
export class AppTopBarComponent implements OnDestroy {
|
||||||
@@ -50,7 +52,8 @@ export class AppTopBarComponent implements OnDestroy {
|
|||||||
@ViewChild('topbarmenu') menu!: ElementRef;
|
@ViewChild('topbarmenu') menu!: ElementRef;
|
||||||
|
|
||||||
constructor(public layoutService: LayoutService, public dialogService: PrimeDialogService,
|
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.eventService.eventHighlight$.subscribe(highlight => {
|
||||||
this.eventHighlight = highlight;
|
this.eventHighlight = highlight;
|
||||||
});
|
});
|
||||||
|
|||||||
+4
-5
@@ -1,19 +1,18 @@
|
|||||||
<p-tabs [value]="tab" lazy="true" style="height: 100%; overflow: hidden;">
|
<p-tabs [value]="tab" lazy="true" style="height: 100%; overflow: hidden;">
|
||||||
<p-tablist>
|
<p-tablist>
|
||||||
<p-tab value="view">Book Details</p-tab>
|
<p-tab value="view">Book Details</p-tab>
|
||||||
<p-tab value="edit">Edit Details</p-tab>
|
<p-tab *ngIf="canEditMetadata" value="edit">Edit Details</p-tab>
|
||||||
<p-tab value="match">Match Book</p-tab>
|
<p-tab *ngIf="canEditMetadata" value="match">Match Book</p-tab>
|
||||||
</p-tablist>
|
</p-tablist>
|
||||||
<p-tabpanels style="height: 100%; overflow: hidden; padding-bottom: 0">
|
<p-tabpanels style="height: 100%; overflow: hidden; padding-bottom: 0">
|
||||||
<p-tabpanel value="view" style="height: 100%; overflow: hidden;">
|
<p-tabpanel value="view" style="height: 100%; overflow: hidden;">
|
||||||
<app-metadata-viewer></app-metadata-viewer>
|
<app-metadata-viewer></app-metadata-viewer>
|
||||||
</p-tabpanel>
|
</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>
|
<app-metadata-editor></app-metadata-editor>
|
||||||
</p-tabpanel>
|
</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>
|
<app-metadata-searcher></app-metadata-searcher>
|
||||||
</p-tabpanel>
|
</p-tabpanel>
|
||||||
</p-tabpanels>
|
</p-tabpanels>
|
||||||
</p-tabs>
|
</p-tabs>
|
||||||
|
|
||||||
|
|||||||
+25
-4
@@ -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 {Tab, TabList, TabPanel, TabPanels, Tabs} from 'primeng/tabs';
|
||||||
import {MetadataEditorComponent} from './metadata-editor/metadata-editor.component';
|
import {MetadataEditorComponent} from './metadata-editor/metadata-editor.component';
|
||||||
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||||
import {MetadataSearcherComponent} from './metadata-searcher/metadata-searcher.component';
|
import {MetadataSearcherComponent} from './metadata-searcher/metadata-searcher.component';
|
||||||
import {BookMetadataCenterService} from './book-metadata-center.service';
|
import {BookMetadataCenterService} from './book-metadata-center.service';
|
||||||
import {MetadataViewerComponent} from './metadata-viewer/metadata-viewer.component';
|
import {MetadataViewerComponent} from './metadata-viewer/metadata-viewer.component';
|
||||||
|
import {UserService} from '../../user.service';
|
||||||
|
import {Subscription} from 'rxjs';
|
||||||
|
import {NgIf} from '@angular/common';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-book-metadata-center',
|
selector: 'app-book-metadata-center',
|
||||||
standalone: true,
|
standalone: true,
|
||||||
templateUrl: './book-metadata-center.component.html',
|
templateUrl: './book-metadata-center.component.html',
|
||||||
styleUrl: './book-metadata-center.component.scss',
|
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 dynamicDialogConfig = inject(DynamicDialogConfig);
|
||||||
private dynamicDialogRef = inject(DynamicDialogRef);
|
private dynamicDialogRef = inject(DynamicDialogRef);
|
||||||
private metadataCenterService = inject(BookMetadataCenterService);
|
private metadataCenterService = inject(BookMetadataCenterService);
|
||||||
|
private userService = inject(UserService);
|
||||||
|
|
||||||
tab = 'view';
|
tab = 'view';
|
||||||
|
canEditMetadata: boolean = false;
|
||||||
|
private userSubscription: Subscription = Subscription.EMPTY;
|
||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
const book = this.dynamicDialogConfig.data.book;
|
const book = this.dynamicDialogConfig.data.book;
|
||||||
this.tab = this.dynamicDialogConfig.data.tab;
|
this.tab = this.dynamicDialogConfig.data.tab;
|
||||||
|
|
||||||
if (book?.metadata) {
|
if (book?.metadata) {
|
||||||
this.metadataCenterService.emit(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) => {
|
this.metadataCenterService.dialogClose$.subscribe((close) => {
|
||||||
if (close) {
|
if (close) {
|
||||||
this.metadataCenterService.closeDialog(false);
|
this.metadataCenterService.closeDialog(false);
|
||||||
this.dynamicDialogRef.close();
|
this.dynamicDialogRef.close();
|
||||||
}
|
}
|
||||||
})
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
ngOnDestroy(): void {
|
||||||
|
// Clean up subscription to prevent memory leaks
|
||||||
|
if (this.userSubscription) {
|
||||||
|
this.userSubscription.unsubscribe();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,27 +1,9 @@
|
|||||||
import {inject, Injectable} from '@angular/core';
|
import {inject, Injectable, Injector} from '@angular/core';
|
||||||
import {HttpClient} from '@angular/common/http';
|
import {HttpClient} from '@angular/common/http';
|
||||||
import {Observable} from 'rxjs';
|
import {BehaviorSubject, Observable} from 'rxjs';
|
||||||
import {API_CONFIG} from './config/api-config';
|
import {API_CONFIG} from './config/api-config';
|
||||||
|
import {jwtDecode} from 'jwt-decode';
|
||||||
interface UserCreateRequest {
|
import {RxStompService} from './shared/websocket/rx-stomp.service';
|
||||||
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;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface User {
|
export interface User {
|
||||||
id: number;
|
id: number;
|
||||||
@@ -29,23 +11,54 @@ export interface User {
|
|||||||
name: string;
|
name: string;
|
||||||
email: string;
|
email: string;
|
||||||
permissions: {
|
permissions: {
|
||||||
|
isAdmin: boolean;
|
||||||
canUpload: boolean;
|
canUpload: boolean;
|
||||||
canDownload: boolean;
|
canDownload: boolean;
|
||||||
canEditMetadata: boolean;
|
canEditMetadata: boolean;
|
||||||
|
canManipulateLibrary: boolean;
|
||||||
};
|
};
|
||||||
isEditing?: boolean;
|
}
|
||||||
|
|
||||||
|
interface JwtPayload {
|
||||||
|
sub: string;
|
||||||
|
userId: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Injectable({
|
@Injectable({
|
||||||
providedIn: 'root'
|
providedIn: 'root'
|
||||||
})
|
})
|
||||||
export class UserService {
|
export class UserService {
|
||||||
|
|
||||||
private http = inject(HttpClient);
|
|
||||||
private readonly apiUrl = `${API_CONFIG.BASE_URL}/api/v1/auth/register`;
|
private readonly apiUrl = `${API_CONFIG.BASE_URL}/api/v1/auth/register`;
|
||||||
private readonly userUrl = `${API_CONFIG.BASE_URL}/api/v1/users`;
|
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);
|
return this.http.post<{ message: string }>(this.apiUrl, userData);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -53,7 +66,7 @@ export class UserService {
|
|||||||
return this.http.get<User[]>(this.userUrl);
|
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);
|
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}`);
|
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');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user